processing_idefics2.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # Copyright 2024 The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Processor class for IDEFICS2.
  16. """
  17. import re
  18. from itertools import accumulate
  19. from typing import TYPE_CHECKING, Union
  20. from ...feature_extraction_utils import BatchFeature
  21. from ...image_utils import ImageInput, is_valid_image, load_image
  22. from ...processing_utils import (
  23. ProcessingKwargs,
  24. ProcessorMixin,
  25. Unpack,
  26. )
  27. from ...tokenization_utils_base import AddedToken, TextInput
  28. from ...utils import auto_docstring, logging
  29. if TYPE_CHECKING:
  30. from ...tokenization_utils_base import PreTokenizedInput
  31. logger = logging.get_logger(__name__)
  32. def is_url(val) -> bool:
  33. return isinstance(val, str) and val.startswith("http")
  34. def is_image_or_image_url(elem):
  35. return is_url(elem) or is_valid_image(elem)
  36. class Idefics2ProcessorKwargs(ProcessingKwargs, total=False):
  37. _defaults = {
  38. "text_kwargs": {
  39. "add_special_tokens": True,
  40. "padding": False,
  41. "is_split_into_words": False,
  42. },
  43. }
  44. @auto_docstring
  45. class Idefics2Processor(ProcessorMixin):
  46. def __init__(
  47. self, image_processor, tokenizer=None, image_seq_len: int = 64, chat_template: str | None = None, **kwargs
  48. ):
  49. r"""
  50. image_seq_len (`int`, *optional*, defaults to 64):
  51. The length of the image sequence i.e. the number of <image> tokens per image in the input.
  52. This parameter is used to build the string from the input prompt and image tokens and should match the
  53. config.perceiver_config.resampler_n_latents value for the model used.
  54. """
  55. if not hasattr(tokenizer, "image_token"):
  56. self.fake_image_token = AddedToken("<fake_token_around_image>", normalized=False, special=True).content
  57. self.image_token = AddedToken("<image>", normalized=False, special=True).content
  58. tokens_to_add = {"additional_special_tokens": [self.fake_image_token, self.image_token]}
  59. tokenizer.add_special_tokens(tokens_to_add)
  60. self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
  61. else:
  62. self.fake_image_token = tokenizer.image_boundary_token
  63. self.image_token = tokenizer.image_token
  64. self.image_token_id = tokenizer.image_token_id
  65. self.end_of_utterance_token = AddedToken("<end_of_utterance>", normalized=False, special=True)
  66. tokenizer.add_special_tokens({"additional_special_tokens": [self.end_of_utterance_token]})
  67. self.image_seq_len = image_seq_len
  68. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  69. def _extract_images_from_prompts(self, prompts):
  70. prompt_images = []
  71. for prompt in prompts:
  72. images = []
  73. for elem in prompt:
  74. if is_valid_image(elem):
  75. images.append(elem)
  76. elif is_url(elem):
  77. images.append(load_image(elem))
  78. prompt_images.append(images)
  79. return prompt_images
  80. @auto_docstring
  81. def __call__(
  82. self,
  83. images: ImageInput | list[ImageInput] | list[list[ImageInput]] = None,
  84. text: Union[TextInput, "PreTokenizedInput", list[TextInput], list["PreTokenizedInput"]] = None,
  85. **kwargs: Unpack[Idefics2ProcessorKwargs],
  86. ) -> BatchFeature:
  87. if text is None and images is None:
  88. raise ValueError("You must provide either `text` or `images`.")
  89. output_kwargs = self._merge_kwargs(
  90. Idefics2ProcessorKwargs,
  91. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  92. **kwargs,
  93. )
  94. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  95. n_images_in_text = []
  96. inputs = {}
  97. if text is not None:
  98. if isinstance(text, str):
  99. text = [text]
  100. elif not isinstance(text, list) and not isinstance(text[0], str):
  101. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  102. # Replace the image token with fake tokens around the expanded image token sequence of length `image_seq_len`
  103. fake_image_token = self.fake_image_token
  104. image_token = self.image_token
  105. image_str = f"{fake_image_token}{image_token * self.image_seq_len}{fake_image_token}"
  106. if self.image_processor.do_image_splitting:
  107. # A single image token is split into 4 patches + 1 original image
  108. image_str = image_str * 5
  109. prompt_strings = []
  110. closing_fake_pattern = re.compile(rf"{re.escape(fake_image_token)}(?=[^\s<])")
  111. for sample in text:
  112. n_images_in_text.append(sample.count(image_token))
  113. sample = sample.replace(image_token, image_str)
  114. # Remove any double fake tokens if images are adjacent
  115. sample = sample.replace(f"{fake_image_token}{fake_image_token}", f"{fake_image_token}")
  116. # Ensure words attached directly after the closing fake token remain word-boundary aligned
  117. sample = closing_fake_pattern.sub(f"{fake_image_token} ", sample)
  118. prompt_strings.append(sample)
  119. text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"])
  120. self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
  121. inputs.update(text_inputs)
  122. if images is not None:
  123. if is_image_or_image_url(images):
  124. images = [[images]]
  125. elif isinstance(images, (list, tuple)) and is_image_or_image_url(images[0]):
  126. if text is not None:
  127. if sum(n_images_in_text) != len(images):
  128. raise ValueError(
  129. f"The total number of {image_token} tokens in the prompts should be the same as the number of images passed."
  130. f" Found {sum(n_images_in_text)} {image_token} tokens and {len(images)} images."
  131. )
  132. # Reorganize the images to match the prompts
  133. cumsum_images_in_text = [0] + list(accumulate(n_images_in_text))
  134. images = [
  135. images[cumsum_images_in_text[i] : cumsum_images_in_text[i + 1]]
  136. for i in range(len(n_images_in_text))
  137. ]
  138. else:
  139. images = [images]
  140. elif (
  141. not isinstance(images, (list, tuple))
  142. and not isinstance(images[0], (list, tuple))
  143. and not is_image_or_image_url(images[0][0])
  144. ):
  145. raise ValueError(
  146. "Invalid input images. Please provide a single image or a list of images or a list of list of images."
  147. )
  148. n_images_in_images = [len(sample) for sample in images]
  149. if text is not None and not n_images_in_images == n_images_in_text:
  150. raise ValueError(
  151. f"The number of images in the text {n_images_in_text} and images {n_images_in_images} should be the same."
  152. )
  153. # Load images if they are URLs
  154. images = [[load_image(im) for im in sample] for sample in images]
  155. image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  156. inputs.update(image_inputs)
  157. return BatchFeature(inputs, tensor_type=return_tensors)
  158. __all__ = ["Idefics2Processor"]