processing_instructblip.py 8.6 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 InstructBLIP. Largely copy of Blip2Processor with addition of a tokenizer for the Q-Former.
  17. """
  18. import os
  19. from typing import Optional, Union
  20. from ...image_processing_utils import BatchFeature
  21. from ...image_utils import ImageInput
  22. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
  23. from ...tokenization_utils_base import AddedToken, PreTokenizedInput, TextInput
  24. from ...utils import logging
  25. from ..auto import AutoTokenizer
  26. logger = logging.get_logger(__name__)
  27. class InstructBlipProcessorKwargs(ProcessingKwargs, total=False):
  28. _defaults = {
  29. "text_kwargs": {
  30. "add_special_tokens": True,
  31. "padding": False,
  32. "stride": 0,
  33. "return_overflowing_tokens": False,
  34. "return_special_tokens_mask": False,
  35. "return_offsets_mapping": False,
  36. "return_token_type_ids": False,
  37. "return_length": False,
  38. "verbose": True,
  39. },
  40. "images_kwargs": {},
  41. }
  42. class InstructBlipProcessor(ProcessorMixin):
  43. r"""
  44. Constructs an InstructBLIP processor which wraps a BLIP image processor and a LLaMa/T5 tokenizer into a single
  45. processor.
  46. [`InstructBlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`AutoTokenizer`]. See the
  47. docstring of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information.
  48. Args:
  49. image_processor (`BlipImageProcessor`):
  50. An instance of [`BlipImageProcessor`]. The image processor is a required input.
  51. tokenizer (`AutoTokenizer`):
  52. An instance of ['PreTrainedTokenizer`]. The tokenizer is a required input.
  53. qformer_tokenizer (`AutoTokenizer`):
  54. An instance of ['PreTrainedTokenizer`]. The Q-Former tokenizer is a required input.
  55. num_query_tokens (`int`, *optional*):"
  56. Number of tokens used by the Qformer as queries, should be same as in model's config.
  57. """
  58. attributes = ["image_processor", "tokenizer", "qformer_tokenizer"]
  59. image_processor_class = ("BlipImageProcessor", "BlipImageProcessorFast")
  60. tokenizer_class = "AutoTokenizer"
  61. qformer_tokenizer_class = "AutoTokenizer"
  62. def __init__(self, image_processor, tokenizer, qformer_tokenizer, num_query_tokens=None, **kwargs):
  63. if not hasattr(tokenizer, "image_token"):
  64. self.image_token = AddedToken("<image>", normalized=False, special=True)
  65. tokenizer.add_tokens([self.image_token], special_tokens=True)
  66. else:
  67. self.image_token = tokenizer.image_token
  68. self.num_query_tokens = num_query_tokens
  69. super().__init__(image_processor, tokenizer, qformer_tokenizer)
  70. def __call__(
  71. self,
  72. images: Optional[ImageInput] = None,
  73. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  74. audio=None,
  75. videos=None,
  76. **kwargs: Unpack[InstructBlipProcessorKwargs],
  77. ) -> BatchFeature:
  78. """
  79. This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
  80. [`BertTokenizerFast.__call__`] to prepare text for the model.
  81. Please refer to the docstring of the above two methods for more information.
  82. Args:
  83. images (`ImageInput`):
  84. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  85. tensor. Both channels-first and channels-last formats are supported.
  86. text (`TextInput`, `PreTokenizedInput`, `list[TextInput]`, `list[PreTokenizedInput]`):
  87. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  88. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  89. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  90. """
  91. if images is None and text is None:
  92. raise ValueError("You have to specify at least images or text.")
  93. output_kwargs = self._merge_kwargs(
  94. InstructBlipProcessorKwargs,
  95. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  96. **kwargs,
  97. )
  98. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  99. encoding = {}
  100. if text is not None:
  101. if isinstance(text, str):
  102. text = [text]
  103. elif not isinstance(text, list) and not isinstance(text[0], str):
  104. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  105. qformer_text_encoding = self.qformer_tokenizer(text, **output_kwargs["text_kwargs"])
  106. encoding["qformer_input_ids"] = qformer_text_encoding.pop("input_ids")
  107. encoding["qformer_attention_mask"] = qformer_text_encoding.pop("attention_mask")
  108. # We need this hacky manipulation because BLIP expects image tokens to be at the beginning even before BOS token
  109. if output_kwargs["text_kwargs"].get("max_length") is not None:
  110. output_kwargs["text_kwargs"]["max_length"] -= self.num_query_tokens
  111. text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
  112. if images is not None:
  113. # Image tokens should not be padded/truncated or prepended with special BOS token
  114. image_tokens = self.image_token.content * self.num_query_tokens
  115. output_kwargs["text_kwargs"]["add_special_tokens"] = False
  116. output_kwargs["text_kwargs"]["padding"] = False
  117. output_kwargs["text_kwargs"]["truncation"] = False
  118. image_text_encoding = self.tokenizer(image_tokens, **output_kwargs["text_kwargs"])
  119. for k in text_encoding:
  120. text_encoding[k] = [image_text_encoding[k] + sample for sample in text_encoding[k]]
  121. encoding.update(text_encoding)
  122. if images is not None:
  123. image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
  124. encoding.update(image_encoding)
  125. # Cast to desired return tensors type
  126. encoding = BatchFeature(encoding, tensor_type=return_tensors)
  127. return encoding
  128. @property
  129. def model_input_names(self):
  130. tokenizer_input_names = self.tokenizer.model_input_names
  131. image_processor_input_names = self.image_processor.model_input_names
  132. qformer_input_names = ["qformer_input_ids", "qformer_attention_mask"]
  133. return tokenizer_input_names + image_processor_input_names + qformer_input_names
  134. # overwrite to save the Q-Former tokenizer in a separate folder
  135. def save_pretrained(self, save_directory, **kwargs):
  136. if os.path.isfile(save_directory):
  137. raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")
  138. os.makedirs(save_directory, exist_ok=True)
  139. qformer_tokenizer_path = os.path.join(save_directory, "qformer_tokenizer")
  140. self.qformer_tokenizer.save_pretrained(qformer_tokenizer_path)
  141. # We modify the attributes so that only the tokenizer and image processor are saved in the main folder
  142. qformer_present = "qformer_tokenizer" in self.attributes
  143. if qformer_present:
  144. self.attributes.remove("qformer_tokenizer")
  145. outputs = super().save_pretrained(save_directory, **kwargs)
  146. if qformer_present:
  147. self.attributes += ["qformer_tokenizer"]
  148. return outputs
  149. # overwrite to load the Q-Former tokenizer from a separate folder
  150. @classmethod
  151. def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
  152. processor = super().from_pretrained(pretrained_model_name_or_path, **kwargs)
  153. # if return_unused_kwargs a tuple is returned where the second element is 'unused_kwargs'
  154. if isinstance(processor, tuple):
  155. processor = processor[0]
  156. qformer_tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder="qformer_tokenizer")
  157. processor.qformer_tokenizer = qformer_tokenizer
  158. return processor
  159. __all__ = ["InstructBlipProcessor"]