processing_llava.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # coding=utf-8
  2. # Copyright 2023 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 Llava.
  17. """
  18. from typing import List, Union
  19. from ...feature_extraction_utils import BatchFeature
  20. from ...image_utils import ImageInput, get_image_size, to_numpy_array
  21. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, _validate_images_text_input_order
  22. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  23. from ...utils import logging
  24. logger = logging.get_logger(__name__)
  25. class LlavaProcessorKwargs(ProcessingKwargs, total=False):
  26. _defaults = {
  27. "text_kwargs": {
  28. "padding": False,
  29. },
  30. "images_kwargs": {},
  31. }
  32. class LlavaProcessor(ProcessorMixin):
  33. r"""
  34. Constructs a Llava processor which wraps a Llava image processor and a Llava tokenizer into a single processor.
  35. [`LlavaProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`LlamaTokenizerFast`]. See the
  36. [`~LlavaProcessor.__call__`] and [`~LlavaProcessor.decode`] for more information.
  37. Args:
  38. image_processor ([`CLIPImageProcessor`], *optional*):
  39. The image processor is a required input.
  40. tokenizer ([`LlamaTokenizerFast`], *optional*):
  41. The tokenizer is a required input.
  42. patch_size (`int`, *optional*):
  43. Patch size from the vision tower.
  44. vision_feature_select_strategy (`str`, *optional*):
  45. The feature selection strategy used to select the vision feature from the vision backbone.
  46. Shoudl be same as in model's config
  47. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
  48. in a chat into a tokenizable string.
  49. image_token (`str`, *optional*, defaults to `"<image>"`):
  50. Special token used to denote image location.
  51. """
  52. attributes = ["image_processor", "tokenizer"]
  53. valid_kwargs = ["chat_template", "patch_size", "vision_feature_select_strategy", "image_token"]
  54. image_processor_class = "AutoImageProcessor"
  55. tokenizer_class = "AutoTokenizer"
  56. def __init__(
  57. self,
  58. image_processor=None,
  59. tokenizer=None,
  60. patch_size=None,
  61. vision_feature_select_strategy=None,
  62. chat_template=None,
  63. image_token="<image>", # set the default and let users change if they have peculiar special tokens in rare cases
  64. **kwargs,
  65. ):
  66. self.patch_size = patch_size
  67. self.vision_feature_select_strategy = vision_feature_select_strategy
  68. self.image_token = image_token
  69. super().__init__(image_processor, tokenizer, chat_template=chat_template)
  70. def __call__(
  71. self,
  72. images: ImageInput = None,
  73. text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
  74. audio=None,
  75. videos=None,
  76. **kwargs: Unpack[LlavaProcessorKwargs],
  77. ) -> BatchFeature:
  78. """
  79. Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
  80. and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
  81. the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
  82. CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
  83. of the above two methods for more information.
  84. Args:
  85. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
  86. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  87. tensor. Both channels-first and channels-last formats are supported.
  88. text (`str`, `List[str]`, `List[List[str]]`):
  89. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  90. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  91. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  92. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  93. If set, will return tensors of a particular framework. Acceptable values are:
  94. - `'tf'`: Return TensorFlow `tf.constant` objects.
  95. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  96. - `'np'`: Return NumPy `np.ndarray` objects.
  97. - `'jax'`: Return JAX `jnp.ndarray` objects.
  98. Returns:
  99. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  100. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  101. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  102. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  103. `None`).
  104. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  105. """
  106. if images is None and text is None:
  107. raise ValueError("You have to specify at least one of `images` or `text`.")
  108. # check if images and text inputs are reversed for BC
  109. images, text = _validate_images_text_input_order(images, text)
  110. output_kwargs = self._merge_kwargs(
  111. LlavaProcessorKwargs,
  112. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  113. **kwargs,
  114. )
  115. if images is not None:
  116. image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  117. else:
  118. image_inputs = {}
  119. if isinstance(text, str):
  120. text = [text]
  121. elif not isinstance(text, list) and not isinstance(text[0], str):
  122. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  123. # try to expand inputs in processing if we have the necessary parts
  124. prompt_strings = text
  125. if image_inputs.get("pixel_values") is not None:
  126. if self.patch_size is not None and self.vision_feature_select_strategy is not None:
  127. # Replace the image token with the expanded image token sequence
  128. pixel_values = image_inputs["pixel_values"]
  129. height, width = get_image_size(to_numpy_array(pixel_values[0]))
  130. num_image_tokens = (height // self.patch_size) * (width // self.patch_size) + 1
  131. if self.vision_feature_select_strategy == "default":
  132. num_image_tokens -= 1
  133. prompt_strings = []
  134. for sample in text:
  135. sample = sample.replace(self.image_token, self.image_token * num_image_tokens)
  136. prompt_strings.append(sample)
  137. else:
  138. logger.warning_once(
  139. "Expanding inputs for image tokens in LLaVa should be done in processing. "
  140. "Please add `patch_size` and `vision_feature_select_strategy` to the model's processing config or set directly "
  141. "with `processor.patch_size = {{patch_size}}` and processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}`. "
  142. "Using processors without these attributes in the config is deprecated and will throw an error in v4.47."
  143. )
  144. text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"])
  145. return BatchFeature(data={**text_inputs, **image_inputs})
  146. # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
  147. def batch_decode(self, *args, **kwargs):
  148. """
  149. This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
  150. refer to the docstring of this method for more information.
  151. """
  152. return self.tokenizer.batch_decode(*args, **kwargs)
  153. # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
  154. def decode(self, *args, **kwargs):
  155. """
  156. This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
  157. the docstring of this method for more information.
  158. """
  159. return self.tokenizer.decode(*args, **kwargs)
  160. @property
  161. # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
  162. def model_input_names(self):
  163. tokenizer_input_names = self.tokenizer.model_input_names
  164. image_processor_input_names = self.image_processor.model_input_names
  165. return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))