processing_emu3.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. # coding=utf-8
  2. # Copyright 2024 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 ...image_processing_utils import BatchFeature
  19. from ...image_utils import ImageInput
  20. from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
  21. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  22. from ...utils import is_vision_available
  23. if is_vision_available():
  24. from .image_processing_emu3 import smart_resize
  25. class Emu3TextKwargs(TextKwargs, total=False):
  26. return_for_image_generation: bool
  27. class Emu3ImagesKwargs(ImagesKwargs, total=False):
  28. ratio: str
  29. image_area: int
  30. class Emu3ProcessorKwargs(ProcessingKwargs, total=False):
  31. text_kwargs: Emu3TextKwargs
  32. images_kwargs: Emu3ImagesKwargs
  33. _defaults = {
  34. "text_kwargs": {
  35. "return_for_image_generation": False,
  36. "return_mm_token_type_ids": False,
  37. },
  38. "images_kwargs": {
  39. "ratio": "1:1",
  40. "image_area": 518400,
  41. },
  42. }
  43. class Emu3Processor(ProcessorMixin):
  44. r"""
  45. Constructs a Emu3 processor which wraps a Emu3 image processor and a GPT2 tokenizer into a single
  46. processor.
  47. [`Emu3Processor`] offers all the functionalities of [`Emu3ImageProcessor`] and [`GPT2TokenizerFast`].
  48. See the [`~Emu3Processor.__call__`] and [`~Emu3Processor.decode`] for more information.
  49. Args:
  50. image_processor ([`Emu3ImageProcessor`]):
  51. The image processor is a required input.
  52. tokenizer ([`Emu3TokenizerFast`]):
  53. The tokenizer is a required input.
  54. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  55. in a chat into a tokenizable string.
  56. """
  57. attributes = ["image_processor", "tokenizer"]
  58. tokenizer_class = ("GPT2Tokenizer", "GPT2TokenizerFast")
  59. image_processor_class = "Emu3ImageProcessor"
  60. def __init__(
  61. self,
  62. image_processor,
  63. tokenizer,
  64. chat_template=None,
  65. **kwargs,
  66. ):
  67. self.image_token = tokenizer.image_token # image_token as placeholder to be replaced by vq-vae tokens
  68. self.image_token_id = tokenizer.image_token_id
  69. self.image_start_token = tokenizer.boi_token # "<|image start|>" fixed tokens for start and end of image
  70. self.image_end_token = tokenizer.eoi_token # "<|image end|>"
  71. self.fake_token_around_image = tokenizer.image_wrapper_token # "<|image token|>" every image starts with it
  72. self.eof_token = tokenizer.eof_token # "<|extra_201|>"
  73. self.bos_token = tokenizer.bos_token
  74. self.downsample_ratio = 8
  75. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  76. def __call__(
  77. self,
  78. images: Optional[ImageInput] = None,
  79. text: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None,
  80. audio=None,
  81. videos=None,
  82. **kwargs: Unpack[Emu3ProcessorKwargs],
  83. ) -> BatchFeature:
  84. """
  85. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  86. and `kwargs` arguments to Emu3TokenizerFast's [`~Emu3TokenizerFast.__call__`] if `text` is not `None` to encode
  87. the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
  88. CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
  89. of the above two methods for more information.
  90. Args:
  91. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  92. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  93. tensor. Both channels-first and channels-last formats are supported.
  94. text (`str`, `list[str]`, `list[list[str]]`):
  95. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  96. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  97. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  98. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  99. If set, will return tensors of a particular framework. Acceptable values are:
  100. - `'tf'`: Return TensorFlow `tf.constant` objects.
  101. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  102. - `'np'`: Return NumPy `np.ndarray` objects.
  103. - `'jax'`: Return JAX `jnp.ndarray` objects.
  104. Returns:
  105. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  106. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  107. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  108. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  109. `None`).
  110. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  111. """
  112. # check if images and text inputs are reversed for BC
  113. if isinstance(text, str):
  114. text = [text]
  115. elif not isinstance(text, list) and not isinstance(text[0], str):
  116. raise TypeError("Invalid input text. Please provide a string, or a list of strings")
  117. output_kwargs = self._merge_kwargs(
  118. Emu3ProcessorKwargs,
  119. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  120. **kwargs,
  121. )
  122. return_for_image_generation = output_kwargs["text_kwargs"].pop("return_for_image_generation", False)
  123. ratio = output_kwargs["images_kwargs"].pop("ratio", None)
  124. image_area = output_kwargs["images_kwargs"].pop("image_area", None)
  125. if return_for_image_generation and images is not None:
  126. raise ValueError("You should not provide `images` when `return_for_image_generation=True`")
  127. if not return_for_image_generation and text is None and images is None:
  128. raise ValueError("You must provide either text or images when `return_for_image_generation=False`")
  129. image_features = {}
  130. image_start_tokens = f"{self.image_start_token}"
  131. image_end_tokens = f"{self.eof_token}{self.image_end_token}"
  132. # generate text from image + text input, so we add placeholders for image tokens
  133. if not return_for_image_generation and images is not None:
  134. image_features = self.image_processor(images, **output_kwargs["images_kwargs"])
  135. image_sizes = iter(image_features.image_sizes)
  136. prompt_strings = []
  137. for sample in text:
  138. while self.image_token in sample:
  139. image_size = next(image_sizes)
  140. height, width = image_size
  141. height = height // self.downsample_ratio
  142. width = width // self.downsample_ratio
  143. image_seq_length = height * (width + 1) # +1 for extra row when converting to BPE in modeling code
  144. image_placeholder = f"{image_start_tokens}{height}*{width}{self.fake_token_around_image}{'<placeholder>' * image_seq_length}{image_end_tokens}"
  145. sample = sample.replace(self.image_token, image_placeholder, 1)
  146. sample = f"{self.bos_token}{sample}" # add BOS because GPT tokenizer doesn't add it
  147. prompt_strings.append(sample)
  148. text = [sample.replace("<placeholder>", self.image_token) for sample in prompt_strings]
  149. # generate image from text input, so we add begin-of-image tokens from where image generation starts
  150. elif return_for_image_generation:
  151. height, width = self.calculate_generate_size(ratio, image_area, self.downsample_ratio)
  152. image_prompt = f"{image_start_tokens}{height}*{width}{self.fake_token_around_image}"
  153. text = [f"{self.bos_token}{sample}{image_prompt}" for sample in text]
  154. image_features["image_sizes"] = [[height, width]] * len(text)
  155. # else just generate from text-only input, and we do no special treatment for text
  156. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  157. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
  158. text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"], return_tensors=None)
  159. self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
  160. if return_mm_token_type_ids:
  161. array_ids = np.array(text_inputs["input_ids"])
  162. mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])
  163. mm_token_type_ids[array_ids == self.image_token_id] = 1
  164. text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()
  165. return BatchFeature(data={**text_inputs, **image_features}, tensor_type=return_tensors)
  166. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  167. """
  168. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  169. Args:
  170. image_sizes (`list[list[int]]`, *optional*):
  171. The input sizes formatted as (height, width) per each image.
  172. Returns:
  173. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  174. input modalities, along with other useful data.
  175. """
  176. vision_data = {}
  177. if image_sizes is not None:
  178. num_image_tokens = []
  179. for height, width in image_sizes:
  180. height, width = smart_resize(
  181. height,
  182. width,
  183. self.image_processor.spatial_factor,
  184. self.image_processor.min_pixels,
  185. self.image_processor.max_pixels,
  186. )
  187. height = height // self.downsample_ratio
  188. width = width // self.downsample_ratio
  189. image_seq_length = height * (width + 1) # +1 for extra row when converting to BPE in modeling code
  190. num_image_tokens.append(image_seq_length)
  191. num_image_patches = [1] * len(image_sizes)
  192. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  193. return MultiModalData(**vision_data)
  194. def calculate_generate_size(self, ratio, image_area, spatial_factor):
  195. width, height = map(int, ratio.split(":"))
  196. current_area = width * height
  197. target_ratio = (image_area / current_area) ** 0.5
  198. token_height = int(round(height * target_ratio / spatial_factor))
  199. token_width = int(round(width * target_ratio / spatial_factor))
  200. return token_height, token_width
  201. def postprocess(self, images: ImageInput, **kwargs):
  202. return self.image_processor.postprocess(images, **kwargs)
  203. __all__ = ["Emu3Processor"]