processing_paligemma.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # Copyright 2024 The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Processor class for PaliGemma.
  16. """
  17. import numpy as np
  18. from ...feature_extraction_utils import BatchFeature
  19. from ...image_utils import ImageInput, is_valid_image
  20. from ...processing_utils import (
  21. MultiModalData,
  22. ProcessingKwargs,
  23. ProcessorMixin,
  24. TextKwargs,
  25. Unpack,
  26. )
  27. from ...tokenization_utils_base import AddedToken, PreTokenizedInput, TextInput
  28. from ...utils import auto_docstring, logging
  29. logger = logging.get_logger(__name__)
  30. IMAGE_TOKEN = "<image>"
  31. EXTRA_TOKENS = [f"<loc{i:0>4}>" for i in range(1024)] + [f"<seg{i:0>3}>" for i in range(128)]
  32. class PaliGemmaTextKwargs(TextKwargs):
  33. """
  34. suffix (`str`, `list[str]`, `list[list[str]]`):
  35. 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
  36. 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".
  37. """
  38. suffix: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None
  39. class PaliGemmaProcessorKwargs(ProcessingKwargs, total=False):
  40. text_kwargs: PaliGemmaTextKwargs
  41. _defaults = {
  42. "text_kwargs": {
  43. "padding": False,
  44. "return_mm_token_type_ids": False,
  45. },
  46. "images_kwargs": {
  47. "data_format": "channels_first",
  48. },
  49. }
  50. # Copied from transformers.models.idefics2.processing_idefics2.is_url
  51. def is_url(val) -> bool:
  52. return isinstance(val, str) and val.startswith("http")
  53. # Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_url
  54. def is_image_or_image_url(elem):
  55. return is_url(elem) or is_valid_image(elem)
  56. def _is_str_or_image(elem):
  57. return isinstance(elem, (str)) or is_image_or_image_url(elem)
  58. def build_string_from_input(prompt, bos_token, image_seq_len, image_token, num_images):
  59. """
  60. Builds a string from the input prompt and image tokens.
  61. For example, for the call:
  62. build_string_from_input(
  63. prompt="Prefix str"
  64. bos_token="<s>",
  65. image_seq_len=3,
  66. image_token="<im>",
  67. )
  68. The output will be:
  69. "<im><im><im><s>Initial str"
  70. Args:
  71. prompt (`list[Union[str, ImageInput]]`): The input prompt.
  72. bos_token (`str`): The beginning of sentence token.
  73. image_seq_len (`int`): The length of the image sequence.
  74. image_token (`str`): The image token.
  75. num_images (`int`): Number of images in the prompt.
  76. """
  77. return f"{image_token * image_seq_len * num_images}{bos_token}{prompt}\n"
  78. @auto_docstring
  79. class PaliGemmaProcessor(ProcessorMixin):
  80. def __init__(
  81. self,
  82. image_processor=None,
  83. tokenizer=None,
  84. chat_template=None,
  85. **kwargs,
  86. ):
  87. if not hasattr(image_processor, "image_seq_length"):
  88. raise ValueError("Image processor is missing an `image_seq_length` attribute.")
  89. self.image_seq_length = image_processor.image_seq_length
  90. if not hasattr(tokenizer, "image_token"):
  91. image_token = AddedToken(IMAGE_TOKEN, normalized=False, special=True)
  92. tokens_to_add = {"additional_special_tokens": [image_token]}
  93. tokenizer.add_special_tokens(tokens_to_add)
  94. self.image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN)
  95. self.image_token = IMAGE_TOKEN
  96. else:
  97. self.image_token_id = tokenizer.image_token_id
  98. self.image_token = tokenizer.image_token
  99. tokenizer.add_tokens(EXTRA_TOKENS)
  100. tokenizer.add_bos_token = False
  101. tokenizer.add_eos_token = False
  102. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  103. @auto_docstring
  104. def __call__(
  105. self,
  106. images: ImageInput | None = None,
  107. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  108. **kwargs: Unpack[PaliGemmaProcessorKwargs],
  109. ) -> BatchFeature:
  110. r"""
  111. Returns:
  112. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  113. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. If `suffix`
  114. is provided, the `input_ids` will also contain the suffix input ids.
  115. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  116. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  117. `None`).
  118. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  119. - **labels** -- Labels compatible with training if `suffix` is not None
  120. """
  121. output_kwargs = self._merge_kwargs(
  122. PaliGemmaProcessorKwargs,
  123. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  124. **kwargs,
  125. )
  126. suffix = output_kwargs["text_kwargs"].pop("suffix", None)
  127. return_token_type_ids = True
  128. if images is None:
  129. raise ValueError("`images` are expected as arguments to a `PaliGemmaProcessor` instance.")
  130. if text is None:
  131. logger.warning_once(
  132. "You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."
  133. )
  134. text = ""
  135. if _is_str_or_image(text):
  136. text = [text]
  137. elif isinstance(text, list) and _is_str_or_image(text[0]):
  138. pass
  139. if text is not None and images is not None:
  140. if not any(IMAGE_TOKEN in sample for sample in text):
  141. logger.warning(
  142. "You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special "
  143. "image tokens in the text, as many tokens as there are images per each text. It is recommended to "
  144. "add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images "
  145. "each text has and add special tokens."
  146. )
  147. if isinstance(text, list) and isinstance(images, list):
  148. if len(images) != len(text):
  149. raise ValueError(
  150. f"Received {len(images)} images for {len(text)} prompts. Each prompt should be associated with an image or list of images."
  151. )
  152. # make a nested list of lists to be able to iterate over the images and text below
  153. if is_valid_image(images):
  154. images = [[images]]
  155. elif isinstance(images, (list, tuple)) and is_valid_image(images[0]):
  156. images = [[image] for image in images]
  157. elif not (
  158. isinstance(images, (list, tuple))
  159. and isinstance(images[0], (list, tuple))
  160. and is_valid_image(images[0][0])
  161. ):
  162. raise ValueError("images must be an image, list of images or list of list of images")
  163. input_strings = [
  164. build_string_from_input(
  165. prompt=prompt,
  166. bos_token=self.tokenizer.bos_token,
  167. image_seq_len=self.image_seq_length,
  168. image_token=IMAGE_TOKEN,
  169. num_images=len(image_list) if isinstance(image_list, list) else 1,
  170. )
  171. for prompt, image_list in zip(text, images)
  172. ]
  173. else:
  174. expanded_samples = []
  175. for sample in text:
  176. expanded_sample = sample.replace(IMAGE_TOKEN, IMAGE_TOKEN * self.image_seq_length)
  177. bos_rfind_index = expanded_sample.rfind(IMAGE_TOKEN)
  178. bos_index = bos_rfind_index + len(IMAGE_TOKEN) if bos_rfind_index != -1 else 0
  179. expanded_sample = (
  180. expanded_sample[:bos_index] + self.tokenizer.bos_token + expanded_sample[bos_index:]
  181. )
  182. expanded_samples.append(expanded_sample)
  183. input_strings = [f"{sample}\n" for sample in expanded_samples]
  184. if suffix is not None and _is_str_or_image(suffix):
  185. suffix = [suffix]
  186. if suffix is not None:
  187. suffix = [sfx + self.tokenizer.eos_token for sfx in suffix]
  188. pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])["pixel_values"]
  189. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  190. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)
  191. inputs = self.tokenizer(
  192. input_strings,
  193. text_pair=suffix,
  194. return_token_type_ids=return_token_type_ids,
  195. **output_kwargs["text_kwargs"],
  196. )
  197. self._check_special_mm_tokens(input_strings, inputs, modalities=["image"])
  198. return_data = {**inputs, "pixel_values": pixel_values}
  199. # TODO: ideally we would control label generation separately, now that we always return token_type_ids.
  200. if return_token_type_ids:
  201. labels = np.array(inputs["input_ids"])
  202. labels[np.array(inputs["token_type_ids"]) == 0] = -100
  203. return_data.update({"labels": labels})
  204. if return_mm_token_type_ids:
  205. return_data["mm_token_type_ids"] = self.create_mm_token_type_ids(return_data["input_ids"])
  206. return BatchFeature(data=return_data, tensor_type=return_tensors)
  207. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  208. """
  209. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  210. Args:
  211. image_sizes (list[list[str]], *optional*):
  212. The input sizes formatted as (height, width) per each image.
  213. Returns:
  214. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  215. input modalities, along with other useful data.
  216. """
  217. vision_data = {}
  218. if image_sizes is not None:
  219. num_image_tokens = [self.image_seq_length] * len(image_sizes)
  220. num_image_patches = [1] * len(image_sizes)
  221. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  222. return MultiModalData(**vision_data)
  223. @property
  224. def model_input_names(self):
  225. tokenizer_input_names = self.tokenizer.model_input_names + ["token_type_ids", "labels"]
  226. image_processor_input_names = self.image_processor.model_input_names
  227. return list(tokenizer_input_names + image_processor_input_names)
  228. __all__ = ["PaliGemmaProcessor"]