processing_gemma3n.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. from typing import Optional, Union
  17. import numpy as np
  18. from ...feature_extraction_utils import BatchFeature
  19. from ...image_utils import ImageInput, make_nested_list_of_images
  20. from ...processing_utils import AudioKwargs, ImagesKwargs, ProcessingKwargs, ProcessorMixin, Unpack
  21. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  22. class Gemma3nImagesKwargs(ImagesKwargs):
  23. do_convert_rgb: Optional[bool]
  24. class Gemma3nProcessorKwargs(ProcessingKwargs, total=False):
  25. audio_kwargs: AudioKwargs
  26. images_kwargs: Gemma3nImagesKwargs
  27. _defaults = {
  28. "text_kwargs": {
  29. "padding": False,
  30. },
  31. }
  32. class Gemma3nProcessor(ProcessorMixin):
  33. """
  34. A processor for Gemma 3n, wrapping the full capabilities of a feature extractor, image processor, and tokenizer
  35. into a single processor.
  36. Args:
  37. feature_extractor (`Gemma3nAudioFeatureExtractor`):
  38. Feature extractor that converts raw audio waveforms into MEL spectrograms for the audio encoder. This
  39. should return a `BatchFeature` with `input_features` and `input_features_mask` features.
  40. image_processor (`SiglipImageProcessorFast`):
  41. Image processor that prepares batches of images for the vision encoder. This should return a `BatchFeature`
  42. with a `pixel_values` feature.
  43. tokenizer (`GemmaTokenizerFast`):
  44. The text tokenizer for the model.
  45. chat_template (`string`, *optional*):
  46. A Jinja template for generating text prompts from a set of messages.
  47. audio_seq_length (int, *optional*, defaults to 188):
  48. The number of audio soft tokens that will be added to the text prompt
  49. image_seq_length (int, *optional*, defaults to 256):
  50. The number of image soft tokens that should be added to
  51. """
  52. attributes = ["feature_extractor", "image_processor", "tokenizer"]
  53. feature_extractor_class = "AutoFeatureExtractor"
  54. image_processor_class = "AutoImageProcessor"
  55. tokenizer_class = "AutoTokenizer"
  56. def __init__(
  57. self,
  58. feature_extractor,
  59. image_processor,
  60. tokenizer,
  61. chat_template=None,
  62. audio_seq_length: int = 188,
  63. image_seq_length: int = 256,
  64. **kwargs,
  65. ):
  66. self.audio_seq_length = audio_seq_length
  67. self.audio_token_id = tokenizer.audio_token_id
  68. self.boa_token = tokenizer.boa_token
  69. self.audio_token = tokenizer.audio_token
  70. audio_tokens_expanded = "".join([tokenizer.audio_token] * audio_seq_length)
  71. self.full_audio_sequence = f"\n\n{tokenizer.boa_token}{audio_tokens_expanded}{tokenizer.eoa_token}\n\n"
  72. self.image_seq_length = image_seq_length
  73. self.image_token_id = tokenizer.image_token_id
  74. self.boi_token = tokenizer.boi_token
  75. self.image_token = tokenizer.image_token
  76. image_tokens_expanded = "".join([tokenizer.image_token] * image_seq_length)
  77. self.full_image_sequence = f"\n\n{tokenizer.boi_token}{image_tokens_expanded}{tokenizer.eoi_token}\n\n"
  78. super().__init__(
  79. feature_extractor=feature_extractor,
  80. image_processor=image_processor,
  81. tokenizer=tokenizer,
  82. chat_template=chat_template,
  83. **kwargs,
  84. )
  85. def __call__(
  86. self,
  87. images: Optional[ImageInput] = None,
  88. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  89. audio: Optional[Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]]] = None,
  90. videos=None,
  91. **kwargs: Unpack[Gemma3nProcessorKwargs],
  92. ) -> BatchFeature:
  93. if text is None and images is None and audio is None:
  94. raise ValueError("Provide at least one of `text`, `images`, or `audio`.")
  95. output_kwargs = self._merge_kwargs(
  96. Gemma3nProcessorKwargs,
  97. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  98. **kwargs,
  99. )
  100. if isinstance(text, str):
  101. text = [text]
  102. elif not isinstance(text, list) and not isinstance(text[0], str):
  103. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  104. if audio is not None:
  105. audio_inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
  106. if not text:
  107. text = [self.audio_token for _ in audio]
  108. # Expand placeholder audio tokens to the full audio token sequence
  109. text = [prompt.replace(self.audio_token, self.full_audio_sequence) for prompt in text]
  110. else:
  111. audio_inputs = {}
  112. if images is not None:
  113. images = self.image_processor.fetch_images(images)
  114. batched_images = make_nested_list_of_images(images)
  115. image_inputs = self.image_processor(batched_images, **output_kwargs["images_kwargs"])
  116. # Create empty text to be replaced with placeholders
  117. if not text:
  118. text = [" ".join([self.image_token] * len(images)) for images in batched_images]
  119. if len(batched_images) != len(text):
  120. raise ValueError(
  121. f"Received inconsistently sized batches of images ({len(batched_images)}) and text ({len(text)})."
  122. )
  123. # Expand placeholder image tokens to the full image token sequence
  124. text = [prompt.replace(self.image_token, self.full_image_sequence) for prompt in text]
  125. else:
  126. image_inputs = {}
  127. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  128. text_inputs = self.tokenizer(text=text, **output_kwargs["text_kwargs"], return_tensors="np")
  129. self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
  130. # Add token type ids manually, as tokenizer can't do arbitrary position token types
  131. array_ids = text_inputs["input_ids"]
  132. token_type_ids = np.zeros_like(array_ids)
  133. token_type_ids[array_ids == self.image_token_id] = 1
  134. token_type_ids[array_ids == self.audio_token_id] = 3
  135. text_inputs = {k: v.tolist() for k, v in text_inputs.items()} # in case user requested list inputs
  136. text_inputs["token_type_ids"] = token_type_ids.tolist()
  137. return BatchFeature(data={**text_inputs, **image_inputs, **audio_inputs}, tensor_type=return_tensors)
  138. __all__ = ["Gemma3nProcessor"]