processing_colqwen2.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/colqwen2/modular_colqwen2.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_colqwen2.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2025 The HuggingFace Inc. team.
  9. #
  10. # Licensed under the Apache License, Version 2.0 (the "License");
  11. # you may not use this file except in compliance with the License.
  12. # You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing, software
  17. # distributed under the License is distributed on an "AS IS" BASIS,
  18. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. # See the License for the specific language governing permissions and
  20. # limitations under the License.
  21. from typing import Optional, Union
  22. from ...feature_extraction_utils import BatchFeature
  23. from ...image_utils import ImageInput, is_valid_image
  24. from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
  25. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  26. from ...utils import is_torch_available
  27. if is_torch_available():
  28. import torch
  29. class ColQwen2ProcessorKwargs(ProcessingKwargs, total=False):
  30. _defaults = {
  31. "text_kwargs": {
  32. "padding": "longest",
  33. },
  34. "images_kwargs": {
  35. "data_format": "channels_first",
  36. "do_convert_rgb": True,
  37. },
  38. "common_kwargs": {"return_tensors": "pt"},
  39. }
  40. class ColQwen2Processor(ProcessorMixin):
  41. r"""
  42. Constructs a ColQwen2 processor which wraps a Qwen2VLProcessor and special methods to process images and queries, as
  43. well as to compute the late-interaction retrieval score.
  44. [`ColQwen2Processor`] offers all the functionalities of [`Qwen2VLProcessor`]. See the [`~Qwen2VLProcessor.__call__`]
  45. for more information.
  46. Args:
  47. image_processor ([`Qwen2VLImageProcessor`], *optional*):
  48. The image processor is a required input.
  49. tokenizer ([`Qwen2TokenizerFast`], *optional*):
  50. The tokenizer is a required input.
  51. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  52. in a chat into a tokenizable string.
  53. visual_prompt_prefix (`str`, *optional*): A string that gets tokenized and prepended to the image tokens.
  54. query_prefix (`str`, *optional*): A prefix to be used for the query.
  55. """
  56. attributes = ["image_processor", "tokenizer"]
  57. image_processor_class = "AutoImageProcessor"
  58. tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
  59. def __init__(
  60. self,
  61. image_processor=None,
  62. tokenizer=None,
  63. chat_template=None,
  64. visual_prompt_prefix: Optional[str] = None,
  65. query_prefix: Optional[str] = None,
  66. **kwargs,
  67. ):
  68. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  69. self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
  70. self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
  71. if visual_prompt_prefix is None:
  72. visual_prompt_prefix = "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"
  73. self.visual_prompt_prefix = visual_prompt_prefix
  74. if query_prefix is None:
  75. query_prefix = "Query: "
  76. self.query_prefix = query_prefix
  77. def __call__(
  78. self,
  79. images: Optional[ImageInput] = None,
  80. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  81. audio=None,
  82. videos=None,
  83. **kwargs: Unpack[ColQwen2ProcessorKwargs],
  84. ) -> BatchFeature:
  85. """
  86. Main method to prepare for the model either (1) one or several texts, either (2) one or several image(s). This method is a custom
  87. wrapper around the Qwen2VLProcessor's [`~Qwen2VLProcessor.__call__`] method adapted for the ColQwen2 model. It cannot process
  88. both text and images at the same time.
  89. When preparing the the text(s), this method forwards the `text` and `kwargs` arguments to Qwen2TokenizerFast's
  90. [`~Qwen2TokenizerFast.__call__`].
  91. When preparing the the image(s), this method forwards the `images` and `kwargs` arguments to Qwen2VLImageProcessor's
  92. [`~Qwen2VLImageProcessor.__call__`].
  93. Please refer to the doctsring of the above two methods for more information.
  94. Args:
  95. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  96. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  97. tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
  98. number of channels, H and W are image height and width.
  99. text (`str`, `list[str]`, `list[list[str]]`):
  100. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  101. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  102. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  103. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  104. If set, will return tensors of a particular framework. Acceptable values are:
  105. - `'tf'`: Return TensorFlow `tf.constant` objects.
  106. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  107. - `'np'`: Return NumPy `np.ndarray` objects.
  108. - `'jax'`: Return JAX `jnp.ndarray` objects.
  109. Returns:
  110. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  111. - **input_ids** -- List of token ids to be fed to a model.
  112. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  113. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  114. `None`).
  115. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  116. """
  117. output_kwargs = self._merge_kwargs(
  118. ColQwen2ProcessorKwargs,
  119. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  120. **kwargs,
  121. )
  122. suffix = output_kwargs["text_kwargs"].pop("suffix", None)
  123. return_token_type_ids = suffix is not None
  124. if text is None and images is None:
  125. raise ValueError("Either text or images must be provided")
  126. if text is not None and images is not None:
  127. raise ValueError("Only one of text or images can be processed at a time")
  128. if images is not None:
  129. if is_valid_image(images):
  130. images = [images]
  131. elif isinstance(images, list) and is_valid_image(images[0]):
  132. pass
  133. elif not (isinstance(images, list) and isinstance(images[0], list) and is_valid_image(images[0][0])):
  134. raise ValueError("images must be an image, list of images or list of list of images")
  135. texts_doc = [self.visual_prompt_prefix] * len(images)
  136. image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
  137. image_grid_thw = image_inputs["image_grid_thw"]
  138. if image_grid_thw is not None:
  139. merge_length = self.image_processor.merge_size**2
  140. index = 0
  141. for i in range(len(texts_doc)):
  142. while self.image_token in texts_doc[i]:
  143. texts_doc[i] = texts_doc[i].replace(
  144. self.image_token, "<|placeholder|>" * (image_grid_thw[index].prod() // merge_length), 1
  145. )
  146. index += 1
  147. texts_doc[i] = texts_doc[i].replace("<|placeholder|>", self.image_token)
  148. text_inputs = self.tokenizer(
  149. texts_doc,
  150. return_token_type_ids=False,
  151. **output_kwargs["text_kwargs"],
  152. )
  153. return_data = BatchFeature(data={**text_inputs, **image_inputs})
  154. # NOTE: The following adjustment ensures correct behavior with DDP on multiple GPUs.
  155. offsets = return_data["image_grid_thw"][:, 1] * return_data["image_grid_thw"][:, 2] # (batch_size,)
  156. # Split the pixel_values tensor into a list of tensors, one per image
  157. pixel_values = list(
  158. torch.split(return_data["pixel_values"], offsets.tolist())
  159. ) # [(num_patches_image_0, pixel_values), ..., (num_patches_image_n, pixel_values)]
  160. # Pad the list of pixel_value tensors to the same length along the sequence dimension
  161. return_data["pixel_values"] = torch.nn.utils.rnn.pad_sequence(
  162. pixel_values, batch_first=True
  163. ) # (batch_size, max_num_patches, pixel_values)
  164. if return_token_type_ids:
  165. labels = return_data["input_ids"].masked_fill(return_data["token_type_ids"] == 0, -100)
  166. return_data.update({"labels": labels})
  167. return return_data
  168. elif text is not None:
  169. if isinstance(text, str):
  170. text = [text]
  171. elif not (isinstance(text, list) and isinstance(text[0], str)):
  172. raise ValueError("Text must be a string or a list of strings")
  173. if suffix is None:
  174. suffix = self.query_augmentation_token * 10
  175. texts_query: list[str] = []
  176. for query in text:
  177. augmented_query = self.query_prefix + query + suffix
  178. texts_query.append(augmented_query)
  179. batch_query = self.tokenizer(
  180. texts_query,
  181. return_token_type_ids=False,
  182. **output_kwargs["text_kwargs"],
  183. )
  184. return batch_query
  185. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  186. """
  187. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  188. Args:
  189. image_sizes (`list[list[int]]`, *optional*):
  190. The input sizes formatted as (height, width) per each image.
  191. Returns:
  192. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  193. input modalities, along with other useful data.
  194. """
  195. vision_data = {}
  196. if image_sizes is not None:
  197. images_kwargs = ColQwen2ProcessorKwargs._defaults.get("images_kwargs", {})
  198. images_kwargs.update(kwargs)
  199. merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
  200. num_image_patches = [
  201. self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
  202. for image_size in image_sizes
  203. ]
  204. num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
  205. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  206. return MultiModalData(**vision_data)
  207. @property
  208. def query_augmentation_token(self) -> str:
  209. """
  210. Return the query augmentation token.
  211. Query augmentation buffers are used as reasoning buffers during inference.
  212. """
  213. return self.tokenizer.pad_token
  214. def process_images(
  215. self,
  216. images: Optional[ImageInput] = None,
  217. **kwargs: Unpack[ColQwen2ProcessorKwargs],
  218. ) -> BatchFeature:
  219. """
  220. Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColQwen2Processor's
  221. [`ColQwen2Processor.__call__`].
  222. This method forwards the `images` and `kwargs` arguments to the image processor.
  223. Args:
  224. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  225. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  226. tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
  227. number of channels, H and W are image height and width.
  228. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  229. If set, will return tensors of a particular framework. Acceptable values are:
  230. - `'tf'`: Return TensorFlow `tf.constant` objects.
  231. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  232. - `'np'`: Return NumPy `np.ndarray` objects.
  233. - `'jax'`: Return JAX `jnp.ndarray` objects.
  234. Returns:
  235. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  236. - **input_ids** -- List of token ids to be fed to a model.
  237. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  238. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  239. `None`).
  240. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  241. """
  242. return self.__call__(images=images, **kwargs)
  243. def process_queries(
  244. self,
  245. text: Union[TextInput, list[TextInput]],
  246. **kwargs: Unpack[ColQwen2ProcessorKwargs],
  247. ) -> BatchFeature:
  248. """
  249. Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColQwen2Processor's
  250. [`ColQwen2Processor.__call__`].
  251. This method forwards the `text` and `kwargs` arguments to the tokenizer.
  252. Args:
  253. text (`str`, `list[str]`, `list[list[str]]`):
  254. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  255. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  256. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  257. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  258. If set, will return tensors of a particular framework. Acceptable values are:
  259. - `'tf'`: Return TensorFlow `tf.constant` objects.
  260. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  261. - `'np'`: Return NumPy `np.ndarray` objects.
  262. - `'jax'`: Return JAX `jnp.ndarray` objects.
  263. Returns:
  264. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  265. - **input_ids** -- List of token ids to be fed to a model.
  266. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  267. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  268. `None`).
  269. """
  270. return self.__call__(text=text, **kwargs)
  271. def score_retrieval(
  272. self,
  273. query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
  274. passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
  275. batch_size: int = 128,
  276. output_dtype: Optional["torch.dtype"] = None,
  277. output_device: Union["torch.device", str] = "cpu",
  278. ) -> "torch.Tensor":
  279. """
  280. Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
  281. query embeddings (`qs`) and passage embeddings (`ps`). For ColQwen2, a passage is the
  282. image of a document page.
  283. Because the embedding tensors are multi-vector and can thus have different shapes, they
  284. should be fed as:
  285. (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
  286. (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
  287. obtained by padding the list of tensors.
  288. Args:
  289. query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
  290. passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
  291. batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
  292. output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
  293. If `None`, the dtype of the input embeddings is used.
  294. output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
  295. Returns:
  296. `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
  297. tensor is saved on the "cpu" device.
  298. """
  299. if len(query_embeddings) == 0:
  300. raise ValueError("No queries provided")
  301. if len(passage_embeddings) == 0:
  302. raise ValueError("No passages provided")
  303. if query_embeddings[0].device != passage_embeddings[0].device:
  304. raise ValueError("Queries and passages must be on the same device")
  305. if query_embeddings[0].dtype != passage_embeddings[0].dtype:
  306. raise ValueError("Queries and passages must have the same dtype")
  307. if output_dtype is None:
  308. output_dtype = query_embeddings[0].dtype
  309. scores: list[torch.Tensor] = []
  310. for i in range(0, len(query_embeddings), batch_size):
  311. batch_scores: list[torch.Tensor] = []
  312. batch_queries = torch.nn.utils.rnn.pad_sequence(
  313. query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
  314. )
  315. for j in range(0, len(passage_embeddings), batch_size):
  316. batch_passages = torch.nn.utils.rnn.pad_sequence(
  317. passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
  318. )
  319. batch_scores.append(
  320. torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
  321. )
  322. scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
  323. return torch.cat(scores, dim=0)
  324. @property
  325. def model_input_names(self):
  326. tokenizer_input_names = self.tokenizer.model_input_names
  327. image_processor_input_names = self.image_processor.model_input_names
  328. # ColQwen doesn't process videos. Make a copy of list when removing
  329. # otherwise `self.feature_extractor.model_input_names` is also modified
  330. image_processor_input_names = [
  331. name for name in image_processor_input_names if name not in ["pixel_values_videos", "video_grid_thw"]
  332. ]
  333. return tokenizer_input_names + image_processor_input_names
  334. __all__ = ["ColQwen2Processor"]