modular_colpali.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. # coding=utf-8
  2. # Copyright 2024 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from typing import Optional, Union
  16. from transformers.models.paligemma.processing_paligemma import IMAGE_TOKEN, PaliGemmaProcessor, build_string_from_input
  17. from ...feature_extraction_utils import BatchFeature
  18. from ...image_utils import ImageInput, make_flat_list_of_images
  19. from ...processing_utils import ProcessingKwargs, Unpack
  20. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  21. from ...utils import is_torch_available, logging
  22. if is_torch_available():
  23. import torch
  24. logger = logging.get_logger(__name__)
  25. class ColPaliProcessorKwargs(ProcessingKwargs, total=False):
  26. _defaults = {
  27. "text_kwargs": {
  28. "padding": "longest",
  29. },
  30. "images_kwargs": {
  31. "data_format": "channels_first",
  32. "do_convert_rgb": True,
  33. },
  34. "common_kwargs": {"return_tensors": "pt"},
  35. }
  36. class ColPaliProcessor(PaliGemmaProcessor):
  37. r"""
  38. Constructs a ColPali processor which wraps a PaliGemmaProcessor and special methods to process images and queries, as
  39. well as to compute the late-interaction retrieval score.
  40. [`ColPaliProcessor`] offers all the functionalities of [`PaliGemmaProcessor`]. See the [`~PaliGemmaProcessor.__call__`]
  41. for more information.
  42. Args:
  43. image_processor ([`SiglipImageProcessor`], *optional*):
  44. The image processor is a required input.
  45. tokenizer ([`LlamaTokenizerFast`], *optional*):
  46. The tokenizer is a required input.
  47. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  48. in a chat into a tokenizable string.
  49. visual_prompt_prefix (`str`, *optional*, defaults to `"Describe the image."`):
  50. A string that gets tokenized and prepended to the image tokens.
  51. query_prefix (`str`, *optional*, defaults to `"Question: "`):
  52. A prefix to be used for the query.
  53. """
  54. def __init__(
  55. self,
  56. image_processor=None,
  57. tokenizer=None,
  58. chat_template=None,
  59. visual_prompt_prefix: str = "Describe the image.",
  60. query_prefix: str = "Question: ",
  61. ):
  62. super().__init__(image_processor=image_processor, tokenizer=tokenizer, chat_template=chat_template)
  63. self.visual_prompt_prefix = visual_prompt_prefix
  64. self.query_prefix = query_prefix
  65. @property
  66. def query_augmentation_token(self) -> str:
  67. """
  68. Return the query augmentation token.
  69. Query augmentation buffers are used as reasoning buffers during inference.
  70. """
  71. return self.tokenizer.pad_token
  72. def __call__(
  73. self,
  74. images: Optional[ImageInput] = None,
  75. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  76. audio=None,
  77. videos=None,
  78. **kwargs: Unpack[ColPaliProcessorKwargs],
  79. ) -> BatchFeature:
  80. """
  81. 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
  82. wrapper around the PaliGemmaProcessor's [`~PaliGemmaProcessor.__call__`] method adapted for the ColPali model. It cannot process
  83. both text and images at the same time.
  84. When preparing the text(s), this method forwards the `text` and `kwargs` arguments to LlamaTokenizerFast's
  85. [`~LlamaTokenizerFast.__call__`].
  86. When preparing the image(s), this method forwards the `images` and `kwargs` arguments to SiglipImageProcessor's
  87. [`~SiglipImageProcessor.__call__`].
  88. Please refer to the docstring of the above two methods for more information.
  89. Args:
  90. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  91. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  92. tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
  93. number of channels, H and W are image height and width.
  94. text (`str`, `list[str]`, `list[list[str]]`):
  95. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  96. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  97. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  98. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  99. If set, will return tensors of a particular framework. Acceptable values are:
  100. - `'tf'`: Return TensorFlow `tf.constant` objects.
  101. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  102. - `'np'`: Return NumPy `np.ndarray` objects.
  103. - `'jax'`: Return JAX `jnp.ndarray` objects.
  104. Returns:
  105. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  106. - **input_ids** -- List of token ids to be fed to a model.
  107. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  108. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  109. `None`).
  110. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  111. """
  112. output_kwargs = self._merge_kwargs(
  113. ColPaliProcessorKwargs,
  114. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  115. **kwargs,
  116. )
  117. suffix = output_kwargs["text_kwargs"].pop("suffix", None)
  118. return_token_type_ids = suffix is not None
  119. if text is None and images is None:
  120. raise ValueError("Either text or images must be provided")
  121. if text is not None and images is not None:
  122. raise ValueError("Only one of text or images can be processed at a time")
  123. if images is not None:
  124. images = self.image_processor.fetch_images(images)
  125. images = make_flat_list_of_images(images)
  126. texts_doc = [self.visual_prompt_prefix] * len(images)
  127. images = [image.convert("RGB") for image in images]
  128. input_strings = [
  129. build_string_from_input(
  130. prompt=prompt,
  131. bos_token=self.tokenizer.bos_token,
  132. image_seq_len=self.image_seq_length,
  133. image_token=IMAGE_TOKEN,
  134. num_images=len(image_list) if isinstance(image_list, list) else 1,
  135. )
  136. for prompt, image_list in zip(texts_doc, images)
  137. ]
  138. pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])["pixel_values"]
  139. # max_length has to account for the image tokens
  140. if output_kwargs["text_kwargs"].get("max_length", None) is not None:
  141. output_kwargs["text_kwargs"]["max_length"] += self.image_seq_length
  142. inputs = self.tokenizer(
  143. input_strings,
  144. return_token_type_ids=False,
  145. **output_kwargs["text_kwargs"],
  146. )
  147. return_data = {**inputs, "pixel_values": pixel_values}
  148. if return_token_type_ids:
  149. labels = inputs["input_ids"].masked_fill(inputs["token_type_ids"] == 0, -100)
  150. return_data.update({"labels": labels})
  151. return BatchFeature(data=return_data)
  152. elif text is not None:
  153. if isinstance(text, str):
  154. text = [text]
  155. elif not (isinstance(text, list) and isinstance(text[0], str)):
  156. raise ValueError("Text must be a string or a list of strings")
  157. if suffix is None:
  158. suffix = self.query_augmentation_token * 10
  159. texts_query: list[str] = []
  160. for query in text:
  161. query = self.tokenizer.bos_token + self.query_prefix + query + suffix + "\n"
  162. texts_query.append(query)
  163. output_kwargs["text_kwargs"]["max_length"] = output_kwargs["text_kwargs"].get("max_length", 50)
  164. batch_query = self.tokenizer(
  165. texts_query,
  166. return_token_type_ids=False,
  167. **output_kwargs["text_kwargs"],
  168. )
  169. return batch_query
  170. def process_images(
  171. self,
  172. images: Optional[ImageInput] = None,
  173. **kwargs: Unpack[ColPaliProcessorKwargs],
  174. ) -> BatchFeature:
  175. """
  176. Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColPaliProcessor's
  177. [`ColPaliProcessor.__call__`].
  178. This method forwards the `images` and `kwargs` arguments to the image processor.
  179. Args:
  180. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  181. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  182. tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
  183. number of channels, H and W are image height and width.
  184. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  185. If set, will return tensors of a particular framework. Acceptable values are:
  186. - `'tf'`: Return TensorFlow `tf.constant` objects.
  187. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  188. - `'np'`: Return NumPy `np.ndarray` objects.
  189. - `'jax'`: Return JAX `jnp.ndarray` objects.
  190. Returns:
  191. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  192. - **input_ids** -- List of token ids to be fed to a model.
  193. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  194. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  195. `None`).
  196. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  197. """
  198. return self.__call__(images=images, **kwargs)
  199. def process_queries(
  200. self,
  201. text: Union[TextInput, list[TextInput]],
  202. **kwargs: Unpack[ColPaliProcessorKwargs],
  203. ) -> BatchFeature:
  204. """
  205. Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColPaliProcessor's
  206. [`ColPaliProcessor.__call__`].
  207. This method forwards the `text` and `kwargs` arguments to the tokenizer.
  208. Args:
  209. text (`str`, `list[str]`, `list[list[str]]`):
  210. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  211. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  212. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  213. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  214. If set, will return tensors of a particular framework. Acceptable values are:
  215. - `'tf'`: Return TensorFlow `tf.constant` objects.
  216. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  217. - `'np'`: Return NumPy `np.ndarray` objects.
  218. - `'jax'`: Return JAX `jnp.ndarray` objects.
  219. Returns:
  220. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  221. - **input_ids** -- List of token ids to be fed to a model.
  222. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  223. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  224. `None`).
  225. """
  226. return self.__call__(text=text, **kwargs)
  227. def score_retrieval(
  228. self,
  229. query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
  230. passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
  231. batch_size: int = 128,
  232. output_dtype: Optional["torch.dtype"] = None,
  233. output_device: Union["torch.device", str] = "cpu",
  234. ) -> "torch.Tensor":
  235. """
  236. Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
  237. query embeddings (`qs`) and passage embeddings (`ps`). For ColPali, a passage is the
  238. image of a document page.
  239. Because the embedding tensors are multi-vector and can thus have different shapes, they
  240. should be fed as:
  241. (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
  242. (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
  243. obtained by padding the list of tensors.
  244. Args:
  245. query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
  246. passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
  247. batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
  248. output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
  249. If `None`, the dtype of the input embeddings is used.
  250. output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
  251. Returns:
  252. `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
  253. tensor is saved on the "cpu" device.
  254. """
  255. if len(query_embeddings) == 0:
  256. raise ValueError("No queries provided")
  257. if len(passage_embeddings) == 0:
  258. raise ValueError("No passages provided")
  259. if query_embeddings[0].device != passage_embeddings[0].device:
  260. raise ValueError("Queries and passages must be on the same device")
  261. if query_embeddings[0].dtype != passage_embeddings[0].dtype:
  262. raise ValueError("Queries and passages must have the same dtype")
  263. if output_dtype is None:
  264. output_dtype = query_embeddings[0].dtype
  265. scores: list[torch.Tensor] = []
  266. for i in range(0, len(query_embeddings), batch_size):
  267. batch_scores: list[torch.Tensor] = []
  268. batch_queries = torch.nn.utils.rnn.pad_sequence(
  269. query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
  270. )
  271. for j in range(0, len(passage_embeddings), batch_size):
  272. batch_passages = torch.nn.utils.rnn.pad_sequence(
  273. passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
  274. )
  275. batch_scores.append(
  276. torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
  277. )
  278. scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
  279. return torch.cat(scores, dim=0)
  280. __all__ = [
  281. "ColPaliProcessor",
  282. ]