processing_colqwen2.py 16 KB

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