processing_emu3.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # Copyright 2024 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. from ...image_processing_utils import BatchFeature
  16. from ...image_utils import ImageInput
  17. from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
  18. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  19. from ...utils import auto_docstring, is_vision_available
  20. from ...utils.import_utils import requires
  21. if is_vision_available():
  22. from .image_processing_emu3 import Emu3ImageProcessorKwargs, smart_resize
  23. class Emu3TextKwargs(TextKwargs, total=False):
  24. """
  25. return_for_image_generation (`bool`, *optional*, defaults to `False`):
  26. Whether the processed text is intended for image generation tasks. When `True`, the processor prepares
  27. inputs for image generation by appending image start tokens and size information to the prompt, and
  28. images should not be provided. When `False`, the processor prepares inputs for text generation from
  29. images and text, requiring both inputs to be provided.
  30. """
  31. return_for_image_generation: bool
  32. class Emu3ProcessorKwargs(ProcessingKwargs, total=False):
  33. text_kwargs: Emu3TextKwargs
  34. images_kwargs: Emu3ImageProcessorKwargs
  35. _defaults = {
  36. "text_kwargs": {
  37. "return_for_image_generation": False,
  38. "return_mm_token_type_ids": False,
  39. },
  40. "images_kwargs": {
  41. "ratio": "1:1",
  42. "image_area": 518400,
  43. },
  44. }
  45. @auto_docstring
  46. @requires(backends=("vision",))
  47. class Emu3Processor(ProcessorMixin):
  48. def __init__(
  49. self,
  50. image_processor,
  51. tokenizer,
  52. chat_template=None,
  53. **kwargs,
  54. ):
  55. self.image_token = tokenizer.image_token # image_token as placeholder to be replaced by vq-vae tokens
  56. self.image_token_id = tokenizer.image_token_id
  57. self.image_start_token = tokenizer.boi_token # "<|image start|>" fixed tokens for start and end of image
  58. self.image_end_token = tokenizer.eoi_token # "<|image end|>"
  59. self.fake_token_around_image = tokenizer.image_wrapper_token # "<|image token|>" every image starts with it
  60. self.eof_token = tokenizer.eof_token # "<|extra_201|>"
  61. self.bos_token = tokenizer.bos_token
  62. self.downsample_ratio = 8
  63. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  64. @auto_docstring
  65. def __call__(
  66. self,
  67. images: ImageInput | None = None,
  68. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
  69. **kwargs: Unpack[Emu3ProcessorKwargs],
  70. ) -> BatchFeature:
  71. r"""
  72. Returns:
  73. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  74. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  75. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  76. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  77. `None`).
  78. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  79. """
  80. # check if images and text inputs are reversed for BC
  81. if isinstance(text, str):
  82. text = [text]
  83. elif not isinstance(text, list) and not isinstance(text[0], str):
  84. raise TypeError("Invalid input text. Please provide a string, or a list of strings")
  85. output_kwargs = self._merge_kwargs(
  86. Emu3ProcessorKwargs,
  87. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  88. **kwargs,
  89. )
  90. return_for_image_generation = output_kwargs["text_kwargs"].pop("return_for_image_generation", False)
  91. ratio = output_kwargs["images_kwargs"].pop("ratio", None)
  92. image_area = output_kwargs["images_kwargs"].pop("image_area", None)
  93. if return_for_image_generation and images is not None:
  94. raise ValueError("You should not provide `images` when `return_for_image_generation=True`")
  95. if not return_for_image_generation and text is None and images is None:
  96. raise ValueError("You must provide either text or images when `return_for_image_generation=False`")
  97. image_features = {}
  98. image_start_tokens = f"{self.image_start_token}"
  99. image_end_tokens = f"{self.eof_token}{self.image_end_token}"
  100. # generate text from image + text input, so we add placeholders for image tokens
  101. if not return_for_image_generation and images is not None:
  102. image_features = self.image_processor(images, **output_kwargs["images_kwargs"])
  103. image_sizes = iter(image_features.image_sizes)
  104. prompt_strings = []
  105. for sample in text:
  106. while self.image_token in sample:
  107. image_size = next(image_sizes)
  108. height, width = image_size
  109. height = height // self.downsample_ratio
  110. width = width // self.downsample_ratio
  111. image_seq_length = height * (width + 1) # +1 for extra row when converting to BPE in modeling code
  112. image_placeholder = f"{image_start_tokens}{height}*{width}{self.fake_token_around_image}{'<placeholder>' * image_seq_length}{image_end_tokens}"
  113. sample = sample.replace(self.image_token, image_placeholder, 1)
  114. sample = f"{self.bos_token}{sample}" # add BOS because GPT tokenizer doesn't add it
  115. prompt_strings.append(sample)
  116. text = [sample.replace("<placeholder>", self.image_token) for sample in prompt_strings]
  117. # generate image from text input, so we add begin-of-image tokens from where image generation starts
  118. elif return_for_image_generation:
  119. height, width = self.calculate_generate_size(ratio, image_area, self.downsample_ratio)
  120. image_prompt = f"{image_start_tokens}{height}*{width}{self.fake_token_around_image}"
  121. text = [f"{self.bos_token}{sample}{image_prompt}" for sample in text]
  122. image_features["image_sizes"] = [[height, width]] * len(text)
  123. # else just generate from text-only input, and we do no special treatment for text
  124. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  125. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
  126. text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"], return_tensors=None)
  127. self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
  128. if return_mm_token_type_ids:
  129. text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
  130. return BatchFeature(data={**text_inputs, **image_features}, 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. num_image_tokens = []
  144. for height, width in image_sizes:
  145. height, width = smart_resize(
  146. height,
  147. width,
  148. self.image_processor.spatial_factor,
  149. self.image_processor.min_pixels,
  150. self.image_processor.max_pixels,
  151. )
  152. height = height // self.downsample_ratio
  153. width = width // self.downsample_ratio
  154. image_seq_length = height * (width + 1) # +1 for extra row when converting to BPE in modeling code
  155. num_image_tokens.append(image_seq_length)
  156. num_image_patches = [1] * len(image_sizes)
  157. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  158. return MultiModalData(**vision_data)
  159. def calculate_generate_size(self, ratio, image_area, spatial_factor):
  160. width, height = map(int, ratio.split(":"))
  161. current_area = width * height
  162. target_ratio = (image_area / current_area) ** 0.5
  163. token_height = int(round(height * target_ratio / spatial_factor))
  164. token_width = int(round(width * target_ratio / spatial_factor))
  165. return token_height, token_width
  166. def postprocess(self, images: ImageInput, **kwargs):
  167. return self.image_processor.postprocess(images, **kwargs)
  168. def post_process_multimodal_output(
  169. self, generated_outputs, skip_special_tokens=True, generation_mode=None, **kwargs
  170. ):
  171. """
  172. Post-process the output of a multimodal model to return the requested modality output.
  173. If the model cannot generated the requested modality, an error will be raised.
  174. Args:
  175. generated_outputs (`torch.Tensor` or `np.ndarray`):
  176. The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
  177. or `(sequence_length,)`.
  178. skip_special_tokens (`bool`, *optional*, defaults to `True`):
  179. Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
  180. generation_mode (`str`, *optional*):
  181. Generation mode indicated which modality to output and can be one of `["text", "image", "audio"]`.
  182. **kwargs:
  183. Additional arguments to be passed to the tokenizer's `batch_decode method`.
  184. Returns:
  185. `list[Union[str, PIL.Image.Image]]`: The decoded text or generated image.
  186. """
  187. if generation_mode is None or generation_mode == "text":
  188. return self.post_process_image_text_to_text(
  189. generated_outputs, skip_special_tokens=skip_special_tokens, **kwargs
  190. )
  191. elif generation_mode == "image":
  192. images = self.postprocess(generated_outputs, return_tensors="PIL.Image.Image")
  193. return images["pixel_values"]
  194. else:
  195. raise ValueError(
  196. f"{self.__class__.__name__} got an unexpected generation_mode={generation_mode}. Supported options are only `text` and `image"
  197. )
  198. __all__ = ["Emu3Processor"]