processing_gemma3n.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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 numpy as np
  16. from ...feature_extraction_utils import BatchFeature
  17. from ...image_utils import ImageInput, make_nested_list_of_images
  18. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
  19. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  20. from ...utils import auto_docstring
  21. class Gemma3nProcessorKwargs(ProcessingKwargs, total=False):
  22. _defaults = {
  23. "text_kwargs": {"padding": False},
  24. }
  25. @auto_docstring
  26. class Gemma3nProcessor(ProcessorMixin):
  27. def __init__(
  28. self,
  29. feature_extractor,
  30. image_processor,
  31. tokenizer,
  32. chat_template=None,
  33. audio_seq_length: int = 188,
  34. image_seq_length: int = 256,
  35. **kwargs,
  36. ):
  37. r"""
  38. audio_seq_length (int, *optional*, defaults to 188):
  39. The number of audio soft tokens that will be added to the text prompt
  40. image_seq_length (int, *optional*, defaults to 256):
  41. The number of image soft tokens that should be added to
  42. """
  43. self.audio_seq_length = audio_seq_length
  44. self.audio_token_id = tokenizer.audio_token_id
  45. self.boa_token = tokenizer.boa_token
  46. self.audio_token = tokenizer.audio_token
  47. audio_tokens_expanded = "".join([tokenizer.audio_token] * audio_seq_length)
  48. self.full_audio_sequence = f"\n\n{tokenizer.boa_token}{audio_tokens_expanded}{tokenizer.eoa_token}\n\n"
  49. self.image_seq_length = image_seq_length
  50. self.image_token_id = tokenizer.image_token_id
  51. self.boi_token = tokenizer.boi_token
  52. self.image_token = tokenizer.image_token
  53. image_tokens_expanded = "".join([tokenizer.image_token] * image_seq_length)
  54. self.full_image_sequence = f"\n\n{tokenizer.boi_token}{image_tokens_expanded}{tokenizer.eoi_token}\n\n"
  55. super().__init__(
  56. feature_extractor=feature_extractor,
  57. image_processor=image_processor,
  58. tokenizer=tokenizer,
  59. chat_template=chat_template,
  60. **kwargs,
  61. )
  62. @auto_docstring
  63. def __call__(
  64. self,
  65. images: ImageInput | None = None,
  66. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  67. audio: np.ndarray | list[float] | list[np.ndarray] | list[list[float]] | None = None,
  68. **kwargs: Unpack[Gemma3nProcessorKwargs],
  69. ) -> BatchFeature:
  70. if text is None and images is None and audio is None:
  71. raise ValueError("Provide at least one of `text`, `images`, or `audio`.")
  72. output_kwargs = self._merge_kwargs(
  73. Gemma3nProcessorKwargs,
  74. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  75. **kwargs,
  76. )
  77. if isinstance(text, str):
  78. text = [text]
  79. elif not isinstance(text, list) and not isinstance(text[0], str):
  80. raise TypeError("Invalid input text. Please provide a string, or a list of strings")
  81. if audio is not None:
  82. audio_inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
  83. if not text:
  84. text = [self.audio_token for _ in audio]
  85. # Expand placeholder audio tokens to the full audio token sequence
  86. text = [prompt.replace(self.audio_token, self.full_audio_sequence) for prompt in text]
  87. else:
  88. audio_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(batched_images, **output_kwargs["images_kwargs"])
  93. # Create empty text to be replaced with placeholders
  94. if not text:
  95. text = [" ".join([self.image_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. # Expand placeholder image tokens to the full image token sequence
  101. text = [prompt.replace(self.image_token, self.full_image_sequence) for prompt in text]
  102. else:
  103. image_inputs = {}
  104. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  105. text_inputs = self.tokenizer(text=text, **output_kwargs["text_kwargs"], return_tensors="np")
  106. self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
  107. # Add token type ids manually, as tokenizer can't do arbitrary position token types
  108. array_ids = text_inputs["input_ids"]
  109. token_type_ids = np.zeros_like(array_ids)
  110. token_type_ids[array_ids == self.image_token_id] = 1
  111. token_type_ids[array_ids == self.audio_token_id] = 3
  112. text_inputs = {k: v.tolist() for k, v in text_inputs.items()} # in case user requested list inputs
  113. text_inputs["token_type_ids"] = token_type_ids.tolist()
  114. return BatchFeature(data={**text_inputs, **image_inputs, **audio_inputs}, tensor_type=return_tensors)
  115. @property
  116. def model_input_names(self):
  117. tokenizer_input_names = self.tokenizer.model_input_names + ["token_type_ids"]
  118. image_processor_input_names = self.image_processor.model_input_names
  119. audio_processor_input_names = self.feature_extractor.model_input_names
  120. image_processor_input_names = [name for name in image_processor_input_names if name != "num_crops"]
  121. return list(tokenizer_input_names + image_processor_input_names + audio_processor_input_names)
  122. __all__ = ["Gemma3nProcessor"]