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
+
# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
|
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 |
+
"""
|
17 |
+
Processor class for Phi3-V.
|
18 |
+
"""
|
19 |
+
import re
|
20 |
+
from typing import List, Optional, Union
|
21 |
+
|
22 |
+
import torch
|
23 |
+
|
24 |
+
import transformers
|
25 |
+
from transformers.feature_extraction_utils import BatchFeature
|
26 |
+
from transformers.image_utils import ImageInput
|
27 |
+
from transformers.processing_utils import ProcessorMixin
|
28 |
+
from transformers.tokenization_utils_base import PaddingStrategy, TextInput, TruncationStrategy
|
29 |
+
from transformers.utils import TensorType
|
30 |
+
from .image_processing_phi3_v import Phi3VImageProcessor
|
31 |
+
transformers.Phi3VImageProcessor = Phi3VImageProcessor
|
32 |
+
|
33 |
+
class Phi3VProcessor(ProcessorMixin):
|
34 |
+
r"""
|
35 |
+
Constructs a Phi3-V processor which wraps a Phi3-V image processor and a LLaMa tokenizer into a single processor.
|
36 |
+
|
37 |
+
[`Phi3VProcessor`] offers all the functionalities of [`Phi3VImageProcessor`] and [`LlamaTokenizerFast`]. See the
|
38 |
+
[`~Phi3VProcessor.__call__`] and [`~Phi3VProcessor.decode`] for more information.
|
39 |
+
|
40 |
+
Args:
|
41 |
+
image_processor ([`Phi3VImageProcessor`], *optional*):
|
42 |
+
The image processor is a required input.
|
43 |
+
tokenizer ([`LlamaTokenizerFast`], *optional*):
|
44 |
+
The tokenizer is a required input.
|
45 |
+
"""
|
46 |
+
|
47 |
+
attributes = ["image_processor", "tokenizer"]
|
48 |
+
image_processor_class = "Phi3VImageProcessor"
|
49 |
+
tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
|
50 |
+
special_image_token = "<|image|>"
|
51 |
+
|
52 |
+
def __init__(self, image_processor, tokenizer):
|
53 |
+
self.image_processor = image_processor
|
54 |
+
self.tokenizer = tokenizer
|
55 |
+
self.num_img_tokens = image_processor.num_img_tokens
|
56 |
+
self.img_tokens = [f"<|image_{i+1}|>" for i in range(1000000)]
|
57 |
+
|
58 |
+
def __call__(
|
59 |
+
self,
|
60 |
+
text: Union[TextInput, List[TextInput]],
|
61 |
+
images: ImageInput = None,
|
62 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
63 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
64 |
+
max_length=None,
|
65 |
+
return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
|
66 |
+
) -> BatchFeature:
|
67 |
+
"""
|
68 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
69 |
+
and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
|
70 |
+
the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
|
71 |
+
Phi3ImageProcessor's [`~Phi3ImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
|
72 |
+
of the above two methods for more information.
|
73 |
+
|
74 |
+
Args:
|
75 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
76 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
77 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
78 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
79 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
80 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
81 |
+
tensor. Both channels-first and channels-last formats are supported.
|
82 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
83 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
84 |
+
index) among:
|
85 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
86 |
+
sequence if provided).
|
87 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
88 |
+
acceptable input length for the model if that argument is not provided.
|
89 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
90 |
+
lengths).
|
91 |
+
max_length (`int`, *optional*):
|
92 |
+
Maximum length of the returned list and optionally padding length (see above).
|
93 |
+
truncation (`bool`, *optional*):
|
94 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
95 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
96 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
97 |
+
|
98 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
99 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
100 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
101 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
102 |
+
|
103 |
+
Returns:
|
104 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
105 |
+
|
106 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
107 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
108 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
109 |
+
`None`).
|
110 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
111 |
+
"""
|
112 |
+
if images is not None:
|
113 |
+
image_inputs = self.image_processor(images, return_tensors=return_tensors)
|
114 |
+
else:
|
115 |
+
image_inputs = {}
|
116 |
+
inputs = self._convert_images_texts_to_inputs(image_inputs, text, padding=padding, truncation=truncation, max_length=max_length, return_tensors=return_tensors)
|
117 |
+
return inputs
|
118 |
+
|
119 |
+
def calc_num_image_tokens(self, images: ImageInput):
|
120 |
+
""" Calculate the number of image tokens for each image.
|
121 |
+
Args:
|
122 |
+
images (`ImageInput`):
|
123 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
124 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
125 |
+
"""
|
126 |
+
return self.image_processor.calc_num_image_tokens(images)
|
127 |
+
|
128 |
+
def calc_num_image_tokens_from_image_size(self, width, height):
|
129 |
+
""" Calculate the number of image token for an image with given width and height.
|
130 |
+
Args:
|
131 |
+
width (`int`):
|
132 |
+
Width of the image.
|
133 |
+
height (`int`):
|
134 |
+
Height of the image.
|
135 |
+
"""
|
136 |
+
return self.image_processor.calc_num_image_tokens_from_image_size(width, height)
|
137 |
+
|
138 |
+
|
139 |
+
@property
|
140 |
+
def special_image_token_id(self):
|
141 |
+
return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
|
142 |
+
|
143 |
+
def get_special_image_token_id(self):
|
144 |
+
return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
|
145 |
+
|
146 |
+
def _convert_images_texts_to_inputs(self, images, texts, padding=False, truncation=None, max_length=None, return_tensors=None):
|
147 |
+
|
148 |
+
if not len(images):
|
149 |
+
model_inputs = self.tokenizer(texts, return_tensors=return_tensors, padding=padding, truncation=truncation, max_length=max_length)
|
150 |
+
return BatchFeature(data={**model_inputs})
|
151 |
+
|
152 |
+
pattern = r"<\|image_\d+\|>"
|
153 |
+
if isinstance(texts, str):
|
154 |
+
texts = [texts]
|
155 |
+
|
156 |
+
prompt_chunks = []
|
157 |
+
image_tags = []
|
158 |
+
for text in texts:
|
159 |
+
prompt_chunks.append([self.tokenizer(chunk).input_ids for chunk in re.split(pattern, text)])
|
160 |
+
image_tags.append(re.findall(pattern, text))
|
161 |
+
|
162 |
+
if 'num_img_tokens' in images:
|
163 |
+
num_img_tokens = images['num_img_tokens']
|
164 |
+
else:
|
165 |
+
assert 'num_crops' in images, 'num_crops must be provided in images if num_img_tokens is not provided'
|
166 |
+
num_crops = images['num_crops']
|
167 |
+
num_img_tokens = [_num_crops * self.num_img_tokens for _num_crops in num_crops]
|
168 |
+
|
169 |
+
images, image_sizes = images['pixel_values'], images['image_sizes']
|
170 |
+
|
171 |
+
# image_tags needs to start from 1 to n
|
172 |
+
# image_tags = re.findall(pattern, texts)
|
173 |
+
# image_ids = [int(s.split("|")[1].split("_")[-1]) * -1 for s in image_tags]
|
174 |
+
# image_ids_pad = [[iid]*num_img_tokens[i] for i, iid in enumerate(image_ids)]
|
175 |
+
image_ids = [[int(s.split("|")[1].split("_")[-1]) for s in tags] for tags in image_tags]
|
176 |
+
unique_image_ids = sorted(list(set([iid for ids in image_ids for iid in ids])))
|
177 |
+
# image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be [1, 4, 5]
|
178 |
+
# check the condition
|
179 |
+
assert unique_image_ids == list(range(1, len(unique_image_ids)+1)), f"image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be {unique_image_ids}"
|
180 |
+
# total images must be the same as the number of image tags
|
181 |
+
assert len(unique_image_ids) == len(images), f"total images must be the same as the number of image tags, got {len(unique_image_ids)} image tags and {len(images)} images"
|
182 |
+
|
183 |
+
image_ids_pad = [[[-iid]*num_img_tokens[iid-1] for iid in ids] for ids in image_ids]
|
184 |
+
|
185 |
+
def insert_separator(X, sep_list):
|
186 |
+
if len(X) > len(sep_list):
|
187 |
+
sep_list.append([])
|
188 |
+
return [ele for sublist in zip(X, sep_list) for ele in sublist]
|
189 |
+
input_ids = []
|
190 |
+
for sub_prompt_chunks, sub_image_ids_pad in zip(prompt_chunks, image_ids_pad):
|
191 |
+
input_ids.append([])
|
192 |
+
offset = 0
|
193 |
+
for x in insert_separator(sub_prompt_chunks, sub_image_ids_pad):
|
194 |
+
input_ids[-1].extend(x[offset:])
|
195 |
+
|
196 |
+
max_length = max(len(ids) for ids in input_ids)
|
197 |
+
for i in range(len(input_ids)):
|
198 |
+
while len(input_ids[i]) < max_length:
|
199 |
+
input_ids[i] = [self.tokenizer.pad_token_id]+input_ids[i]
|
200 |
+
|
201 |
+
|
202 |
+
input_ids = torch.tensor(input_ids, dtype=torch.long).unsqueeze(0)
|
203 |
+
attention_mask = (input_ids > -1000000).to(torch.long)
|
204 |
+
attention_mask[input_ids == self.tokenizer.pad_token_id] = 0
|
205 |
+
|
206 |
+
return BatchFeature(data={"input_ids": input_ids,
|
207 |
+
"attention_mask": attention_mask,
|
208 |
+
"pixel_values": images,
|
209 |
+
"image_sizes": image_sizes})
|
210 |
+
|
211 |
+
|
212 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
|
213 |
+
def batch_decode(self, *args, **kwargs):
|
214 |
+
"""
|
215 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
216 |
+
refer to the docstring of this method for more information.
|
217 |
+
"""
|
218 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
219 |
+
|
220 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
|
221 |
+
def decode(self, *args, **kwargs):
|
222 |
+
"""
|
223 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
224 |
+
the docstring of this method for more information.
|
225 |
+
"""
|
226 |
+
return self.tokenizer.decode(*args, **kwargs)
|
227 |
+
|
228 |
+
@property
|
229 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
|
230 |
+
def model_input_names(self):
|
231 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
232 |
+
image_processor_input_names = self.image_processor.model_input_names
|
233 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|