processing_instructblipvideo.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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 ...processing_utils import ProcessorMixin
  22. from ...tokenization_utils_base import (
  23. AddedToken,
  24. PaddingStrategy,
  25. PreTokenizedInput,
  26. TextInput,
  27. TruncationStrategy,
  28. )
  29. from ...utils import TensorType, logging
  30. from ...video_utils import VideoInput
  31. from ..auto import AutoTokenizer
  32. logger = logging.get_logger(__name__)
  33. class InstructBlipVideoProcessor(ProcessorMixin):
  34. r"""
  35. Constructs an InstructBLIPVideo processor which wraps a InstructBLIP image processor and a LLaMa/T5 tokenizer into a single
  36. processor.
  37. [`InstructBlipVideoProcessor`] offers all the functionalities of [`InstructBlipVideoImageProcessor`] and [`AutoTokenizer`]. See the
  38. docstring of [`~InstructBlipVideoProcessor.__call__`] and [`~InstructBlipVideoProcessor.decode`] for more information.
  39. Args:
  40. video_processor (`InstructBlipVideoVideoProcessor`):
  41. An instance of [`InstructBlipVideoVideoProcessor`]. The video processor is a required input.
  42. tokenizer (`AutoTokenizer`):
  43. An instance of ['PreTrainedTokenizer`]. The tokenizer is a required input.
  44. qformer_tokenizer (`AutoTokenizer`):
  45. An instance of ['PreTrainedTokenizer`]. The Q-Former tokenizer is a required input.
  46. num_query_tokens (`int`, *optional*):
  47. Number of tokens used by the Qformer as queries, should be same as in model's config.
  48. """
  49. attributes = ["video_processor", "tokenizer", "qformer_tokenizer"]
  50. video_processor_class = "AutoVideoProcessor"
  51. tokenizer_class = "AutoTokenizer"
  52. qformer_tokenizer_class = "AutoTokenizer"
  53. def __init__(self, video_processor, tokenizer, qformer_tokenizer, num_query_tokens=None, **kwargs):
  54. if not hasattr(tokenizer, "video_token"):
  55. self.video_token = AddedToken("<video>", normalized=False, special=True)
  56. tokenizer.add_tokens([self.video_token], special_tokens=True)
  57. else:
  58. self.video_token = tokenizer.video_token
  59. self.num_query_tokens = num_query_tokens
  60. super().__init__(video_processor, tokenizer, qformer_tokenizer)
  61. def __call__(
  62. self,
  63. images: Optional[VideoInput] = None,
  64. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  65. add_special_tokens: bool = True,
  66. padding: Union[bool, str, PaddingStrategy] = False,
  67. truncation: Union[bool, str, TruncationStrategy] = None,
  68. max_length: Optional[int] = None,
  69. stride: int = 0,
  70. pad_to_multiple_of: Optional[int] = None,
  71. return_attention_mask: Optional[bool] = None,
  72. return_overflowing_tokens: bool = False,
  73. return_special_tokens_mask: bool = False,
  74. return_offsets_mapping: bool = False,
  75. return_token_type_ids: bool = False,
  76. return_length: bool = False,
  77. verbose: bool = True,
  78. return_tensors: Optional[Union[str, TensorType]] = None,
  79. **kwargs,
  80. ) -> BatchFeature:
  81. """
  82. This method uses [`InstructBlipVideoImageProcessor.__call__`] method to prepare image(s) or video(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. """
  86. if images is None and text is None:
  87. raise ValueError("You have to specify at least one of images or text.")
  88. encoding = {}
  89. if text is not None:
  90. if isinstance(text, str):
  91. text = [text]
  92. elif not isinstance(text, list) and not isinstance(text[0], str):
  93. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  94. qformer_text_encoding = self.qformer_tokenizer(
  95. text=text,
  96. add_special_tokens=add_special_tokens,
  97. padding=padding,
  98. truncation=truncation,
  99. max_length=max_length,
  100. stride=stride,
  101. pad_to_multiple_of=pad_to_multiple_of,
  102. return_attention_mask=return_attention_mask,
  103. return_overflowing_tokens=return_overflowing_tokens,
  104. return_special_tokens_mask=return_special_tokens_mask,
  105. return_offsets_mapping=return_offsets_mapping,
  106. return_token_type_ids=return_token_type_ids,
  107. return_length=return_length,
  108. verbose=verbose,
  109. return_tensors=return_tensors,
  110. **kwargs,
  111. )
  112. encoding["qformer_input_ids"] = qformer_text_encoding.pop("input_ids")
  113. encoding["qformer_attention_mask"] = qformer_text_encoding.pop("attention_mask")
  114. # We need this hacky manipulation because BLIP expects image tokens to be at the beginning even before BOS token
  115. # InstrucBLIP works with 4 frames only
  116. if max_length is not None:
  117. max_length -= self.num_query_tokens
  118. text_encoding = self.tokenizer(
  119. text=text,
  120. add_special_tokens=add_special_tokens,
  121. padding=padding,
  122. truncation=truncation,
  123. max_length=max_length,
  124. stride=stride,
  125. pad_to_multiple_of=pad_to_multiple_of,
  126. return_attention_mask=return_attention_mask,
  127. return_overflowing_tokens=return_overflowing_tokens,
  128. return_special_tokens_mask=return_special_tokens_mask,
  129. return_offsets_mapping=return_offsets_mapping,
  130. return_token_type_ids=return_token_type_ids,
  131. return_length=return_length,
  132. verbose=verbose,
  133. return_tensors=None, # required to concatenate below
  134. **kwargs,
  135. )
  136. if images is not None:
  137. video_tokens = self.video_token.content * self.num_query_tokens * 4
  138. video_text_encoding = self.tokenizer(
  139. video_tokens,
  140. add_special_tokens=False, # required to concatenate below
  141. return_attention_mask=return_attention_mask,
  142. return_overflowing_tokens=return_overflowing_tokens,
  143. return_special_tokens_mask=return_special_tokens_mask,
  144. return_offsets_mapping=return_offsets_mapping,
  145. return_token_type_ids=return_token_type_ids,
  146. return_length=return_length,
  147. return_tensors=None,
  148. )
  149. for k in text_encoding:
  150. text_encoding[k] = [video_text_encoding[k] + sample for sample in text_encoding[k]]
  151. encoding.update(text_encoding)
  152. if images is not None:
  153. image_encoding = self.video_processor(images, return_tensors=return_tensors)
  154. encoding.update(image_encoding)
  155. encoding = BatchFeature(encoding, tensor_type=return_tensors)
  156. return encoding
  157. @property
  158. def model_input_names(self):
  159. tokenizer_input_names = self.tokenizer.model_input_names
  160. video_processor_input_names = self.video_processor.model_input_names
  161. qformer_input_names = ["qformer_input_ids", "qformer_attention_mask"]
  162. return tokenizer_input_names + video_processor_input_names + qformer_input_names
  163. # overwrite to save the Q-Former tokenizer in a separate folder
  164. def save_pretrained(self, save_directory, **kwargs):
  165. if os.path.isfile(save_directory):
  166. raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")
  167. os.makedirs(save_directory, exist_ok=True)
  168. qformer_tokenizer_path = os.path.join(save_directory, "qformer_tokenizer")
  169. self.qformer_tokenizer.save_pretrained(qformer_tokenizer_path)
  170. # We modify the attributes so that only the tokenizer and image processor are saved in the main folder
  171. qformer_present = "qformer_tokenizer" in self.attributes
  172. if qformer_present:
  173. self.attributes.remove("qformer_tokenizer")
  174. outputs = super().save_pretrained(save_directory, **kwargs)
  175. if qformer_present:
  176. self.attributes += ["qformer_tokenizer"]
  177. return outputs
  178. # overwrite to load the Q-Former tokenizer from a separate folder
  179. @classmethod
  180. def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
  181. processor = super().from_pretrained(pretrained_model_name_or_path, **kwargs)
  182. # if return_unused_kwargs a tuple is returned where the second element is 'unused_kwargs'
  183. if isinstance(processor, tuple):
  184. processor = processor[0]
  185. qformer_tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder="qformer_tokenizer")
  186. processor.qformer_tokenizer = qformer_tokenizer
  187. return processor
  188. __all__ = ["InstructBlipVideoProcessor"]