processing_chameleon.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. # Copyright 2024 Meta Inc. and The HuggingFace Inc. team. All rights reserved.
  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 Chameleon.
  16. """
  17. from ...feature_extraction_utils import BatchFeature
  18. from ...image_utils import ImageInput
  19. from ...processing_utils import (
  20. MultiModalData,
  21. ProcessingKwargs,
  22. ProcessorMixin,
  23. TextKwargs,
  24. Unpack,
  25. )
  26. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  27. from ...utils import auto_docstring
  28. class ChameleonTextKwargs(TextKwargs, total=False):
  29. """
  30. return_for_text_completion (`bool`, *optional*, defaults to `False`):
  31. Whether the processed text is intended for text completion tasks. When `True`, the processor does not
  32. append the separator token (`sep_token`) to the end of the prompt, which is typically used for chat
  33. mode. When `False`, the separator token is appended for proper chat formatting.
  34. """
  35. return_for_text_completion: bool
  36. class ChameleonProcessorKwargs(ProcessingKwargs, total=False):
  37. text_kwargs: ChameleonTextKwargs
  38. _defaults = {
  39. "text_kwargs": {
  40. "padding": False,
  41. "return_for_text_completion": False,
  42. "return_mm_token_type_ids": False,
  43. },
  44. "common_kwargs": {
  45. "return_tensors": "pt",
  46. },
  47. }
  48. @auto_docstring
  49. class ChameleonProcessor(ProcessorMixin):
  50. def __init__(self, image_processor, tokenizer, image_seq_length: int = 1024, image_token: str = "<image>"):
  51. r"""
  52. image_seq_length (`int`, *optional*, defaults to 1024):
  53. Sequence length of one image embedding.
  54. image_token (`str`, *optional*, defaults to `"<image>"`):
  55. The special token used to indicate image in the text.
  56. """
  57. super().__init__(image_processor, tokenizer)
  58. self.image_seq_length = image_seq_length
  59. self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token
  60. self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
  61. self.image_start_token = (
  62. tokenizer.boi_token if hasattr(tokenizer, "boi_token") else "<racm3:break>"
  63. ) # fixed tokens for start and end, so can hardcode
  64. self.image_end_token = tokenizer.eoi_token if hasattr(tokenizer, "eoi_token") else "<eoss>"
  65. self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
  66. self.image_start_token_id = tokenizer.convert_tokens_to_ids(self.image_start_token)
  67. self.image_end_token_id = tokenizer.convert_tokens_to_ids(self.image_end_token)
  68. self.image_ids = [self.image_token_id, self.image_start_token_id, self.image_end_token_id]
  69. @auto_docstring
  70. def __call__(
  71. self,
  72. images: ImageInput | None = None,
  73. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
  74. **kwargs: Unpack[ChameleonProcessorKwargs],
  75. ) -> BatchFeature:
  76. r"""
  77. Returns:
  78. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  79. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  80. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  81. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  82. `None`).
  83. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  84. """
  85. if isinstance(text, str):
  86. text = [text]
  87. elif not isinstance(text, list) and not isinstance(text[0], str):
  88. raise TypeError("Invalid input text. Please provide a string, or a list of strings")
  89. if text is None and images is None:
  90. raise ValueError("You must provide either text or images")
  91. output_kwargs = self._merge_kwargs(
  92. ChameleonProcessorKwargs,
  93. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  94. **kwargs,
  95. )
  96. return_for_text_completion = output_kwargs["text_kwargs"].pop("return_for_text_completion", False)
  97. # Replace the image token with the expanded image token sequence
  98. prompt_strings = []
  99. one_img_tokens = self.image_start_token + (self.image_token * self.image_seq_length) + self.image_end_token
  100. for sample in text:
  101. sample = sample.replace(self.image_token, one_img_tokens)
  102. if not return_for_text_completion:
  103. sample += self.tokenizer.sep_token # special Chameleon treatment to add sep for chat mode
  104. prompt_strings.append(sample)
  105. image_inputs = {}
  106. if images is not None:
  107. image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
  108. return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
  109. return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False)
  110. text_inputs = self.tokenizer(prompt_strings, **output_kwargs["text_kwargs"], return_tensors=None)
  111. self._check_special_mm_tokens(prompt_strings, text_inputs, modalities=["image"])
  112. if return_mm_token_type_ids:
  113. text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
  114. return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
  115. def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
  116. """
  117. Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
  118. Args:
  119. image_sizes (`list[list[int]]`, *optional*):
  120. The input sizes formatted as (height, width) per each image.
  121. Returns:
  122. `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
  123. input modalities, along with other useful data.
  124. """
  125. vision_data = {}
  126. if image_sizes is not None:
  127. # add 2 for BOI and EOI tokens
  128. num_image_tokens = [self.image_seq_length + 2] * len(image_sizes)
  129. num_image_patches = [1] * len(image_sizes)
  130. vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
  131. return MultiModalData(**vision_data)
  132. __all__ = ["ChameleonProcessor"]