processing_instructblip.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 List, 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 (
  24. AddedToken,
  25. BatchEncoding,
  26. PreTokenizedInput,
  27. TextInput,
  28. )
  29. from ...utils import logging
  30. from ..auto import AutoTokenizer
  31. logger = logging.get_logger(__name__)
  32. class InstructBlipProcessorKwargs(ProcessingKwargs, total=False):
  33. _defaults = {
  34. "text_kwargs": {
  35. "add_special_tokens": True,
  36. "padding": False,
  37. "stride": 0,
  38. "return_overflowing_tokens": False,
  39. "return_special_tokens_mask": False,
  40. "return_offsets_mapping": False,
  41. "return_token_type_ids": False,
  42. "return_length": False,
  43. "verbose": True,
  44. },
  45. "images_kwargs": {},
  46. }
  47. class InstructBlipProcessor(ProcessorMixin):
  48. r"""
  49. Constructs an InstructBLIP processor which wraps a BLIP image processor and a LLaMa/T5 tokenizer into a single
  50. processor.
  51. [`InstructBlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`AutoTokenizer`]. See the
  52. docstring of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information.
  53. Args:
  54. image_processor (`BlipImageProcessor`):
  55. An instance of [`BlipImageProcessor`]. The image processor is a required input.
  56. tokenizer (`AutoTokenizer`):
  57. An instance of ['PreTrainedTokenizer`]. The tokenizer is a required input.
  58. qformer_tokenizer (`AutoTokenizer`):
  59. An instance of ['PreTrainedTokenizer`]. The Q-Former tokenizer is a required input.
  60. num_query_tokens (`int`, *optional*):"
  61. Number of tokens used by the Qformer as queries, should be same as in model's config.
  62. """
  63. attributes = ["image_processor", "tokenizer", "qformer_tokenizer"]
  64. valid_kwargs = ["num_query_tokens"]
  65. image_processor_class = "BlipImageProcessor"
  66. tokenizer_class = "AutoTokenizer"
  67. qformer_tokenizer_class = "AutoTokenizer"
  68. def __init__(self, image_processor, tokenizer, qformer_tokenizer, num_query_tokens=None, **kwargs):
  69. self.image_token = AddedToken("<image>", normalized=False, special=True)
  70. tokenizer.add_tokens([self.image_token], special_tokens=True)
  71. self.num_query_tokens = num_query_tokens
  72. super().__init__(image_processor, tokenizer, qformer_tokenizer)
  73. def __call__(
  74. self,
  75. images: ImageInput = None,
  76. text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
  77. audio=None,
  78. videos=None,
  79. **kwargs: Unpack[InstructBlipProcessorKwargs],
  80. ) -> BatchFeature:
  81. """
  82. This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
  83. [`BertTokenizerFast.__call__`] to prepare text for the model.
  84. Please refer to the docstring of the above two methods for more information.
  85. Args:
  86. images (`ImageInput`):
  87. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  88. tensor. Both channels-first and channels-last formats are supported.
  89. text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):
  90. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  91. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  92. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  93. """
  94. if images is None and text is None:
  95. raise ValueError("You have to specify at least images or text.")
  96. output_kwargs = self._merge_kwargs(
  97. InstructBlipProcessorKwargs,
  98. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  99. **kwargs,
  100. )
  101. encoding = BatchFeature()
  102. if text is not None:
  103. if isinstance(text, str):
  104. text = [text]
  105. elif not isinstance(text, list) and not isinstance(text[0], str):
  106. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  107. # we have to concatenate lists - so we keep track of return_tensors here
  108. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  109. _text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"], return_tensors=None)
  110. output_kwargs["text_kwargs"]["return_tensors"] = return_tensors
  111. # if we know how many query tokens, expand text inside processor. We need this hacky manipulation
  112. # because BLIP expects image tokens to be at the beginning even before BOS token
  113. if self.num_query_tokens is not None and images is not None:
  114. text_encoding = {}
  115. image_tokens = self.image_token.content * self.num_query_tokens
  116. image_token_encoding = self.tokenizer(
  117. [image_tokens] * len(text), add_special_tokens=False, return_tensors=None
  118. )
  119. for k in _text_encoding:
  120. text_encoding[k] = [
  121. img_encoding + txt_encoding
  122. for img_encoding, txt_encoding in zip(image_token_encoding[k], _text_encoding[k])
  123. ]
  124. else:
  125. text_encoding = _text_encoding
  126. if images is not None:
  127. logger.warning_once(
  128. "Expanding inputs for image tokens in InstructBLIP should be done in processing. "
  129. "Please follow instruction here (https://gist.github.com/zucchini-nlp/e9f20b054fa322f84ac9311d9ab67042) to update your InstructBLIP model. "
  130. "Using processors without these attributes in the config is deprecated and will throw an error in v4.47."
  131. )
  132. # cast to desired return tensors type after concatenating
  133. text_encoding = BatchEncoding(text_encoding, tensor_type=return_tensors)
  134. encoding.update(text_encoding)
  135. qformer_text_encoding = self.qformer_tokenizer(text, **output_kwargs["text_kwargs"])
  136. encoding["qformer_input_ids"] = qformer_text_encoding.pop("input_ids")
  137. encoding["qformer_attention_mask"] = qformer_text_encoding.pop("attention_mask")
  138. if images is not None:
  139. image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
  140. encoding.update(image_encoding)
  141. return encoding
  142. # Copied from transformers.models.blip.processing_blip.BlipProcessor.batch_decode with BertTokenizerFast->PreTrainedTokenizer
  143. def batch_decode(self, *args, **kwargs):
  144. """
  145. This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
  146. refer to the docstring of this method for more information.
  147. """
  148. return self.tokenizer.batch_decode(*args, **kwargs)
  149. # Copied from transformers.models.blip.processing_blip.BlipProcessor.decode with BertTokenizerFast->PreTrainedTokenizer
  150. def decode(self, *args, **kwargs):
  151. """
  152. This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
  153. the docstring of this method for more information.
  154. """
  155. return self.tokenizer.decode(*args, **kwargs)
  156. @property
  157. # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
  158. def model_input_names(self):
  159. tokenizer_input_names = self.tokenizer.model_input_names
  160. image_processor_input_names = self.image_processor.model_input_names
  161. return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
  162. # overwrite to save the Q-Former tokenizer in a separate folder
  163. def save_pretrained(self, save_directory, **kwargs):
  164. if os.path.isfile(save_directory):
  165. raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")
  166. os.makedirs(save_directory, exist_ok=True)
  167. qformer_tokenizer_path = os.path.join(save_directory, "qformer_tokenizer")
  168. self.qformer_tokenizer.save_pretrained(qformer_tokenizer_path)
  169. # We modify the attributes so that only the tokenizer and image processor are saved in the main folder
  170. qformer_present = "qformer_tokenizer" in self.attributes
  171. if qformer_present:
  172. self.attributes.remove("qformer_tokenizer")
  173. outputs = super().save_pretrained(save_directory, **kwargs)
  174. if qformer_present:
  175. self.attributes += ["qformer_tokenizer"]
  176. return outputs
  177. # overwrite to load the Q-Former tokenizer from a separate folder
  178. @classmethod
  179. def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
  180. processor = super().from_pretrained(pretrained_model_name_or_path, **kwargs)
  181. # if return_unused_kwargs a tuple is returned where the second element is 'unused_kwargs'
  182. if isinstance(processor, tuple):
  183. processor = processor[0]
  184. qformer_tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder="qformer_tokenizer")
  185. processor.qformer_tokenizer = qformer_tokenizer
  186. return processor