processing_gemma3.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # coding=utf-8
  2. # Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
  3. #
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import re
  17. from typing import Optional, Union
  18. import numpy as np
  19. from ...feature_extraction_utils import BatchFeature
  20. from ...image_utils import ImageInput, make_nested_list_of_images
  21. from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
  22. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  23. from ...utils import to_py_obj
  24. class Gemma3ImagesKwargs(ImagesKwargs):
  25. do_pan_and_scan: Optional[bool]
  26. pan_and_scan_min_crop_size: Optional[int]
  27. pan_and_scan_max_num_crops: Optional[int]
  28. pan_and_scan_min_ratio_to_activate: Optional[float]
  29. do_convert_rgb: Optional[bool]
  30. class Gemma3ProcessorKwargs(ProcessingKwargs, total=False):
  31. images_kwargs: Gemma3ImagesKwargs
  32. _defaults = {
  33. "text_kwargs": {
  34. "padding": False,
  35. "return_mm_token_type_ids": True,
  36. },
  37. "images_kwargs": {
  38. "do_convert_rgb": True,
  39. "do_pan_and_scan": False,
  40. "pan_and_scan_min_crop_size": 256,
  41. "pan_and_scan_max_num_crops": 4,
  42. "pan_and_scan_min_ratio_to_activate": 1.2,
  43. },
  44. }
  45. class Gemma3Processor(ProcessorMixin):
  46. attributes = ["image_processor", "tokenizer"]
  47. image_processor_class = "AutoImageProcessor"
  48. tokenizer_class = "AutoTokenizer"
  49. def __init__(
  50. self,
  51. image_processor,
  52. tokenizer,
  53. chat_template=None,
  54. image_seq_length: int = 256,
  55. **kwargs,
  56. ):
  57. self.image_seq_length = image_seq_length
  58. self.image_token_id = tokenizer.image_token_id
  59. self.boi_token = tokenizer.boi_token
  60. self.image_token = tokenizer.image_token
  61. image_tokens_expanded = "".join([tokenizer.image_token] * image_seq_length)
  62. self.full_image_sequence = f"\n\n{tokenizer.boi_token}{image_tokens_expanded}{tokenizer.eoi_token}\n\n"
  63. super().__init__(
  64. image_processor=image_processor,
  65. tokenizer=tokenizer,
  66. chat_template=chat_template,
  67. **kwargs,
  68. )
  69. def __call__(
  70. self,
  71. images: Optional[ImageInput] = None,
  72. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  73. videos=None,
  74. audio=None,
  75. **kwargs: Unpack[Gemma3ProcessorKwargs],
  76. ) -> BatchFeature:
  77. if text is None and images is None:
  78. raise ValueError("Provide at least one of `text` or `images`.")
  79. output_kwargs = self._merge_kwargs(
  80. Gemma3ProcessorKwargs,
  81. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  82. **kwargs,
  83. )
  84. if isinstance(text, str):
  85. text = [text]
  86. elif not isinstance(text, list) and not isinstance(text[0], str):
  87. raise TypeError("Invalid input text. Please provide a string, or a list of strings")
  88. image_inputs = {}
  89. if images is not None:
  90. images = self.image_processor.fetch_images(images)
  91. batched_images = make_nested_list_of_images(images)
  92. image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  93. # Create empty text to be replaced with placeholders
  94. if not text:
  95. text = [" ".join([self.boi_token] * len(images)) for images in batched_images]
  96. if len(batched_images) != len(text):
  97. raise ValueError(
  98. f"Received inconsistently sized batches of images ({len(batched_images)}) and text ({len(text)})."
  99. )
  100. # Replace image tokens by the full expanded sequence
  101. num_crops = to_py_obj(image_inputs.pop("num_crops"))
  102. batch_num_crops = [[num_crops.pop(0) for _ in range(len(images))] for images in batched_images]
  103. for batch_idx, (prompt, images, num_crops) in enumerate(zip(text, batched_images, batch_num_crops)):
  104. image_indexes = [m.start() for m in re.finditer(self.boi_token, prompt)]
  105. if len(images) != len(image_indexes):
  106. raise ValueError(
  107. f"Prompt contained {len(image_indexes)} image tokens but received {len(images)} images."
  108. )
  109. # Insert additional image tokens for Pan-and-Scan crops
  110. for num, idx in reversed(list(zip(num_crops, image_indexes))):
  111. if num:
  112. formatted_image_text = (
  113. f"Here is the original image {self.boi_token} and here are some crops to help you see better "
  114. + " ".join([self.boi_token] * num)
  115. )
  116. prompt = prompt[:idx] + formatted_image_text + prompt[idx + len(self.boi_token) :]
  117. text[batch_idx] = prompt
  118. # Expand placeholder image tokens to the full image token sequence
  119. text = [prompt.replace(self.boi_token, self.full_image_sequence) for prompt in text]
  120. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  121. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
  122. text_inputs = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
  123. self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
  124. # Add token type ids manually, as tokenizer can't do arbitrary position token types
  125. if return_mm_token_type_ids:
  126. array_ids = np.array(text_inputs["input_ids"])
  127. mm_token_type_ids = np.zeros_like(array_ids)
  128. mm_token_type_ids[array_ids == self.image_token_id] = 1
  129. text_inputs["token_type_ids"] = mm_token_type_ids.tolist()
  130. return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
  131. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  132. """
  133. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  134. Args:
  135. image_sizes (`list[list[int]]`, *optional*):
  136. The input sizes formatted as (height, width) per each image.
  137. Returns:
  138. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  139. input modalities, along with other useful data.
  140. """
  141. vision_data = {}
  142. if image_sizes is not None:
  143. # NOTE: no image cropping supported yet
  144. num_image_tokens = [self.image_seq_length] * len(image_sizes)
  145. num_image_patches = [1] * len(image_sizes)
  146. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  147. return MultiModalData(**vision_data)
  148. @property
  149. def model_input_names(self):
  150. tokenizer_input_names = self.tokenizer.model_input_names + ["token_type_ids"]
  151. image_processor_input_names = self.image_processor.model_input_names
  152. image_processor_input_names = [name for name in image_processor_input_names if name != "num_crops"]
  153. return list(tokenizer_input_names + image_processor_input_names)
  154. __all__ = ["Gemma3Processor"]