processing_gemma3.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
  2. #
  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. import re
  16. from ...feature_extraction_utils import BatchFeature
  17. from ...image_utils import ImageInput, make_nested_list_of_images
  18. from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
  19. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  20. from ...utils import auto_docstring, to_py_obj
  21. class Gemma3ProcessorKwargs(ProcessingKwargs, total=False):
  22. _defaults = {
  23. "text_kwargs": {
  24. "padding": False,
  25. "return_mm_token_type_ids": True,
  26. },
  27. "images_kwargs": {
  28. "do_convert_rgb": True,
  29. "do_pan_and_scan": False,
  30. "pan_and_scan_min_crop_size": 256,
  31. "pan_and_scan_max_num_crops": 4,
  32. "pan_and_scan_min_ratio_to_activate": 1.2,
  33. },
  34. }
  35. @auto_docstring
  36. class Gemma3Processor(ProcessorMixin):
  37. def __init__(
  38. self,
  39. image_processor,
  40. tokenizer,
  41. chat_template=None,
  42. image_seq_length: int = 256,
  43. **kwargs,
  44. ):
  45. self.image_seq_length = image_seq_length
  46. self.image_token_id = tokenizer.image_token_id
  47. self.boi_token = tokenizer.boi_token
  48. self.image_token = tokenizer.image_token
  49. image_tokens_expanded = "".join([tokenizer.image_token] * image_seq_length)
  50. self.full_image_sequence = f"\n\n{tokenizer.boi_token}{image_tokens_expanded}{tokenizer.eoi_token}\n\n"
  51. super().__init__(
  52. image_processor=image_processor,
  53. tokenizer=tokenizer,
  54. chat_template=chat_template,
  55. **kwargs,
  56. )
  57. @auto_docstring
  58. def __call__(
  59. self,
  60. images: ImageInput | None = None,
  61. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  62. **kwargs: Unpack[Gemma3ProcessorKwargs],
  63. ) -> BatchFeature:
  64. if text is None and images is None:
  65. raise ValueError("Provide at least one of `text` or `images`.")
  66. output_kwargs = self._merge_kwargs(
  67. Gemma3ProcessorKwargs,
  68. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  69. **kwargs,
  70. )
  71. if isinstance(text, str):
  72. text = [text]
  73. elif not isinstance(text, list) and not isinstance(text[0], str):
  74. raise TypeError("Invalid input text. Please provide a string, or a list of strings")
  75. image_inputs = {}
  76. if images is not None:
  77. images = self.image_processor.fetch_images(images)
  78. batched_images = make_nested_list_of_images(images)
  79. image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  80. # Create empty text to be replaced with placeholders
  81. if not text:
  82. text = [" ".join([self.boi_token] * len(images)) for images in batched_images]
  83. if len(batched_images) != len(text):
  84. raise ValueError(
  85. f"Received inconsistently sized batches of images ({len(batched_images)}) and text ({len(text)})."
  86. )
  87. # Replace image tokens by the full expanded sequence
  88. num_crops = to_py_obj(image_inputs.pop("num_crops"))
  89. batch_num_crops = [[num_crops.pop(0) for _ in range(len(images))] for images in batched_images]
  90. for batch_idx, (prompt, images, num_crops) in enumerate(zip(text, batched_images, batch_num_crops)):
  91. image_indexes = [m.start() for m in re.finditer(self.boi_token, prompt)]
  92. if len(images) != len(image_indexes):
  93. raise ValueError(
  94. f"Prompt contained {len(image_indexes)} image tokens but received {len(images)} images."
  95. )
  96. # Insert additional image tokens for Pan-and-Scan crops
  97. for num, idx in reversed(list(zip(num_crops, image_indexes))):
  98. if num:
  99. formatted_image_text = (
  100. f"Here is the original image {self.boi_token} and here are some crops to help you see better "
  101. + " ".join([self.boi_token] * num)
  102. )
  103. prompt = prompt[:idx] + formatted_image_text + prompt[idx + len(self.boi_token) :]
  104. text[batch_idx] = prompt
  105. # Expand placeholder image tokens to the full image token sequence
  106. text = [prompt.replace(self.boi_token, self.full_image_sequence) for prompt in text]
  107. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  108. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
  109. text_inputs = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
  110. self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
  111. if return_mm_token_type_ids:
  112. text_inputs["token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
  113. return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
  114. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  115. """
  116. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  117. Args:
  118. image_sizes (`list[list[int]]`, *optional*):
  119. The input sizes formatted as (height, width) per each image.
  120. Returns:
  121. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  122. input modalities, along with other useful data.
  123. """
  124. vision_data = {}
  125. if image_sizes is not None:
  126. # NOTE: no image cropping supported yet
  127. num_image_tokens = [self.image_seq_length] * len(image_sizes)
  128. num_image_patches = [1] * len(image_sizes)
  129. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  130. return MultiModalData(**vision_data)
  131. @property
  132. def model_input_names(self):
  133. tokenizer_input_names = self.tokenizer.model_input_names + ["token_type_ids"]
  134. image_processor_input_names = self.image_processor.model_input_names
  135. image_processor_input_names = [name for name in image_processor_input_names if name != "num_crops"]
  136. return list(tokenizer_input_names + image_processor_input_names)
  137. __all__ = ["Gemma3Processor"]