processing_instructblip.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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 ...image_utils import ImageInput
  19. from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
  20. from ...tokenization_utils_base import AddedToken, PreTokenizedInput, TextInput
  21. from ...utils import auto_docstring, logging
  22. logger = logging.get_logger(__name__)
  23. class InstructBlipProcessorKwargs(ProcessingKwargs, total=False):
  24. _defaults = {
  25. "text_kwargs": {
  26. "add_special_tokens": True,
  27. "padding": False,
  28. "stride": 0,
  29. "return_overflowing_tokens": False,
  30. "return_special_tokens_mask": False,
  31. "return_offsets_mapping": False,
  32. "return_token_type_ids": False,
  33. "return_length": False,
  34. "verbose": True,
  35. },
  36. }
  37. @auto_docstring
  38. class InstructBlipProcessor(ProcessorMixin):
  39. def __init__(self, image_processor, tokenizer, qformer_tokenizer, num_query_tokens=None, **kwargs):
  40. r"""
  41. qformer_tokenizer (`AutoTokenizer`):
  42. An instance of ['PreTrainedTokenizer`]. The Q-Former tokenizer is a required input.
  43. num_query_tokens (`int`, *optional*):
  44. "
  45. Number of tokens used by the Qformer as queries, should be same as in model's config.
  46. """
  47. if not hasattr(tokenizer, "image_token"):
  48. self.image_token = AddedToken("<image>", normalized=False, special=True)
  49. tokenizer.add_tokens([self.image_token], special_tokens=True)
  50. else:
  51. self.image_token = tokenizer.image_token
  52. self.num_query_tokens = num_query_tokens
  53. super().__init__(image_processor, tokenizer, qformer_tokenizer)
  54. @auto_docstring
  55. def __call__(
  56. self,
  57. images: ImageInput | None = None,
  58. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  59. **kwargs: Unpack[InstructBlipProcessorKwargs],
  60. ) -> BatchFeature:
  61. if images is None and text is None:
  62. raise ValueError("You have to specify at least images or text.")
  63. output_kwargs = self._merge_kwargs(
  64. InstructBlipProcessorKwargs,
  65. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  66. **kwargs,
  67. )
  68. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  69. encoding = {}
  70. if text is not None:
  71. if isinstance(text, str):
  72. text = [text]
  73. elif not isinstance(text, list) and not isinstance(text[0], str):
  74. raise ValueError("Invalid input text. Please provide a string, or a list of strings")
  75. qformer_text_encoding = self.qformer_tokenizer(text, **output_kwargs["text_kwargs"])
  76. encoding["qformer_input_ids"] = qformer_text_encoding.pop("input_ids")
  77. encoding["qformer_attention_mask"] = qformer_text_encoding.pop("attention_mask")
  78. # We need this hacky manipulation because BLIP expects image tokens to be at the beginning even before BOS token
  79. if output_kwargs["text_kwargs"].get("max_length") is not None:
  80. output_kwargs["text_kwargs"]["max_length"] -= self.num_query_tokens
  81. text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
  82. if images is not None:
  83. # Image tokens should not be padded/truncated or prepended with special BOS token
  84. image_tokens = self.image_token.content * self.num_query_tokens
  85. output_kwargs["text_kwargs"]["add_special_tokens"] = False
  86. output_kwargs["text_kwargs"]["padding"] = False
  87. output_kwargs["text_kwargs"]["truncation"] = False
  88. image_text_encoding = self.tokenizer(image_tokens, **output_kwargs["text_kwargs"])
  89. for k in text_encoding:
  90. text_encoding[k] = [image_text_encoding[k] + sample for sample in text_encoding[k]]
  91. encoding.update(text_encoding)
  92. if images is not None:
  93. image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
  94. encoding.update(image_encoding)
  95. # Cast to desired return tensors type
  96. encoding = BatchFeature(encoding, tensor_type=return_tensors)
  97. return encoding
  98. @property
  99. def model_input_names(self):
  100. tokenizer_input_names = self.tokenizer.model_input_names
  101. image_processor_input_names = self.image_processor.model_input_names
  102. qformer_input_names = ["qformer_input_ids", "qformer_attention_mask"]
  103. return tokenizer_input_names + image_processor_input_names + qformer_input_names
  104. __all__ = ["InstructBlipProcessor"]