processing_colpali.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/colpali/modular_colpali.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_colpali.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2024 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, make_flat_list_of_images
  23. from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
  24. from ...tokenization_utils_base import AddedToken, PreTokenizedInput, TextInput
  25. from ...utils import auto_docstring, is_torch_available
  26. if is_torch_available():
  27. import torch
  28. class ColPaliProcessorKwargs(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. IMAGE_TOKEN = "<image>"
  40. EXTRA_TOKENS = [f"<loc{i:0>4}>" for i in range(1024)] + [f"<seg{i:0>3}>" for i in range(128)]
  41. def build_string_from_input(prompt, bos_token, image_seq_len, image_token, num_images):
  42. """
  43. Builds a string from the input prompt and image tokens.
  44. For example, for the call:
  45. build_string_from_input(
  46. prompt="Prefix str"
  47. bos_token="<s>",
  48. image_seq_len=3,
  49. image_token="<im>",
  50. )
  51. The output will be:
  52. "<im><im><im><s>Initial str"
  53. Args:
  54. prompt (`list[Union[str, ImageInput]]`): The input prompt.
  55. bos_token (`str`): The beginning of sentence token.
  56. image_seq_len (`int`): The length of the image sequence.
  57. image_token (`str`): The image token.
  58. num_images (`int`): Number of images in the prompt.
  59. """
  60. return f"{image_token * image_seq_len * num_images}{bos_token}{prompt}\n"
  61. @auto_docstring
  62. class ColPaliProcessor(ProcessorMixin):
  63. def __init__(
  64. self,
  65. image_processor=None,
  66. tokenizer=None,
  67. chat_template=None,
  68. visual_prompt_prefix: str = "Describe the image.",
  69. query_prefix: str = "Question: ",
  70. ):
  71. r"""
  72. visual_prompt_prefix (`str`, *optional*, defaults to `"Describe the image."`):
  73. A string that gets tokenized and prepended to the image tokens.
  74. query_prefix (`str`, *optional*, defaults to `"Question: "`):
  75. A prefix to be used for the query.
  76. """
  77. self.visual_prompt_prefix = visual_prompt_prefix
  78. self.query_prefix = query_prefix
  79. if not hasattr(image_processor, "image_seq_length"):
  80. raise ValueError("Image processor is missing an `image_seq_length` attribute.")
  81. self.image_seq_length = image_processor.image_seq_length
  82. if not hasattr(tokenizer, "image_token"):
  83. image_token = AddedToken(IMAGE_TOKEN, normalized=False, special=True)
  84. tokens_to_add = {"additional_special_tokens": [image_token]}
  85. tokenizer.add_special_tokens(tokens_to_add)
  86. self.image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN)
  87. self.image_token = IMAGE_TOKEN
  88. else:
  89. self.image_token_id = tokenizer.image_token_id
  90. self.image_token = tokenizer.image_token
  91. tokenizer.add_tokens(EXTRA_TOKENS)
  92. tokenizer.add_bos_token = False
  93. tokenizer.add_eos_token = False
  94. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  95. @auto_docstring
  96. def __call__(
  97. self,
  98. images: ImageInput | None = None,
  99. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  100. **kwargs: Unpack[ColPaliProcessorKwargs],
  101. ) -> BatchFeature:
  102. r"""
  103. Returns:
  104. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  105. - **input_ids** -- List of token ids to be fed to a model.
  106. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  107. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  108. `None`).
  109. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  110. """
  111. output_kwargs = self._merge_kwargs(
  112. ColPaliProcessorKwargs,
  113. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  114. **kwargs,
  115. )
  116. suffix = output_kwargs["text_kwargs"].pop("suffix", None)
  117. return_token_type_ids = True
  118. if text is None and images is None:
  119. raise ValueError("Either text or images must be provided")
  120. if text is not None and images is not None:
  121. raise ValueError("Only one of text or images can be processed at a time")
  122. if images is not None:
  123. images = self.image_processor.fetch_images(images)
  124. images = make_flat_list_of_images(images)
  125. texts_doc = [self.visual_prompt_prefix] * len(images)
  126. images = [image.convert("RGB") for image in images]
  127. input_strings = [
  128. build_string_from_input(
  129. prompt=prompt,
  130. bos_token=self.tokenizer.bos_token,
  131. image_seq_len=self.image_seq_length,
  132. image_token=IMAGE_TOKEN,
  133. num_images=len(image_list) if isinstance(image_list, list) else 1,
  134. )
  135. for prompt, image_list in zip(texts_doc, images)
  136. ]
  137. pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])["pixel_values"]
  138. # max_length has to account for the image tokens
  139. if output_kwargs["text_kwargs"].get("max_length", None) is not None:
  140. output_kwargs["text_kwargs"]["max_length"] += self.image_seq_length
  141. inputs = self.tokenizer(
  142. input_strings,
  143. return_token_type_ids=return_token_type_ids,
  144. **output_kwargs["text_kwargs"],
  145. )
  146. return_data = {**inputs, "pixel_values": pixel_values}
  147. if return_token_type_ids:
  148. labels = inputs["input_ids"].masked_fill(inputs["token_type_ids"] == 0, -100)
  149. return_data.update({"labels": labels})
  150. return BatchFeature(data=return_data)
  151. elif text is not None:
  152. if isinstance(text, str):
  153. text = [text]
  154. elif not (isinstance(text, list) and isinstance(text[0], str)):
  155. raise ValueError("Text must be a string or a list of strings")
  156. if suffix is None:
  157. suffix = self.query_augmentation_token * 10
  158. texts_query: list[str] = []
  159. for query in text:
  160. query = self.tokenizer.bos_token + self.query_prefix + query + suffix + "\n"
  161. texts_query.append(query)
  162. output_kwargs["text_kwargs"]["max_length"] = output_kwargs["text_kwargs"].get("max_length", 50)
  163. batch_query = self.tokenizer(
  164. texts_query,
  165. return_token_type_ids=return_token_type_ids,
  166. **output_kwargs["text_kwargs"],
  167. )
  168. return batch_query
  169. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  170. """
  171. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  172. Args:
  173. image_sizes (list[list[str]], *optional*):
  174. The input sizes formatted as (height, width) per each image.
  175. Returns:
  176. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  177. input modalities, along with other useful data.
  178. """
  179. vision_data = {}
  180. if image_sizes is not None:
  181. num_image_tokens = [self.image_seq_length] * len(image_sizes)
  182. num_image_patches = [1] * len(image_sizes)
  183. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  184. return MultiModalData(**vision_data)
  185. @property
  186. def model_input_names(self):
  187. tokenizer_input_names = self.tokenizer.model_input_names + ["token_type_ids", "labels"]
  188. image_processor_input_names = self.image_processor.model_input_names
  189. return list(tokenizer_input_names + image_processor_input_names)
  190. @property
  191. def query_augmentation_token(self) -> str:
  192. """
  193. Return the query augmentation token.
  194. Query augmentation buffers are used as reasoning buffers during inference.
  195. """
  196. return self.tokenizer.pad_token
  197. def process_images(
  198. self,
  199. images: ImageInput | None = None,
  200. **kwargs: Unpack[ColPaliProcessorKwargs],
  201. ) -> BatchFeature:
  202. """
  203. Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColPaliProcessor's
  204. [`ColPaliProcessor.__call__`].
  205. This method forwards the `images` and `kwargs` arguments to the image processor.
  206. Args:
  207. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  208. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  209. tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
  210. number of channels, H and W are image height and width.
  211. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  212. If set, will return tensors of a particular framework. Acceptable values are:
  213. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  214. - `'np'`: Return NumPy `np.ndarray` objects.
  215. Returns:
  216. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  217. - **input_ids** -- List of token ids to be fed to a model.
  218. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  219. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  220. `None`).
  221. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  222. """
  223. return self.__call__(images=images, **kwargs)
  224. def process_queries(
  225. self,
  226. text: TextInput | list[TextInput],
  227. **kwargs: Unpack[ColPaliProcessorKwargs],
  228. ) -> BatchFeature:
  229. """
  230. Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColPaliProcessor's
  231. [`ColPaliProcessor.__call__`].
  232. This method forwards the `text` and `kwargs` arguments to the tokenizer.
  233. Args:
  234. text (`str`, `list[str]`, `list[list[str]]`):
  235. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  236. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  237. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  238. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  239. If set, will return tensors of a particular framework. Acceptable values are:
  240. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  241. - `'np'`: Return NumPy `np.ndarray` objects.
  242. Returns:
  243. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  244. - **input_ids** -- List of token ids to be fed to a model.
  245. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  246. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  247. `None`).
  248. """
  249. return self.__call__(text=text, **kwargs)
  250. def score_retrieval(
  251. self,
  252. query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
  253. passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
  254. batch_size: int = 128,
  255. output_dtype: Optional["torch.dtype"] = None,
  256. output_device: Union["torch.device", str] = "cpu",
  257. ) -> "torch.Tensor":
  258. """
  259. Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
  260. query embeddings (`qs`) and passage embeddings (`ps`). For ColPali, a passage is the
  261. image of a document page.
  262. Because the embedding tensors are multi-vector and can thus have different shapes, they
  263. should be fed as:
  264. (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
  265. (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
  266. obtained by padding the list of tensors.
  267. Args:
  268. query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
  269. passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
  270. batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
  271. output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
  272. If `None`, the dtype of the input embeddings is used.
  273. output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
  274. Returns:
  275. `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
  276. tensor is saved on the "cpu" device.
  277. """
  278. if len(query_embeddings) == 0:
  279. raise ValueError("No queries provided")
  280. if len(passage_embeddings) == 0:
  281. raise ValueError("No passages provided")
  282. if query_embeddings[0].device != passage_embeddings[0].device:
  283. raise ValueError("Queries and passages must be on the same device")
  284. if query_embeddings[0].dtype != passage_embeddings[0].dtype:
  285. raise ValueError("Queries and passages must have the same dtype")
  286. if output_dtype is None:
  287. output_dtype = query_embeddings[0].dtype
  288. scores: list[torch.Tensor] = []
  289. for i in range(0, len(query_embeddings), batch_size):
  290. batch_scores: list[torch.Tensor] = []
  291. batch_queries = torch.nn.utils.rnn.pad_sequence(
  292. query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
  293. )
  294. for j in range(0, len(passage_embeddings), batch_size):
  295. batch_passages = torch.nn.utils.rnn.pad_sequence(
  296. passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
  297. )
  298. batch_scores.append(
  299. torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
  300. )
  301. scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
  302. return torch.cat(scores, dim=0)
  303. __all__ = ["ColPaliProcessor"]