processing_pixtral.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # coding=utf-8
  2. # Copyright 2024 The HuggingFace Inc. team.
  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. """
  16. Processor class for Pixtral.
  17. """
  18. from typing import Optional, Union
  19. import numpy as np
  20. from ...feature_extraction_utils import BatchFeature
  21. from ...image_utils import ImageInput, is_valid_image
  22. from ...processing_utils import (
  23. MultiModalData,
  24. ProcessingKwargs,
  25. ProcessorMixin,
  26. Unpack,
  27. )
  28. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  29. from ...utils import is_vision_available, logging
  30. if is_vision_available():
  31. from .image_processing_pixtral import get_resize_output_image_size
  32. logger = logging.get_logger(__name__)
  33. class PixtralProcessorKwargs(ProcessingKwargs, total=False):
  34. _defaults = {
  35. "text_kwargs": {
  36. "padding": False,
  37. "return_mm_token_type_ids": False,
  38. },
  39. "images_kwargs": {},
  40. "common_kwargs": {
  41. "return_tensors": "pt",
  42. },
  43. }
  44. # Copied from transformers.models.idefics2.processing_idefics2.is_url
  45. def is_url(val) -> bool:
  46. return isinstance(val, str) and val.startswith("http")
  47. # Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_url
  48. def is_image_or_image_url(elem):
  49. return is_url(elem) or is_valid_image(elem)
  50. class PixtralProcessor(ProcessorMixin):
  51. r"""
  52. Constructs a Pixtral processor which wraps a Pixtral image processor and a Pixtral tokenizer into a single processor.
  53. [`PixtralProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`LlamaTokenizerFast`]. See the
  54. [`~PixtralProcessor.__call__`] and [`~PixtralProcessor.decode`] for more information.
  55. Args:
  56. image_processor ([`PixtralImageProcessor`], *optional*):
  57. The image processor is a required input.
  58. tokenizer ([`LlamaTokenizerFast`], *optional*):
  59. The tokenizer is a required input.
  60. patch_size (`int`, *optional*, defaults to 16):
  61. Patch size from the vision tower.
  62. spatial_merge_size (`int`, *optional*, defaults to 1):
  63. The downsampling factor for the spatial merge operation.
  64. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  65. in a chat into a tokenizable string.
  66. image_token (`str`, *optional*, defaults to `"[IMG]"`):
  67. Special token used to denote image location.
  68. image_break_token (`str`, *optional*, defaults to `"[IMG_BREAK]"`):
  69. Special token used to denote the end of a line of pixels in an image.
  70. image_end_token (`str`, *optional*, defaults to `"[IMG_END]"`):
  71. Special token used to denote the end of an image input.
  72. """
  73. attributes = ["image_processor", "tokenizer"]
  74. image_processor_class = "AutoImageProcessor"
  75. tokenizer_class = "AutoTokenizer"
  76. def __init__(
  77. self,
  78. image_processor=None,
  79. tokenizer=None,
  80. patch_size: int = 16,
  81. spatial_merge_size: int = 1,
  82. chat_template=None,
  83. image_token="[IMG]", # set the default and let users change if they have peculiar special tokens in rare cases
  84. image_break_token="[IMG_BREAK]",
  85. image_end_token="[IMG_END]",
  86. **kwargs,
  87. ):
  88. self.patch_size = patch_size
  89. self.spatial_merge_size = spatial_merge_size
  90. self.image_token = image_token
  91. self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
  92. self.image_break_token = image_break_token
  93. self.image_end_token = image_end_token
  94. self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
  95. self.image_break_token_id = tokenizer.convert_tokens_to_ids(self.image_break_token)
  96. self.image_end_token_id = tokenizer.convert_tokens_to_ids(self.image_end_token)
  97. self.image_ids = [self.image_token_id, self.image_break_token_id, self.image_end_token_id]
  98. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  99. def __call__(
  100. self,
  101. images: Optional[ImageInput] = None,
  102. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  103. audio=None,
  104. videos=None,
  105. **kwargs: Unpack[PixtralProcessorKwargs],
  106. ) -> BatchFeature:
  107. """
  108. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  109. and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
  110. the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
  111. CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
  112. of the above two methods for more information.
  113. Args:
  114. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  115. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  116. tensor. Both channels-first and channels-last formats are supported.
  117. text (`str`, `list[str]`, `list[list[str]]`):
  118. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  119. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  120. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  121. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  122. If set, will return tensors of a particular framework. Acceptable values are:
  123. - `'tf'`: Return TensorFlow `tf.constant` objects.
  124. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  125. - `'np'`: Return NumPy `np.ndarray` objects.
  126. - `'jax'`: Return JAX `jnp.ndarray` objects.
  127. Returns:
  128. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  129. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  130. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  131. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  132. `None`).
  133. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  134. """
  135. output_kwargs = self._merge_kwargs(
  136. PixtralProcessorKwargs,
  137. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  138. **kwargs,
  139. )
  140. patch_size = self.patch_size * self.spatial_merge_size
  141. if images is not None:
  142. image_inputs = self.image_processor(images, patch_size=patch_size, **output_kwargs["images_kwargs"])
  143. else:
  144. image_inputs = {}
  145. if isinstance(text, str):
  146. text = [text]
  147. elif not isinstance(text, list) and not isinstance(text[0], str):
  148. raise TypeError("Invalid input text. Please provide a string, or a list of strings")
  149. # try to expand inputs in processing if we have the necessary parts
  150. prompt_strings = text
  151. if image_inputs.get("pixel_values") is not None:
  152. # Replace the image token with the expanded image token sequence
  153. image_sizes = iter(image_inputs["image_sizes"])
  154. prompt_strings = []
  155. replace_strings = []
  156. for sample in text:
  157. while self.image_token in sample:
  158. height, width = next(image_sizes)
  159. num_height_tokens = height // patch_size
  160. num_width_tokens = width // patch_size
  161. replace_tokens = [
  162. [self.image_token] * num_width_tokens + [self.image_break_token]
  163. ] * num_height_tokens
  164. # Flatten list
  165. replace_tokens = [item for sublist in replace_tokens for item in sublist]
  166. replace_tokens[-1] = self.image_end_token
  167. replace_str = "".join(replace_tokens)
  168. replace_strings.append(replace_str)
  169. sample = sample.replace(self.image_token, "<placeholder>", 1)
  170. while "<placeholder>" in sample:
  171. replace_str = replace_strings.pop(0)
  172. sample = sample.replace("<placeholder>", replace_str, 1)
  173. prompt_strings.append(sample)
  174. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  175. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
  176. text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"], return_tensors=None)
  177. self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
  178. if return_mm_token_type_ids:
  179. array_ids = np.array(text_inputs["input_ids"])
  180. mm_token_type_ids = np.zeros_like(text_inputs["input_ids"])
  181. mm_token_type_ids[np.isin(array_ids, self.image_ids)] = 1
  182. text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()
  183. return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
  184. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  185. """
  186. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  187. Args:
  188. image_sizes (`list[list[int]]`, *optional*):
  189. The input sizes formatted as (height, width) per each image.
  190. Returns:
  191. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  192. input modalities, along with other useful data.
  193. """
  194. vision_data = {}
  195. if image_sizes is not None:
  196. images_kwargs = PixtralProcessorKwargs._defaults.get("images_kwargs", {})
  197. images_kwargs.update(kwargs)
  198. size = images_kwargs.get("size", None) or self.image_processor.size
  199. patch_size = self.patch_size * self.spatial_merge_size
  200. num_image_tokens = []
  201. for height, width in image_sizes:
  202. resized_height, resized_width = get_resize_output_image_size(
  203. np.zeros((height, width, 3)),
  204. size=(size["longest_edge"], size["longest_edge"]),
  205. patch_size=(patch_size, patch_size),
  206. )
  207. num_height_tokens = resized_height // patch_size
  208. num_width_tokens = resized_width // patch_size
  209. num_image_tokens.append((num_width_tokens + 1) * num_height_tokens)
  210. num_image_patches = [1] * len(image_sizes)
  211. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  212. return MultiModalData(**vision_data)
  213. @property
  214. def model_input_names(self):
  215. tokenizer_input_names = self.tokenizer.model_input_names
  216. image_processor_input_names = self.image_processor.model_input_names
  217. return tokenizer_input_names + image_processor_input_names + ["image_sizes"]
  218. __all__ = ["PixtralProcessor"]