processing_idefics2.py 11 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 IDEFICS2.
  17. """
  18. from typing import TYPE_CHECKING, List, Optional, Union
  19. from ...feature_extraction_utils import BatchFeature
  20. from ...image_utils import ImageInput, is_valid_image, load_image
  21. from ...processing_utils import (
  22. ImagesKwargs,
  23. ProcessingKwargs,
  24. ProcessorMixin,
  25. Unpack,
  26. _validate_images_text_input_order,
  27. )
  28. from ...tokenization_utils_base import AddedToken, TextInput
  29. from ...utils import logging
  30. if TYPE_CHECKING:
  31. from ...tokenization_utils_base import PreTokenizedInput
  32. logger = logging.get_logger(__name__)
  33. def is_url(val) -> bool:
  34. return isinstance(val, str) and val.startswith("http")
  35. def is_image_or_image_url(elem):
  36. return is_url(elem) or is_valid_image(elem)
  37. class Idefics2ImagesKwargs(ImagesKwargs, total=False):
  38. image_seq_len: Optional[int]
  39. class Idefics2ProcessorKwargs(ProcessingKwargs, total=False):
  40. images_kwargs: Idefics2ImagesKwargs
  41. _defaults = {
  42. "text_kwargs": {
  43. "add_special_tokens": True,
  44. "padding": False,
  45. "is_split_into_words": False,
  46. },
  47. "images_kwargs": {},
  48. }
  49. class Idefics2Processor(ProcessorMixin):
  50. r"""
  51. Constructs a IDEFICS2 processor which wraps a LLama tokenizer and IDEFICS2 image processor into a single processor.
  52. [`IdeficsProcessor`] offers all the functionalities of [`Idefics2ImageProcessor`] and [`LlamaTokenizerFast`]. See
  53. the docstring of [`~IdeficsProcessor.__call__`] and [`~IdeficsProcessor.decode`] for more information.
  54. Args:
  55. image_processor (`Idefics2ImageProcessor`):
  56. An instance of [`Idefics2ImageProcessor`]. The image processor is a required input.
  57. tokenizer (`PreTrainedTokenizerBase`, *optional*):
  58. An instance of [`PreTrainedTokenizerBase`]. This should correspond with the model's text model. The tokenizer is a required input.
  59. image_seq_len (`int`, *optional*, defaults to 64):
  60. The length of the image sequence i.e. the number of <image> tokens per image in the input.
  61. This parameter is used to build the string from the input prompt and image tokens and should match the
  62. config.perceiver_config.resampler_n_latents value for the model used.
  63. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  64. in a chat into a tokenizable string.
  65. """
  66. attributes = ["image_processor", "tokenizer"]
  67. valid_kwargs = ["image_seq_len", "chat_template"]
  68. image_processor_class = "Idefics2ImageProcessor"
  69. tokenizer_class = "AutoTokenizer"
  70. def __init__(self, image_processor, tokenizer=None, image_seq_len: int = 64, chat_template: str = None, **kwargs):
  71. if image_processor is None:
  72. raise ValueError("You need to specify an `image_processor`.")
  73. if tokenizer is None:
  74. raise ValueError("You need to specify a `tokenizer`.")
  75. self.fake_image_token = AddedToken("<fake_token_around_image>", normalized=False, special=True)
  76. self.image_token = AddedToken("<image>", normalized=False, special=True)
  77. self.end_of_utterance_token = AddedToken("<end_of_utterance>", normalized=False, special=True)
  78. self.image_seq_len = image_seq_len
  79. tokens_to_add = {
  80. "additional_special_tokens": [self.fake_image_token, self.image_token, self.end_of_utterance_token]
  81. }
  82. tokenizer.add_special_tokens(tokens_to_add)
  83. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  84. def _extract_images_from_prompts(self, prompts):
  85. prompt_images = []
  86. for prompt in prompts:
  87. images = []
  88. for elem in prompt:
  89. if is_valid_image(elem):
  90. images.append(elem)
  91. elif is_url(elem):
  92. images.append(load_image(elem))
  93. prompt_images.append(images)
  94. return prompt_images
  95. def __call__(
  96. self,
  97. images: Union[ImageInput, List[ImageInput], List[List[ImageInput]]] = None,
  98. text: Union[TextInput, "PreTokenizedInput", List[TextInput], List["PreTokenizedInput"]] = None,
  99. audio=None,
  100. videos=None,
  101. **kwargs: Unpack[Idefics2ProcessorKwargs],
  102. ) -> BatchFeature:
  103. """
  104. Processes the input prompts and returns a BatchEncoding.
  105. Example:
  106. ```python
  107. >>> import requests
  108. >>> from transformers import Idefics2Processor
  109. >>> from transformers.image_utils import load_image
  110. >>> processor = Idefics2Processor.from_pretrained("HuggingFaceM4/idefics2-8b", image_seq_len=2)
  111. >>> processor.image_processor.do_image_splitting = False # Force as False to simplify the example
  112. >>> url1 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
  113. >>> url2 = "https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg"
  114. >>> image1, image2 = load_image(url1), load_image(url2)
  115. >>> images = [[image1], [image2]]
  116. >>> text = [
  117. ... "<image>In this image, we see",
  118. ... "bla bla bla<image>",
  119. ... ]
  120. >>> outputs = processor(images=images, text=text, return_tensors="pt", padding=True)
  121. >>> input_ids = outputs.input_ids
  122. >>> input_tokens = processor.tokenizer.batch_decode(input_ids)
  123. >>> print(input_tokens)
  124. ['<s><fake_token_around_image><image><image><fake_token_around_image> In this image, we see', '<s> bla bla bla<fake_token_around_image><image><image><fake_token_around_image>']
  125. ```
  126. Args:
  127. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*):
  128. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  129. tensor. If is of type `List[ImageInput]`, it's assumed that this is for a single prompt i.e. of batch size 1.
  130. text (`Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]`, *optional*):
  131. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  132. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  133. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  134. Wherever an image token, `<image>` is encountered it is expanded to
  135. `<fake_token_around_image>` + `<image>` * `image_seq_len` * <fake_token_around_image>`.
  136. return_tensors (`Union[str, TensorType]`, *optional*):
  137. If set, will return tensors of a particular framework. See [`PreTrainedTokenizerFast.__call__`] for more
  138. information.
  139. """
  140. if text is None and images is None:
  141. raise ValueError("You must provide either `text` or `images`.")
  142. # check if images and text inputs are reversed for BC
  143. images, text = _validate_images_text_input_order(images, text)
  144. output_kwargs = self._merge_kwargs(
  145. Idefics2ProcessorKwargs,
  146. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  147. **kwargs,
  148. )
  149. image_seq_len = output_kwargs["images_kwargs"].pop("image_seq_len", None)
  150. image_seq_len = image_seq_len if image_seq_len is not None else self.image_seq_len
  151. n_images_in_text = []
  152. inputs = BatchFeature()
  153. if text is not None:
  154. if isinstance(text, str):
  155. text = [text]
  156. elif not isinstance(text, list) and not isinstance(text[0], str):
  157. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  158. # Replace the image token with fake tokens around the expanded image token sequence of length `image_seq_len`
  159. fake_image_token = self.fake_image_token.content
  160. image_token = self.image_token.content
  161. image_str = f"{fake_image_token}{image_token * image_seq_len}{fake_image_token}"
  162. if self.image_processor.do_image_splitting:
  163. # A single image token is split into 4 patches + 1 original image
  164. image_str = image_str * 5
  165. prompt_strings = []
  166. for sample in text:
  167. n_images_in_text.append(sample.count(image_token))
  168. sample = sample.replace(image_token, image_str)
  169. # Remove any double fake tokens if images are adjacent
  170. sample = sample.replace(f"{fake_image_token}{fake_image_token}", f"{fake_image_token}")
  171. prompt_strings.append(sample)
  172. text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"])
  173. inputs.update(text_inputs)
  174. if images is not None:
  175. if is_image_or_image_url(images):
  176. images = [[images]]
  177. elif isinstance(images, list) and is_image_or_image_url(images[0]):
  178. images = [images]
  179. elif (
  180. not isinstance(images, list)
  181. and not isinstance(images[0], list)
  182. and not is_image_or_image_url(images[0][0])
  183. ):
  184. raise ValueError(
  185. "Invalid input images. Please provide a single image or a list of images or a list of list of images."
  186. )
  187. n_images_in_images = [len(sample) for sample in images]
  188. if text is not None and not n_images_in_images == n_images_in_text:
  189. raise ValueError(
  190. f"The number of images in the text {n_images_in_text} and images {n_images_in_images} should be the same."
  191. )
  192. # Load images if they are URLs
  193. images = [[load_image(im) for im in sample] for sample in images]
  194. image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  195. inputs.update(image_inputs)
  196. return inputs
  197. def batch_decode(self, *args, **kwargs):
  198. """
  199. This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  200. refer to the docstring of this method for more information.
  201. """
  202. return self.tokenizer.batch_decode(*args, **kwargs)
  203. def decode(self, *args, **kwargs):
  204. """
  205. This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
  206. the docstring of this method for more information.
  207. """
  208. return self.tokenizer.decode(*args, **kwargs)
  209. @property
  210. def model_input_names(self):
  211. tokenizer_input_names = self.tokenizer.model_input_names
  212. image_processor_input_names = self.image_processor.model_input_names
  213. return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))