processing_instructblipvideo.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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 InstructBLIP. Largely copy of Blip2Processor with addition of a tokenizer for the Q-Former.
  16. """
  17. from ...image_processing_utils import BatchFeature
  18. from ...processing_utils import ProcessorMixin
  19. from ...tokenization_utils_base import (
  20. AddedToken,
  21. PaddingStrategy,
  22. PreTokenizedInput,
  23. TextInput,
  24. TruncationStrategy,
  25. )
  26. from ...utils import TensorType, auto_docstring, logging
  27. from ...video_utils import VideoInput
  28. logger = logging.get_logger(__name__)
  29. @auto_docstring
  30. class InstructBlipVideoProcessor(ProcessorMixin):
  31. def __init__(self, video_processor, tokenizer, qformer_tokenizer, num_query_tokens=None, **kwargs):
  32. r"""
  33. qformer_tokenizer (`AutoTokenizer`):
  34. An instance of ['PreTrainedTokenizer`]. The Q-Former tokenizer is a required input.
  35. num_query_tokens (`int`, *optional*):
  36. Number of tokens used by the Qformer as queries, should be same as in model's config.
  37. """
  38. if not hasattr(tokenizer, "video_token"):
  39. self.video_token = AddedToken("<video>", normalized=False, special=True)
  40. tokenizer.add_tokens([self.video_token], special_tokens=True)
  41. else:
  42. self.video_token = tokenizer.video_token
  43. self.num_query_tokens = num_query_tokens
  44. super().__init__(video_processor, tokenizer, qformer_tokenizer)
  45. @auto_docstring
  46. def __call__(
  47. self,
  48. images: VideoInput | None = None,
  49. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  50. add_special_tokens: bool = True,
  51. padding: bool | str | PaddingStrategy = False,
  52. truncation: bool | str | TruncationStrategy = None,
  53. max_length: int | None = None,
  54. stride: int = 0,
  55. pad_to_multiple_of: int | None = None,
  56. return_attention_mask: bool | None = None,
  57. return_overflowing_tokens: bool = False,
  58. return_special_tokens_mask: bool = False,
  59. return_offsets_mapping: bool = False,
  60. return_token_type_ids: bool = False,
  61. return_length: bool = False,
  62. verbose: bool = True,
  63. return_tensors: str | TensorType | None = None,
  64. **kwargs,
  65. ) -> BatchFeature:
  66. if images is None and text is None:
  67. raise ValueError("You have to specify at least one of images or text.")
  68. encoding = {}
  69. if text is not None:
  70. if isinstance(text, str):
  71. text = [text]
  72. elif not isinstance(text, list) and not isinstance(text[0], str):
  73. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  74. qformer_text_encoding = self.qformer_tokenizer(
  75. text=text,
  76. add_special_tokens=add_special_tokens,
  77. padding=padding,
  78. truncation=truncation,
  79. max_length=max_length,
  80. stride=stride,
  81. pad_to_multiple_of=pad_to_multiple_of,
  82. return_attention_mask=return_attention_mask,
  83. return_overflowing_tokens=return_overflowing_tokens,
  84. return_special_tokens_mask=return_special_tokens_mask,
  85. return_offsets_mapping=return_offsets_mapping,
  86. return_token_type_ids=return_token_type_ids,
  87. return_length=return_length,
  88. verbose=verbose,
  89. return_tensors=return_tensors,
  90. **kwargs,
  91. )
  92. encoding["qformer_input_ids"] = qformer_text_encoding.pop("input_ids")
  93. encoding["qformer_attention_mask"] = qformer_text_encoding.pop("attention_mask")
  94. # We need this hacky manipulation because BLIP expects image tokens to be at the beginning even before BOS token
  95. # InstrucBLIP works with 4 frames only
  96. if max_length is not None:
  97. max_length -= self.num_query_tokens
  98. text_encoding = self.tokenizer(
  99. text=text,
  100. add_special_tokens=add_special_tokens,
  101. padding=padding,
  102. truncation=truncation,
  103. max_length=max_length,
  104. stride=stride,
  105. pad_to_multiple_of=pad_to_multiple_of,
  106. return_attention_mask=return_attention_mask,
  107. return_overflowing_tokens=return_overflowing_tokens,
  108. return_special_tokens_mask=return_special_tokens_mask,
  109. return_offsets_mapping=return_offsets_mapping,
  110. return_token_type_ids=return_token_type_ids,
  111. return_length=return_length,
  112. verbose=verbose,
  113. return_tensors=None, # required to concatenate below
  114. **kwargs,
  115. )
  116. if images is not None:
  117. video_tokens = self.video_token.content * self.num_query_tokens * 4
  118. video_text_encoding = self.tokenizer(
  119. video_tokens,
  120. add_special_tokens=False, # required to concatenate below
  121. return_attention_mask=return_attention_mask,
  122. return_overflowing_tokens=return_overflowing_tokens,
  123. return_special_tokens_mask=return_special_tokens_mask,
  124. return_offsets_mapping=return_offsets_mapping,
  125. return_token_type_ids=return_token_type_ids,
  126. return_length=return_length,
  127. return_tensors=None,
  128. )
  129. for k in text_encoding:
  130. text_encoding[k] = [video_text_encoding[k] + sample for sample in text_encoding[k]]
  131. encoding.update(text_encoding)
  132. if images is not None:
  133. image_encoding = self.video_processor(images, return_tensors=return_tensors)
  134. encoding.update(image_encoding)
  135. encoding = BatchFeature(encoding, tensor_type=return_tensors)
  136. return encoding
  137. @property
  138. def model_input_names(self):
  139. tokenizer_input_names = self.tokenizer.model_input_names
  140. video_processor_input_names = self.video_processor.model_input_names
  141. qformer_input_names = ["qformer_input_ids", "qformer_attention_mask"]
  142. return tokenizer_input_names + video_processor_input_names + qformer_input_names
  143. __all__ = ["InstructBlipVideoProcessor"]