processing_llava.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. # Copyright 2023 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 Llava.
  16. """
  17. from ...feature_extraction_utils import BatchFeature
  18. from ...image_utils import ImageInput, get_image_size, to_numpy_array
  19. from ...processing_utils import (
  20. MultiModalData,
  21. ProcessingKwargs,
  22. ProcessorMixin,
  23. Unpack,
  24. )
  25. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  26. from ...utils import auto_docstring, logging
  27. logger = logging.get_logger(__name__)
  28. class LlavaProcessorKwargs(ProcessingKwargs, total=False):
  29. _defaults = {
  30. "text_kwargs": {"padding": False, "return_mm_token_type_ids": False},
  31. }
  32. @auto_docstring
  33. class LlavaProcessor(ProcessorMixin):
  34. def __init__(
  35. self,
  36. image_processor=None,
  37. tokenizer=None,
  38. patch_size=None,
  39. vision_feature_select_strategy=None,
  40. chat_template=None,
  41. image_token="<image>", # set the default and let users change if they have peculiar special tokens in rare cases
  42. num_additional_image_tokens=0,
  43. **kwargs,
  44. ):
  45. r"""
  46. patch_size (`int`, *optional*):
  47. Patch size from the vision tower.
  48. vision_feature_select_strategy (`str`, *optional*):
  49. The feature selection strategy used to select the vision feature from the vision backbone.
  50. Should be same as in model's config
  51. image_token (`str`, *optional*, defaults to `"<image>"`):
  52. Special token used to denote image location.
  53. num_additional_image_tokens (`int`, *optional*, defaults to 0):
  54. Number of additional tokens added to the image embeddings, such as CLS (+1). If the backbone has no CLS or other
  55. extra tokens appended, no need to set this arg.
  56. """
  57. self.patch_size = patch_size
  58. self.num_additional_image_tokens = num_additional_image_tokens
  59. self.vision_feature_select_strategy = vision_feature_select_strategy
  60. self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token
  61. self.image_token_id = tokenizer.encode(self.image_token, add_special_tokens=False)[0]
  62. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  63. @auto_docstring
  64. def __call__(
  65. self,
  66. images: ImageInput | None = None,
  67. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  68. **kwargs: Unpack[LlavaProcessorKwargs],
  69. ) -> BatchFeature:
  70. r"""
  71. Returns:
  72. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  73. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  74. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  75. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  76. `None`).
  77. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  78. """
  79. if images is None and text is None:
  80. raise ValueError("You have to specify at least one of `images` or `text`.")
  81. output_kwargs = self._merge_kwargs(
  82. LlavaProcessorKwargs,
  83. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  84. **kwargs,
  85. )
  86. if images is not None:
  87. image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  88. else:
  89. image_inputs = {}
  90. if isinstance(text, str):
  91. text = [text]
  92. elif not isinstance(text, list) and not isinstance(text[0], str):
  93. raise TypeError("Invalid input text. Please provide a string, or a list of strings")
  94. # try to expand inputs in processing if we have the necessary parts
  95. prompt_strings = text
  96. if image_inputs.get("pixel_values") is not None:
  97. # Replace the image token with the expanded image token sequence
  98. pixel_values = image_inputs["pixel_values"]
  99. height, width = get_image_size(to_numpy_array(pixel_values[0]))
  100. num_image_tokens = (height // self.patch_size) * (
  101. width // self.patch_size
  102. ) + self.num_additional_image_tokens
  103. if self.vision_feature_select_strategy == "default":
  104. num_image_tokens -= 1
  105. prompt_strings = []
  106. for sample in text:
  107. sample = sample.replace(self.image_token, self.image_token * num_image_tokens)
  108. prompt_strings.append(sample)
  109. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  110. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
  111. text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"], return_tensors=None)
  112. self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
  113. if return_mm_token_type_ids:
  114. text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
  115. return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
  116. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  117. """
  118. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  119. Args:
  120. image_sizes (`list[list[int]]`, *optional*):
  121. The input sizes formatted as (height, width) per each image.
  122. Returns:
  123. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  124. input modalities, along with other useful data.
  125. """
  126. vision_data = {}
  127. if image_sizes is not None:
  128. images_kwargs = LlavaProcessorKwargs._defaults.get("images_kwargs", {})
  129. images_kwargs.update(kwargs)
  130. crop_size = images_kwargs.get("crop_size", None) or self.image_processor.crop_size
  131. resized_height, resized_width = crop_size["height"], crop_size["width"]
  132. num_image_tokens = (resized_height // self.patch_size) * (resized_width // self.patch_size)
  133. num_image_tokens += self.num_additional_image_tokens
  134. if self.vision_feature_select_strategy == "default":
  135. num_image_tokens -= 1
  136. num_image_tokens = [num_image_tokens] * len(image_sizes)
  137. num_image_patches = [1] * len(image_sizes)
  138. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  139. return MultiModalData(**vision_data)
  140. __all__ = ["LlavaProcessor"]