processing_paligemma.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. """
  16. Processor class for PaliGemma.
  17. """
  18. from typing import Optional, Union
  19. import numpy as np
  20. from ...feature_extraction_utils import BatchFeature
  21. from ...image_utils import ImageInput, is_valid_image
  22. from ...processing_utils import (
  23. ImagesKwargs,
  24. MultiModalData,
  25. ProcessingKwargs,
  26. ProcessorMixin,
  27. TextKwargs,
  28. Unpack,
  29. )
  30. from ...tokenization_utils_base import AddedToken, PreTokenizedInput, TextInput
  31. from ...utils import logging
  32. logger = logging.get_logger(__name__)
  33. IMAGE_TOKEN = "<image>"
  34. EXTRA_TOKENS = [f"<loc{i:0>4}>" for i in range(1024)] + [f"<seg{i:0>3}>" for i in range(128)]
  35. class PaliGemmaTextKwargs(TextKwargs):
  36. suffix: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]]
  37. class PaliGemmaImagesKwargs(ImagesKwargs):
  38. do_convert_rgb: Optional[bool]
  39. class PaliGemmaProcessorKwargs(ProcessingKwargs, total=False):
  40. text_kwargs: PaliGemmaTextKwargs
  41. images_kwargs: PaliGemmaImagesKwargs
  42. _defaults = {
  43. "text_kwargs": {
  44. "padding": False,
  45. "return_mm_token_type_ids": False,
  46. },
  47. "images_kwargs": {
  48. "data_format": "channels_first",
  49. },
  50. }
  51. # Copied from transformers.models.idefics2.processing_idefics2.is_url
  52. def is_url(val) -> bool:
  53. return isinstance(val, str) and val.startswith("http")
  54. # Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_url
  55. def is_image_or_image_url(elem):
  56. return is_url(elem) or is_valid_image(elem)
  57. def _is_str_or_image(elem):
  58. return isinstance(elem, (str)) or is_image_or_image_url(elem)
  59. def build_string_from_input(prompt, bos_token, image_seq_len, image_token, num_images):
  60. """
  61. Builds a string from the input prompt and image tokens.
  62. For example, for the call:
  63. build_string_from_input(
  64. prompt="Prefix str"
  65. bos_token="<s>",
  66. image_seq_len=3,
  67. image_token="<im>",
  68. )
  69. The output will be:
  70. "<im><im><im><s>Initial str"
  71. Args:
  72. prompt (`list[Union[str, ImageInput]]`): The input prompt.
  73. bos_token (`str`): The beginning of sentence token.
  74. image_seq_len (`int`): The length of the image sequence.
  75. image_token (`str`): The image token.
  76. num_images (`int`): Number of images in the prompt.
  77. """
  78. return f"{image_token * image_seq_len * num_images}{bos_token}{prompt}\n"
  79. class PaliGemmaProcessor(ProcessorMixin):
  80. r"""
  81. Constructs a PaliGemma processor which wraps a PaliGemma image processor and a PaliGemma tokenizer into a single processor.
  82. [`PaliGemmaProcessor`] offers all the functionalities of [`SiglipImageProcessor`] and [`GemmaTokenizerFast`]. See the
  83. [`~PaliGemmaProcessor.__call__`] and [`~PaliGemmaProcessor.decode`] for more information.
  84. Args:
  85. image_processor ([`SiglipImageProcessor`], *optional*):
  86. The image processor is a required input.
  87. tokenizer ([`GemmaTokenizerFast`], *optional*):
  88. The tokenizer is a required input.
  89. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  90. in a chat into a tokenizable string.
  91. """
  92. attributes = ["image_processor", "tokenizer"]
  93. image_processor_class = ("SiglipImageProcessor", "SiglipImageProcessorFast")
  94. tokenizer_class = ("GemmaTokenizer", "GemmaTokenizerFast")
  95. def __init__(
  96. self,
  97. image_processor=None,
  98. tokenizer=None,
  99. chat_template=None,
  100. **kwargs,
  101. ):
  102. if not hasattr(image_processor, "image_seq_length"):
  103. raise ValueError("Image processor is missing an `image_seq_length` attribute.")
  104. self.image_seq_length = image_processor.image_seq_length
  105. if not hasattr(tokenizer, "image_token"):
  106. image_token = AddedToken(IMAGE_TOKEN, normalized=False, special=True)
  107. tokens_to_add = {"additional_special_tokens": [image_token]}
  108. tokenizer.add_special_tokens(tokens_to_add)
  109. self.image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN)
  110. self.image_token = IMAGE_TOKEN
  111. else:
  112. self.image_token_id = tokenizer.image_token_id
  113. self.image_token = tokenizer.image_token
  114. tokenizer.add_tokens(EXTRA_TOKENS)
  115. tokenizer.add_bos_token = False
  116. tokenizer.add_eos_token = False
  117. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  118. def __call__(
  119. self,
  120. images: Optional[ImageInput] = None,
  121. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  122. audio=None,
  123. videos=None,
  124. **kwargs: Unpack[PaliGemmaProcessorKwargs],
  125. ) -> BatchFeature:
  126. """
  127. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  128. and `kwargs` arguments to GemmaTokenizerFast's [`~GemmaTokenizerFast.__call__`] if `text` is not `None` to encode
  129. the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
  130. SiglipImageProcessor's [`~SiglipImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
  131. of the above two methods for more information.
  132. The usage for PaliGemma fine-tuning preparation is slightly different than usual. suffix passed are suffixes to
  133. the prompt in `text`, and will be placed after the prompt. This is because attention is handled differently for
  134. the prefix and the suffix. For instance,
  135. ```python
  136. image = PIL_cow_image
  137. prompt = "answer en Where is the cow standing?"
  138. suffix = "on the beach"
  139. inputs = processor(text=prompt, images=image, suffix=suffix)
  140. ```
  141. Here `inputs` will contain the `input_ids` and `token_type_ids` that follow
  142. ```python
  143. inputs["input_ids"][:, 256:]
  144. # tensor([[ 2, 6006, 603, 573, 13910, 9980, 235336, 108, 477, 573, 8318]])
  145. inputs["token_type_ids"][:, 256:]
  146. tensor([[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]])
  147. ```
  148. Meaning the last three tokens are of "label" ("suffix") type while the other ones are of "prefix" type.
  149. Args:
  150. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  151. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  152. tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
  153. number of channels, H and W are image height and width.
  154. text (`str`, `list[str]`, `list[list[str]]`):
  155. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  156. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  157. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  158. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  159. If set, will return tensors of a particular framework. Acceptable values are:
  160. - `'tf'`: Return TensorFlow `tf.constant` objects.
  161. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  162. - `'np'`: Return NumPy `np.ndarray` objects.
  163. - `'jax'`: Return JAX `jnp.ndarray` objects.
  164. suffix (`str`, `list[str]`, `list[list[str]]`):
  165. The suffixes or batch of suffixes to be encoded. Only necessary for finetuning. See https://github.com/google-research/big_vision/blob/main/big_vision/configs/proj/paligemma/README.md
  166. for more information. If your prompt is "<image> What is on the image", the suffix corresponds to the expected prediction "a cow sitting on a bench".
  167. Returns:
  168. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  169. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. If `suffix`
  170. is provided, the `input_ids` will also contain the suffix input ids.
  171. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  172. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  173. `None`).
  174. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  175. - **labels** -- Labels compatible with training if `suffix` is not None
  176. """
  177. output_kwargs = self._merge_kwargs(
  178. PaliGemmaProcessorKwargs,
  179. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  180. **kwargs,
  181. )
  182. suffix = output_kwargs["text_kwargs"].pop("suffix", None)
  183. return_token_type_ids = suffix is not None
  184. if images is None:
  185. raise ValueError("`images` are expected as arguments to a `PaliGemmaProcessor` instance.")
  186. if text is None:
  187. logger.warning_once(
  188. "You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."
  189. )
  190. text = ""
  191. if _is_str_or_image(text):
  192. text = [text]
  193. elif isinstance(text, list) and _is_str_or_image(text[0]):
  194. pass
  195. if text is not None and images is not None:
  196. if not any(IMAGE_TOKEN in sample for sample in text):
  197. logger.warning(
  198. "You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special "
  199. "image tokens in the text, as many tokens as there are images per each text. It is recommended to "
  200. "add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images "
  201. "each text has and add special tokens."
  202. )
  203. if isinstance(text, list) and isinstance(images, list):
  204. if len(images) != len(text):
  205. raise ValueError(
  206. f"Received {len(images)} images for {len(text)} prompts. Each prompt should be associated with an image or list of images."
  207. )
  208. # make a nested list of lists to be able to iterate over the images and text below
  209. if is_valid_image(images):
  210. images = [[images]]
  211. elif isinstance(images, (list, tuple)) and is_valid_image(images[0]):
  212. images = [[image] for image in images]
  213. elif not (
  214. isinstance(images, (list, tuple))
  215. and isinstance(images[0], (list, tuple))
  216. and is_valid_image(images[0][0])
  217. ):
  218. raise ValueError("images must be an image, list of images or list of list of images")
  219. input_strings = [
  220. build_string_from_input(
  221. prompt=prompt,
  222. bos_token=self.tokenizer.bos_token,
  223. image_seq_len=self.image_seq_length,
  224. image_token=IMAGE_TOKEN,
  225. num_images=len(image_list) if isinstance(image_list, list) else 1,
  226. )
  227. for prompt, image_list in zip(text, images)
  228. ]
  229. else:
  230. expanded_samples = []
  231. for sample in text:
  232. expanded_sample = sample.replace(IMAGE_TOKEN, IMAGE_TOKEN * self.image_seq_length)
  233. bos_rfind_index = expanded_sample.rfind(IMAGE_TOKEN)
  234. bos_index = bos_rfind_index + len(IMAGE_TOKEN) if bos_rfind_index != -1 else 0
  235. expanded_sample = (
  236. expanded_sample[:bos_index] + self.tokenizer.bos_token + expanded_sample[bos_index:]
  237. )
  238. expanded_samples.append(expanded_sample)
  239. input_strings = [f"{sample}\n" for sample in expanded_samples]
  240. if suffix is not None and _is_str_or_image(suffix):
  241. suffix = [suffix]
  242. if suffix is not None:
  243. suffix = [sfx + self.tokenizer.eos_token for sfx in suffix]
  244. pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])["pixel_values"]
  245. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  246. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)
  247. inputs = self.tokenizer(
  248. input_strings,
  249. text_pair=suffix,
  250. return_token_type_ids=return_token_type_ids,
  251. **output_kwargs["text_kwargs"],
  252. )
  253. self._check_special_mm_tokens(input_strings, inputs, modalities=["image"])
  254. return_data = {**inputs, "pixel_values": pixel_values}
  255. if return_token_type_ids:
  256. labels = np.array(inputs["input_ids"])
  257. labels[np.array(inputs["token_type_ids"]) == 0] = -100
  258. return_data.update({"labels": labels})
  259. if return_mm_token_type_ids:
  260. array_ids = np.array(return_data["input_ids"])
  261. mm_token_type_ids = np.zeros_like(return_data["input_ids"])
  262. mm_token_type_ids[array_ids == self.image_token_id] = 1
  263. return_data["mm_token_type_ids"] = mm_token_type_ids.tolist()
  264. return BatchFeature(data=return_data, tensor_type=return_tensors)
  265. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  266. """
  267. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  268. Args:
  269. image_sizes (list[list[str]], *optional*):
  270. The input sizes formatted as (height, width) per each image.
  271. Returns:
  272. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  273. input modalities, along with other useful data.
  274. """
  275. vision_data = {}
  276. if image_sizes is not None:
  277. num_image_tokens = [self.image_seq_length] * len(image_sizes)
  278. num_image_patches = [1] * len(image_sizes)
  279. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  280. return MultiModalData(**vision_data)
  281. __all__ = ["PaliGemmaProcessor"]