Upload 3 files
Browse files- preprocessor_config.json +21 -0
- processing_phi3_v.py +493 -0
- processor_config.json +6 -0
preprocessor_config.json
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoImageProcessor": "processing_phi3_v.Phi3VImageProcessor",
|
4 |
+
"AutoProcessor": "processing_phi3_v.Phi3VProcessor"
|
5 |
+
},
|
6 |
+
"do_convert_rgb": true,
|
7 |
+
"image_mean": [
|
8 |
+
0.48145466,
|
9 |
+
0.4578275,
|
10 |
+
0.40821073
|
11 |
+
],
|
12 |
+
"image_processor_type": "Phi3VImageProcessor",
|
13 |
+
"image_std": [
|
14 |
+
0.26862954,
|
15 |
+
0.26130258,
|
16 |
+
0.27577711
|
17 |
+
],
|
18 |
+
"num_crops": 4,
|
19 |
+
"num_img_tokens": 144,
|
20 |
+
"processor_class": "Phi3VProcessor"
|
21 |
+
}
|
processing_phi3_v.py
ADDED
@@ -0,0 +1,493 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# 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 |
+
|
31 |
+
"""Image processor class for Phi3-V."""
|
32 |
+
|
33 |
+
from typing import List, Optional, Union
|
34 |
+
|
35 |
+
import numpy as np
|
36 |
+
|
37 |
+
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
|
38 |
+
from transformers.image_transforms import (
|
39 |
+
convert_to_rgb,
|
40 |
+
)
|
41 |
+
from transformers.image_utils import (
|
42 |
+
OPENAI_CLIP_MEAN,
|
43 |
+
OPENAI_CLIP_STD,
|
44 |
+
ImageInput,
|
45 |
+
make_list_of_images,
|
46 |
+
valid_images,
|
47 |
+
)
|
48 |
+
from transformers.utils import TensorType, is_vision_available, logging
|
49 |
+
|
50 |
+
from transformers import AutoImageProcessor
|
51 |
+
|
52 |
+
logger = logging.get_logger(__name__)
|
53 |
+
|
54 |
+
if is_vision_available():
|
55 |
+
from PIL import Image
|
56 |
+
|
57 |
+
import torch
|
58 |
+
import torchvision
|
59 |
+
|
60 |
+
|
61 |
+
def padding_336(b):
|
62 |
+
width, height = b.size
|
63 |
+
tar = int(np.ceil(height / 336) * 336)
|
64 |
+
top_padding = int((tar - height) / 2)
|
65 |
+
bottom_padding = tar - height - top_padding
|
66 |
+
left_padding = 0
|
67 |
+
right_padding = 0
|
68 |
+
b = torchvision.transforms.functional.pad(b, [left_padding, top_padding, right_padding, bottom_padding],
|
69 |
+
fill=[255, 255, 255])
|
70 |
+
|
71 |
+
return b
|
72 |
+
|
73 |
+
|
74 |
+
def calc_padded_size(width, height, padding_unit=336):
|
75 |
+
target_height = int(np.ceil(height / padding_unit) * padding_unit)
|
76 |
+
top_padding = int((target_height - height) / 2)
|
77 |
+
bottom_padding = target_height - height - top_padding
|
78 |
+
left_padding = 0
|
79 |
+
right_padding = 0
|
80 |
+
padded_width = width + left_padding + right_padding
|
81 |
+
padded_height = height + top_padding + bottom_padding
|
82 |
+
return padded_width, padded_height
|
83 |
+
|
84 |
+
|
85 |
+
def HD_transform(img, hd_num=16):
|
86 |
+
width, height = img.size
|
87 |
+
trans = False
|
88 |
+
if width < height:
|
89 |
+
img = img.transpose(Image.TRANSPOSE)
|
90 |
+
trans = True
|
91 |
+
width, height = img.size
|
92 |
+
ratio = (width / height)
|
93 |
+
scale = 1
|
94 |
+
while scale * np.ceil(scale / ratio) <= hd_num:
|
95 |
+
scale += 1
|
96 |
+
scale -= 1
|
97 |
+
new_w = int(scale * 336)
|
98 |
+
new_h = int(new_w / ratio)
|
99 |
+
|
100 |
+
img = torchvision.transforms.functional.resize(img, [new_h, new_w], )
|
101 |
+
img = padding_336(img)
|
102 |
+
width, height = img.size
|
103 |
+
if trans:
|
104 |
+
img = img.transpose(Image.TRANSPOSE)
|
105 |
+
|
106 |
+
return img
|
107 |
+
|
108 |
+
|
109 |
+
def calc_hd_transform_size(width, height, hd_num=16):
|
110 |
+
transposed = False
|
111 |
+
if width < height:
|
112 |
+
width, height = height, width
|
113 |
+
transposed = True
|
114 |
+
|
115 |
+
ratio = width / height
|
116 |
+
scale = 1
|
117 |
+
while scale * np.ceil(scale / ratio) <= hd_num:
|
118 |
+
scale += 1
|
119 |
+
scale -= 1
|
120 |
+
|
121 |
+
new_width = int(scale * 336)
|
122 |
+
new_height = int(new_width / ratio)
|
123 |
+
|
124 |
+
padded_width, padded_height = calc_padded_size(new_width, new_height)
|
125 |
+
|
126 |
+
if transposed:
|
127 |
+
padded_width, padded_height = padded_height, padded_width
|
128 |
+
|
129 |
+
return padded_width, padded_height
|
130 |
+
|
131 |
+
|
132 |
+
def pad_to_max_num_crops_tensor(images, max_crops=5):
|
133 |
+
"""
|
134 |
+
images: B x 3 x H x W, B<=max_crops
|
135 |
+
"""
|
136 |
+
B, _, H, W = images.shape
|
137 |
+
if B < max_crops:
|
138 |
+
pad = torch.zeros(max_crops - B, 3, H, W, dtype=images.dtype, device=images.device)
|
139 |
+
images = torch.cat([images, pad], dim=0)
|
140 |
+
return images
|
141 |
+
|
142 |
+
|
143 |
+
class Phi3VImageProcessor(BaseImageProcessor):
|
144 |
+
r"""
|
145 |
+
Constructs a Phi3 image processor. Based on [`CLIPImageProcessor`] with incorporation of additional techniques
|
146 |
+
for processing high resolution images as explained in the [InternLM-XComposer2-4KHD](https://arxiv.org/pdf/2404.06512)
|
147 |
+
|
148 |
+
Args:
|
149 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
|
150 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
151 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
152 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
|
153 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
154 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
155 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
156 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
157 |
+
Whether to convert the image to RGB.
|
158 |
+
"""
|
159 |
+
|
160 |
+
model_input_names = ["pixel_values"]
|
161 |
+
|
162 |
+
def __init__(
|
163 |
+
self,
|
164 |
+
num_crops: int = 1,
|
165 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
166 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
167 |
+
do_convert_rgb: bool = True,
|
168 |
+
**kwargs,
|
169 |
+
) -> None:
|
170 |
+
super().__init__(**kwargs)
|
171 |
+
self.num_crops = num_crops
|
172 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
173 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
174 |
+
self.do_convert_rgb = do_convert_rgb
|
175 |
+
|
176 |
+
def calc_num_image_tokens(
|
177 |
+
self,
|
178 |
+
images: ImageInput
|
179 |
+
):
|
180 |
+
""" Calculate the number of image tokens for each image.
|
181 |
+
Args:
|
182 |
+
images (`ImageInput`):
|
183 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
184 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
185 |
+
"""
|
186 |
+
images = make_list_of_images(images)
|
187 |
+
|
188 |
+
if not valid_images(images):
|
189 |
+
raise ValueError(
|
190 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
191 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
192 |
+
)
|
193 |
+
|
194 |
+
images = [image.convert('RGB') for image in images]
|
195 |
+
# (H, W, C)
|
196 |
+
elems = [HD_transform(im, hd_num=self.num_crops) for im in images]
|
197 |
+
shapes = [[im.size[1], im.size[0]] for im in elems]
|
198 |
+
num_img_tokens = [int((h // 336 * w // 336 + 1) * 144 + 1 + (h // 336 + 1) * 12) for h, w in shapes]
|
199 |
+
return num_img_tokens
|
200 |
+
|
201 |
+
def calc_num_image_tokens_from_image_size(self, width, height):
|
202 |
+
"""
|
203 |
+
Calculate the number of image tokens for a given image size.
|
204 |
+
Args:
|
205 |
+
width (`int`): Width of the image.
|
206 |
+
height (`int`): Height of the image.
|
207 |
+
"""
|
208 |
+
new_width, new_height = calc_hd_transform_size(width, height, hd_num=self.num_crops)
|
209 |
+
num_img_tokens = int((new_height // 336 * new_width // 336 + 1) * 144 + 1 + (new_height // 336 + 1) * 12)
|
210 |
+
return num_img_tokens
|
211 |
+
|
212 |
+
def preprocess(
|
213 |
+
self,
|
214 |
+
images: ImageInput,
|
215 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
216 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
217 |
+
do_convert_rgb: bool = None,
|
218 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
219 |
+
):
|
220 |
+
"""
|
221 |
+
Args:
|
222 |
+
images (`ImageInput`):
|
223 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
224 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
225 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
226 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
227 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
228 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
229 |
+
`True`.
|
230 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
231 |
+
Whether to convert the image to RGB.
|
232 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
233 |
+
The type of tensors to return. Can be one of:
|
234 |
+
- Unset: Return a list of `np.ndarray`.
|
235 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
236 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
237 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
238 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
239 |
+
"""
|
240 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
241 |
+
image_std = image_std if image_std is not None else self.image_std
|
242 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
243 |
+
|
244 |
+
images = make_list_of_images(images)
|
245 |
+
|
246 |
+
if not valid_images(images):
|
247 |
+
raise ValueError(
|
248 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
249 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
250 |
+
)
|
251 |
+
|
252 |
+
if do_convert_rgb:
|
253 |
+
images = [convert_to_rgb(image) for image in images]
|
254 |
+
|
255 |
+
image_sizes = []
|
256 |
+
img_processor = torchvision.transforms.Compose([
|
257 |
+
torchvision.transforms.ToTensor(),
|
258 |
+
torchvision.transforms.Normalize(image_mean, image_std)
|
259 |
+
])
|
260 |
+
|
261 |
+
# PIL images
|
262 |
+
# HD_transform pad images to size of multiiply of 336, 336
|
263 |
+
# convert to RGB first
|
264 |
+
images = [image.convert('RGB') for image in images]
|
265 |
+
elems = [HD_transform(im, hd_num=self.num_crops) for im in images]
|
266 |
+
# tensor transform and normalize
|
267 |
+
hd_images = [img_processor(im) for im in elems]
|
268 |
+
# create global image
|
269 |
+
global_image = [
|
270 |
+
torch.nn.functional.interpolate(im.unsqueeze(0).float(), size=(336, 336), mode='bicubic', ).to(im.dtype) for
|
271 |
+
im in hd_images]
|
272 |
+
|
273 |
+
# [(3, h, w)], where h, w is multiple of 336
|
274 |
+
shapes = [[im.size(1), im.size(2)] for im in hd_images]
|
275 |
+
num_img_tokens = [int(((h // 336) * (w // 336) + 1) * 144 + 1 + (h // 336 + 1) * 12) for h, w in shapes]
|
276 |
+
# reshape to channel dimension -> (num_images, num_crops, 3, 336, 336)
|
277 |
+
# (1, 3, h//336, 336, w//336, 336) -> (1, h//336, w//336, 3, 336, 336) -> (h//336*w//336, 3, 336, 336)
|
278 |
+
hd_images_reshape = [
|
279 |
+
im.reshape(1, 3, h // 336, 336, w // 336, 336).permute(0, 2, 4, 1, 3, 5).reshape(-1, 3, 336,
|
280 |
+
336).contiguous() for
|
281 |
+
im, (h, w) in zip(hd_images, shapes)]
|
282 |
+
# concat global image and local image
|
283 |
+
hd_images_reshape = [torch.cat([_global_image] + [_im], dim=0) for _global_image, _im in
|
284 |
+
zip(global_image, hd_images_reshape)]
|
285 |
+
|
286 |
+
# pad to max_num_crops
|
287 |
+
image_transformed = [pad_to_max_num_crops_tensor(im, self.num_crops + 1) for im in hd_images_reshape]
|
288 |
+
image_transformed = torch.stack(image_transformed, dim=0)
|
289 |
+
image_sizes = [torch.LongTensor(_shapes) for _shapes in shapes]
|
290 |
+
padded_images = image_transformed
|
291 |
+
image_sizes = shapes
|
292 |
+
|
293 |
+
data = {"pixel_values": padded_images,
|
294 |
+
"image_sizes": image_sizes,
|
295 |
+
"num_img_tokens": num_img_tokens
|
296 |
+
}
|
297 |
+
|
298 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
299 |
+
|
300 |
+
|
301 |
+
AutoImageProcessor.register("Phi3VImageProcessor", Phi3VImageProcessor)
|
302 |
+
|
303 |
+
transformers.Phi3VImageProcessor = Phi3VImageProcessor
|
304 |
+
|
305 |
+
|
306 |
+
class Phi3VProcessor(ProcessorMixin):
|
307 |
+
r"""
|
308 |
+
Constructs a Phi3-V processor which wraps a Phi3-V image processor and a LLaMa tokenizer into a single processor.
|
309 |
+
|
310 |
+
[`Phi3VProcessor`] offers all the functionalities of [`Phi3VImageProcessor`] and [`LlamaTokenizerFast`]. See the
|
311 |
+
[`~Phi3VProcessor.__call__`] and [`~Phi3VProcessor.decode`] for more information.
|
312 |
+
|
313 |
+
Args:
|
314 |
+
image_processor ([`Phi3VImageProcessor`], *optional*):
|
315 |
+
The image processor is a required input.
|
316 |
+
tokenizer ([`LlamaTokenizerFast`], *optional*):
|
317 |
+
The tokenizer is a required input.
|
318 |
+
"""
|
319 |
+
|
320 |
+
attributes = ["image_processor", "tokenizer"]
|
321 |
+
image_processor_class = "Phi3VImageProcessor"
|
322 |
+
tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
|
323 |
+
special_image_token = "<|image|>"
|
324 |
+
|
325 |
+
def __init__(self, image_processor, tokenizer):
|
326 |
+
self.image_processor = image_processor
|
327 |
+
self.tokenizer = tokenizer
|
328 |
+
self.num_img_tokens = image_processor.num_img_tokens
|
329 |
+
self.img_tokens = [f"<|image_{i + 1}|>" for i in range(1000000)]
|
330 |
+
|
331 |
+
def __call__(
|
332 |
+
self,
|
333 |
+
text: Union[TextInput, List[TextInput]],
|
334 |
+
images: ImageInput = None,
|
335 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
336 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
337 |
+
max_length=None,
|
338 |
+
return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
|
339 |
+
) -> BatchFeature:
|
340 |
+
"""
|
341 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
342 |
+
and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
|
343 |
+
the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
|
344 |
+
Phi3ImageProcessor's [`~Phi3ImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
|
345 |
+
of the above two methods for more information.
|
346 |
+
|
347 |
+
Args:
|
348 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
349 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
350 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
351 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
352 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
353 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
354 |
+
tensor. Both channels-first and channels-last formats are supported.
|
355 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
356 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
357 |
+
index) among:
|
358 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
359 |
+
sequence if provided).
|
360 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
361 |
+
acceptable input length for the model if that argument is not provided.
|
362 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
363 |
+
lengths).
|
364 |
+
max_length (`int`, *optional*):
|
365 |
+
Maximum length of the returned list and optionally padding length (see above).
|
366 |
+
truncation (`bool`, *optional*):
|
367 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
368 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
369 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
370 |
+
|
371 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
372 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
373 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
374 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
375 |
+
|
376 |
+
Returns:
|
377 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
378 |
+
|
379 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
380 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
381 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
382 |
+
`None`).
|
383 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
384 |
+
"""
|
385 |
+
if images is not None:
|
386 |
+
image_inputs = self.image_processor(images, return_tensors=return_tensors)
|
387 |
+
else:
|
388 |
+
image_inputs = {}
|
389 |
+
inputs = self._convert_images_texts_to_inputs(image_inputs, text, padding=padding, truncation=truncation,
|
390 |
+
max_length=max_length, return_tensors=return_tensors)
|
391 |
+
return inputs
|
392 |
+
|
393 |
+
def calc_num_image_tokens(self, images: ImageInput):
|
394 |
+
""" Calculate the number of image tokens for each image.
|
395 |
+
Args:
|
396 |
+
images (`ImageInput`):
|
397 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
398 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
399 |
+
"""
|
400 |
+
return self.image_processor.calc_num_image_tokens(images)
|
401 |
+
|
402 |
+
def calc_num_image_tokens_from_image_size(self, width, height):
|
403 |
+
""" Calculate the number of image token for an image with given width and height.
|
404 |
+
Args:
|
405 |
+
width (`int`):
|
406 |
+
Width of the image.
|
407 |
+
height (`int`):
|
408 |
+
Height of the image.
|
409 |
+
"""
|
410 |
+
return self.image_processor.calc_num_image_tokens_from_image_size(width, height)
|
411 |
+
|
412 |
+
@property
|
413 |
+
def special_image_token_id(self):
|
414 |
+
return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
|
415 |
+
|
416 |
+
def get_special_image_token_id(self):
|
417 |
+
return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
|
418 |
+
|
419 |
+
def _convert_images_texts_to_inputs(self, images, texts, padding=False, truncation=None, max_length=None,
|
420 |
+
return_tensors=None):
|
421 |
+
if not len(images):
|
422 |
+
model_inputs = self.tokenizer(texts, return_tensors=return_tensors, padding=padding, truncation=truncation,
|
423 |
+
max_length=max_length)
|
424 |
+
return BatchFeature(data={**model_inputs})
|
425 |
+
|
426 |
+
pattern = r"<\|image_\d+\|>"
|
427 |
+
prompt_chunks = [self.tokenizer(chunk, truncation=truncation, max_length=max_length).input_ids for chunk in re.split(pattern, texts)]
|
428 |
+
|
429 |
+
if 'num_img_tokens' in images:
|
430 |
+
num_img_tokens = images['num_img_tokens']
|
431 |
+
else:
|
432 |
+
assert 'num_crops' in images, 'num_crops must be provided in images if num_img_tokens is not provided'
|
433 |
+
num_crops = images['num_crops']
|
434 |
+
num_img_tokens = [_num_crops * self.num_img_tokens for _num_crops in num_crops]
|
435 |
+
|
436 |
+
images, image_sizes = images['pixel_values'], images['image_sizes']
|
437 |
+
|
438 |
+
# image_tags needs to start from 1 to n
|
439 |
+
image_tags = re.findall(pattern, texts)
|
440 |
+
# image_ids = [int(s.split("|")[1].split("_")[-1]) * -1 for s in image_tags]
|
441 |
+
# image_ids_pad = [[iid]*num_img_tokens[i] for i, iid in enumerate(image_ids)]
|
442 |
+
image_ids = [int(s.split("|")[1].split("_")[-1]) for s in image_tags]
|
443 |
+
unique_image_ids = sorted(list(set(image_ids)))
|
444 |
+
# image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be [1, 4, 5]
|
445 |
+
# check the condition
|
446 |
+
assert unique_image_ids == list(range(1,
|
447 |
+
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}"
|
448 |
+
# total images must be the same as the number of image tags
|
449 |
+
assert len(unique_image_ids) == len(
|
450 |
+
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"
|
451 |
+
|
452 |
+
image_ids_pad = [[-iid] * num_img_tokens[iid - 1] for iid in image_ids]
|
453 |
+
|
454 |
+
def insert_separator(X, sep_list):
|
455 |
+
if len(X) > len(sep_list):
|
456 |
+
sep_list.append([])
|
457 |
+
return [ele for sublist in zip(X, sep_list) for ele in sublist]
|
458 |
+
|
459 |
+
input_ids = []
|
460 |
+
offset = 0
|
461 |
+
for x in insert_separator(prompt_chunks, image_ids_pad):
|
462 |
+
input_ids.extend(x[offset:])
|
463 |
+
|
464 |
+
input_ids = torch.tensor(input_ids, dtype=torch.long).unsqueeze(0)
|
465 |
+
attention_mask = (input_ids > -1000000).to(torch.long)
|
466 |
+
|
467 |
+
return BatchFeature(data={"input_ids": input_ids,
|
468 |
+
"attention_mask": attention_mask,
|
469 |
+
"pixel_values": images,
|
470 |
+
"image_sizes": image_sizes})
|
471 |
+
|
472 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
|
473 |
+
def batch_decode(self, *args, **kwargs):
|
474 |
+
"""
|
475 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
476 |
+
refer to the docstring of this method for more information.
|
477 |
+
"""
|
478 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
479 |
+
|
480 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
|
481 |
+
def decode(self, *args, **kwargs):
|
482 |
+
"""
|
483 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
484 |
+
the docstring of this method for more information.
|
485 |
+
"""
|
486 |
+
return self.tokenizer.decode(*args, **kwargs)
|
487 |
+
|
488 |
+
@property
|
489 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
|
490 |
+
def model_input_names(self):
|
491 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
492 |
+
image_processor_input_names = self.image_processor.model_input_names
|
493 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
processor_config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoProcessor": "processing_phi3_v.Phi3VProcessor"
|
4 |
+
},
|
5 |
+
"processor_class": "Phi3VProcessor"
|
6 |
+
}
|