Upload folder using huggingface_hub
Browse files- image_processing_minicpmv.py +402 -0
- processing_minicpmv.py +244 -0
- tokenization_minicpmv_fast.py +51 -0
image_processing_minicpmv.py
ADDED
@@ -0,0 +1,402 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Optional, Union, Dict, Any
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import math
|
5 |
+
import PIL.Image
|
6 |
+
import PIL.ImageSequence
|
7 |
+
import numpy as np
|
8 |
+
import PIL
|
9 |
+
from PIL import Image
|
10 |
+
|
11 |
+
from transformers.utils import TensorType, requires_backends, is_torch_dtype, is_torch_device
|
12 |
+
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
|
13 |
+
from transformers import AutoImageProcessor
|
14 |
+
from transformers.image_transforms import to_channel_dimension_format
|
15 |
+
from transformers.image_utils import (
|
16 |
+
ImageInput,
|
17 |
+
make_list_of_images,
|
18 |
+
valid_images,
|
19 |
+
is_torch_tensor,
|
20 |
+
to_numpy_array,
|
21 |
+
infer_channel_dimension_format,
|
22 |
+
ChannelDimension
|
23 |
+
)
|
24 |
+
|
25 |
+
|
26 |
+
def recursive_converter(converter, value):
|
27 |
+
if isinstance(value, list):
|
28 |
+
new_value = []
|
29 |
+
for v in value:
|
30 |
+
new_value += [recursive_converter(converter, v)]
|
31 |
+
return new_value
|
32 |
+
else:
|
33 |
+
return converter(value)
|
34 |
+
|
35 |
+
|
36 |
+
class MiniCPMVBatchFeature(BatchFeature):
|
37 |
+
r"""
|
38 |
+
Extend from BatchFeature for supporting various image size
|
39 |
+
"""
|
40 |
+
def __init__(self, data: Optional[Dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None):
|
41 |
+
super().__init__(data)
|
42 |
+
self.convert_to_tensors(tensor_type=tensor_type)
|
43 |
+
|
44 |
+
def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None):
|
45 |
+
if tensor_type is None:
|
46 |
+
return self
|
47 |
+
|
48 |
+
is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type)
|
49 |
+
|
50 |
+
def converter(value):
|
51 |
+
try:
|
52 |
+
if not is_tensor(value):
|
53 |
+
tensor = as_tensor(value)
|
54 |
+
return tensor
|
55 |
+
except: # noqa E722
|
56 |
+
if key == "overflowing_values":
|
57 |
+
raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
|
58 |
+
raise ValueError(
|
59 |
+
"Unable to create tensor, you should probably activate padding "
|
60 |
+
"with 'padding=True' to have batched tensors with the same length."
|
61 |
+
)
|
62 |
+
|
63 |
+
|
64 |
+
for key, value in self.items():
|
65 |
+
self[key] = recursive_converter(converter, value)
|
66 |
+
return self
|
67 |
+
|
68 |
+
def to(self, *args, **kwargs) -> "MiniCPMVBatchFeature":
|
69 |
+
requires_backends(self, ["torch"])
|
70 |
+
import torch
|
71 |
+
|
72 |
+
def cast_tensor(v):
|
73 |
+
# check if v is a floating point
|
74 |
+
if torch.is_floating_point(v):
|
75 |
+
# cast and send to device
|
76 |
+
return v.to(*args, **kwargs)
|
77 |
+
elif device is not None:
|
78 |
+
return v.to(device=device)
|
79 |
+
else:
|
80 |
+
return v
|
81 |
+
|
82 |
+
new_data = {}
|
83 |
+
device = kwargs.get("device")
|
84 |
+
# Check if the args are a device or a dtype
|
85 |
+
if device is None and len(args) > 0:
|
86 |
+
# device should be always the first argument
|
87 |
+
arg = args[0]
|
88 |
+
if is_torch_dtype(arg):
|
89 |
+
# The first argument is a dtype
|
90 |
+
pass
|
91 |
+
elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):
|
92 |
+
device = arg
|
93 |
+
else:
|
94 |
+
# it's something else
|
95 |
+
raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.")
|
96 |
+
# We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor`
|
97 |
+
for k, v in self.items():
|
98 |
+
new_data[k] = recursive_converter(cast_tensor, v)
|
99 |
+
self.data = new_data
|
100 |
+
return self
|
101 |
+
|
102 |
+
|
103 |
+
class MiniCPMVImageProcessor(BaseImageProcessor):
|
104 |
+
model_input_names = ["pixel_values"]
|
105 |
+
|
106 |
+
def __init__(
|
107 |
+
self,
|
108 |
+
max_slice_nums=9,
|
109 |
+
scale_resolution=448,
|
110 |
+
patch_size=14,
|
111 |
+
**kwargs):
|
112 |
+
super().__init__(**kwargs)
|
113 |
+
self.max_slice_nums = max_slice_nums
|
114 |
+
self.scale_resolution = scale_resolution
|
115 |
+
self.patch_size = patch_size
|
116 |
+
self.image_feature_size = kwargs.pop("image_feature_size", 64)
|
117 |
+
self.im_start_token = kwargs.pop("im_start", "<image>")
|
118 |
+
self.im_end_token = kwargs.pop("im_end", "</image>")
|
119 |
+
self.slice_start_token = kwargs.pop("slice_start", "<slice>")
|
120 |
+
self.slice_end_token = kwargs.pop("slice_end", "</slice>")
|
121 |
+
self.unk_token = kwargs.pop("unk", "<unk>")
|
122 |
+
self.mean = np.array(kwargs.pop("norm_mean", [0.5, 0.5, 0.5]))
|
123 |
+
self.std = np.array(kwargs.pop("norm_std", [0.5, 0.5, 0.5]))
|
124 |
+
self.version = kwargs.pop("version", 2.0)
|
125 |
+
|
126 |
+
def ensure_divide(self, length, patch_size):
|
127 |
+
return max(round(length / patch_size) * patch_size, patch_size)
|
128 |
+
|
129 |
+
def find_best_resize(self,
|
130 |
+
original_size,
|
131 |
+
scale_resolution,
|
132 |
+
patch_size,
|
133 |
+
allow_upscale=False):
|
134 |
+
width, height = original_size
|
135 |
+
if (width * height >
|
136 |
+
scale_resolution * scale_resolution) or allow_upscale:
|
137 |
+
r = width / height
|
138 |
+
height = int(scale_resolution / math.sqrt(r))
|
139 |
+
width = int(height * r)
|
140 |
+
best_width = self.ensure_divide(width, patch_size)
|
141 |
+
best_height = self.ensure_divide(height, patch_size)
|
142 |
+
return (best_width, best_height)
|
143 |
+
|
144 |
+
def get_refine_size(self,
|
145 |
+
original_size,
|
146 |
+
grid,
|
147 |
+
scale_resolution,
|
148 |
+
patch_size,
|
149 |
+
allow_upscale=False):
|
150 |
+
width, height = original_size
|
151 |
+
grid_x, grid_y = grid
|
152 |
+
|
153 |
+
refine_width = self.ensure_divide(width, grid_x)
|
154 |
+
refine_height = self.ensure_divide(height, grid_y)
|
155 |
+
|
156 |
+
grid_width = refine_width / grid_x
|
157 |
+
grid_height = refine_height / grid_y
|
158 |
+
|
159 |
+
best_grid_size = self.find_best_resize((grid_width, grid_height),
|
160 |
+
scale_resolution,
|
161 |
+
patch_size,
|
162 |
+
allow_upscale=allow_upscale)
|
163 |
+
refine_size = (best_grid_size[0] * grid_x, best_grid_size[1] * grid_y)
|
164 |
+
return refine_size
|
165 |
+
|
166 |
+
def split_to_patches(self, image, grid):
|
167 |
+
patches = []
|
168 |
+
width, height = image.size
|
169 |
+
grid_x = int(width / grid[0])
|
170 |
+
grid_y = int(height / grid[1])
|
171 |
+
for i in range(0, height, grid_y):
|
172 |
+
images = []
|
173 |
+
for j in range(0, width, grid_x):
|
174 |
+
box = (j, i, j + grid_x, i + grid_y)
|
175 |
+
patch = image.crop(box)
|
176 |
+
images.append(patch)
|
177 |
+
patches.append(images)
|
178 |
+
return patches
|
179 |
+
|
180 |
+
def slice_image(
|
181 |
+
self, image, max_slice_nums=9, scale_resolution=448, patch_size=14, never_split=False
|
182 |
+
):
|
183 |
+
original_size = image.size
|
184 |
+
original_width, original_height = original_size
|
185 |
+
log_ratio = math.log(original_width / original_height)
|
186 |
+
ratio = original_width * original_height / (scale_resolution * scale_resolution)
|
187 |
+
multiple = min(math.ceil(ratio), max_slice_nums)
|
188 |
+
|
189 |
+
source_image = None
|
190 |
+
best_grid = None
|
191 |
+
patches = []
|
192 |
+
|
193 |
+
if multiple <= 1 or never_split:
|
194 |
+
# dont need to slice, upsample
|
195 |
+
best_size = self.find_best_resize(
|
196 |
+
original_size, scale_resolution, patch_size, allow_upscale=True
|
197 |
+
)
|
198 |
+
source_image = image.resize(best_size, resample=Image.Resampling.BICUBIC)
|
199 |
+
else:
|
200 |
+
candidate_split_grids_nums = []
|
201 |
+
for i in [multiple - 1, multiple, multiple + 1]:
|
202 |
+
if i == 1 or i > max_slice_nums:
|
203 |
+
continue
|
204 |
+
candidate_split_grids_nums.append(i)
|
205 |
+
|
206 |
+
# source image, down-sampling and ensure divided by patch_size
|
207 |
+
best_resize = self.find_best_resize(original_size, scale_resolution, patch_size)
|
208 |
+
source_image = image.copy().resize(best_resize, resample=Image.Resampling.BICUBIC)
|
209 |
+
candidate_grids = []
|
210 |
+
|
211 |
+
# find best grid
|
212 |
+
for split_grids_nums in candidate_split_grids_nums:
|
213 |
+
m = 1
|
214 |
+
while m <= split_grids_nums:
|
215 |
+
if split_grids_nums % m == 0:
|
216 |
+
candidate_grids.append([m, split_grids_nums // m])
|
217 |
+
m += 1
|
218 |
+
|
219 |
+
best_grid = [1, 1]
|
220 |
+
min_error = float("inf")
|
221 |
+
for grid in candidate_grids:
|
222 |
+
error = abs(log_ratio - math.log(grid[0] / grid[1]))
|
223 |
+
if error < min_error:
|
224 |
+
best_grid = grid
|
225 |
+
min_error = error
|
226 |
+
|
227 |
+
refine_size = self.get_refine_size(
|
228 |
+
original_size, best_grid, scale_resolution, patch_size, allow_upscale=True
|
229 |
+
)
|
230 |
+
|
231 |
+
refine_image = image.resize(refine_size, resample=Image.Resampling.BICUBIC)
|
232 |
+
patches = self.split_to_patches(refine_image, best_grid)
|
233 |
+
|
234 |
+
return source_image, patches, best_grid
|
235 |
+
|
236 |
+
def get_grid_placeholder(self, grid):
|
237 |
+
if grid is None:
|
238 |
+
return ""
|
239 |
+
image_placeholder = (
|
240 |
+
self.im_start_token
|
241 |
+
+ self.unk_token * self.image_feature_size
|
242 |
+
+ self.im_end_token
|
243 |
+
)
|
244 |
+
|
245 |
+
cols = grid[0]
|
246 |
+
rows = grid[1]
|
247 |
+
slices = []
|
248 |
+
for i in range(rows):
|
249 |
+
lines = []
|
250 |
+
for j in range(cols):
|
251 |
+
lines.append(image_placeholder)
|
252 |
+
slices.append("".join(lines))
|
253 |
+
|
254 |
+
slice_placeholder = self.slice_start_token + "\n".join(slices) + self.slice_end_token
|
255 |
+
return slice_placeholder
|
256 |
+
|
257 |
+
def get_sliced_images(self, image):
|
258 |
+
slice_images = []
|
259 |
+
|
260 |
+
source_image, patches, sliced_grid = self.slice_image(
|
261 |
+
image,
|
262 |
+
self.max_slice_nums, # default: 9
|
263 |
+
self.scale_resolution, # default: 448
|
264 |
+
self.patch_size # default: 14
|
265 |
+
)
|
266 |
+
slice_images.append(source_image)
|
267 |
+
|
268 |
+
if len(patches) > 0:
|
269 |
+
for i in range(len(patches)):
|
270 |
+
for j in range(len(patches[0])):
|
271 |
+
slice_images.append(patches[i][j])
|
272 |
+
return slice_images
|
273 |
+
|
274 |
+
def get_sliced_grid(self, image_size):
|
275 |
+
original_width, original_height = image_size
|
276 |
+
log_ratio = math.log(original_width / original_height)
|
277 |
+
ratio = original_width * original_height / (self.scale_resolution * self.scale_resolution)
|
278 |
+
multiple = min(math.ceil(ratio), self.max_slice_nums)
|
279 |
+
if multiple <= 1:
|
280 |
+
return None
|
281 |
+
candidate_split_grids_nums = []
|
282 |
+
for i in [multiple - 1, multiple, multiple + 1]:
|
283 |
+
if i == 1 or i > self.max_slice_nums:
|
284 |
+
continue
|
285 |
+
candidate_split_grids_nums.append(i)
|
286 |
+
|
287 |
+
candidate_grids = []
|
288 |
+
for split_grids_nums in candidate_split_grids_nums:
|
289 |
+
m = 1
|
290 |
+
while m <= split_grids_nums:
|
291 |
+
if split_grids_nums % m == 0:
|
292 |
+
candidate_grids.append([m, split_grids_nums // m])
|
293 |
+
m += 1
|
294 |
+
|
295 |
+
best_grid = [1, 1]
|
296 |
+
min_error = float("inf")
|
297 |
+
for grid in candidate_grids:
|
298 |
+
error = abs(log_ratio - math.log(grid[0] / grid[1]))
|
299 |
+
if error < min_error:
|
300 |
+
best_grid = grid
|
301 |
+
min_error = error
|
302 |
+
|
303 |
+
return best_grid
|
304 |
+
|
305 |
+
def get_slice_image_placeholder(self, image_size):
|
306 |
+
grid = self.get_sliced_grid(image_size=image_size)
|
307 |
+
return (
|
308 |
+
self.im_start_token
|
309 |
+
+ self.unk_token * self.image_feature_size
|
310 |
+
+ self.im_end_token
|
311 |
+
) + self.get_grid_placeholder(grid=grid)
|
312 |
+
|
313 |
+
def to_pil_image(self, image, rescale=None) -> PIL.Image.Image:
|
314 |
+
"""
|
315 |
+
Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
|
316 |
+
needed.
|
317 |
+
|
318 |
+
Args:
|
319 |
+
image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):
|
320 |
+
The image to convert to the PIL Image format.
|
321 |
+
rescale (`bool`, *optional*):
|
322 |
+
Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will
|
323 |
+
default to `True` if the image type is a floating type, `False` otherwise.
|
324 |
+
"""
|
325 |
+
if isinstance(image, PIL.Image.Image):
|
326 |
+
return image
|
327 |
+
if is_torch_tensor(image):
|
328 |
+
image = image.numpy()
|
329 |
+
|
330 |
+
if isinstance(image, np.ndarray):
|
331 |
+
if rescale is None:
|
332 |
+
# rescale default to the array being of floating type.
|
333 |
+
rescale = isinstance(image.flat[0], np.floating)
|
334 |
+
# If the channel as been moved to first dim, we put it back at the end.
|
335 |
+
if image.ndim == 3 and image.shape[0] in [1, 3]:
|
336 |
+
image = image.transpose(1, 2, 0)
|
337 |
+
if rescale:
|
338 |
+
image = image * 255
|
339 |
+
image = image.astype(np.uint8)
|
340 |
+
return PIL.Image.fromarray(image)
|
341 |
+
return image
|
342 |
+
|
343 |
+
def reshape_by_patch(self, image):
|
344 |
+
"""
|
345 |
+
:param image: shape [3, H, W]
|
346 |
+
:param patch_size:
|
347 |
+
:return: [3, patch_size, HW/patch_size]
|
348 |
+
"""
|
349 |
+
image = torch.from_numpy(image)
|
350 |
+
patch_size = self.patch_size
|
351 |
+
patches = torch.nn.functional.unfold(
|
352 |
+
image,
|
353 |
+
(patch_size, patch_size),
|
354 |
+
stride=(patch_size, patch_size)
|
355 |
+
)
|
356 |
+
|
357 |
+
patches = patches.reshape(image.size(0), patch_size, patch_size, -1)
|
358 |
+
patches = patches.permute(0, 1, 3, 2).reshape(image.size(0), patch_size, -1)
|
359 |
+
return patches.numpy()
|
360 |
+
|
361 |
+
def preprocess(
|
362 |
+
self,
|
363 |
+
images: ImageInput,
|
364 |
+
do_pad: Optional[bool] = True, # TODO: add pad for MiniCPM-Llama3-V-2_5
|
365 |
+
return_tensors: Optional[Union[str, TensorType]] = None
|
366 |
+
) -> MiniCPMVBatchFeature:
|
367 |
+
images = make_list_of_images(images)
|
368 |
+
|
369 |
+
if not valid_images(images):
|
370 |
+
raise ValueError(
|
371 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
372 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
373 |
+
)
|
374 |
+
|
375 |
+
images = [self.to_pil_image(image).convert("RGB") for image in images]
|
376 |
+
input_data_format = infer_channel_dimension_format(np.array(images[0]))
|
377 |
+
|
378 |
+
new_images = []
|
379 |
+
image_sizes = [image.size for image in images]
|
380 |
+
tgt_sizes = []
|
381 |
+
for image in images:
|
382 |
+
image_patches = self.get_sliced_images(image)
|
383 |
+
image_patches = [to_numpy_array(image).astype(np.float32) / 255 for image in image_patches]
|
384 |
+
image_patches = [
|
385 |
+
self.normalize(image=image, mean=self.mean, std=self.std, input_data_format=input_data_format)
|
386 |
+
for image in image_patches
|
387 |
+
]
|
388 |
+
image_patches = [
|
389 |
+
to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=input_data_format)
|
390 |
+
for image in image_patches
|
391 |
+
]
|
392 |
+
for slice_image in image_patches:
|
393 |
+
new_images.append(self.reshape_by_patch(slice_image))
|
394 |
+
tgt_sizes.append(np.array((slice_image.shape[1] // self.patch_size, slice_image.shape[2] // self.patch_size)))
|
395 |
+
|
396 |
+
if tgt_sizes:
|
397 |
+
tgt_sizes = np.vstack(tgt_sizes)
|
398 |
+
return MiniCPMVBatchFeature(
|
399 |
+
data={"pixel_values": [new_images], "image_sizes": [image_sizes], "tgt_sizes": [tgt_sizes]}, tensor_type=return_tensors
|
400 |
+
)
|
401 |
+
|
402 |
+
AutoImageProcessor.register("MiniCPMVImageProcessor", MiniCPMVImageProcessor)
|
processing_minicpmv.py
ADDED
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
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 |
+
Processor class for MiniCPMV.
|
17 |
+
"""
|
18 |
+
|
19 |
+
from typing import List, Optional, Union, Dict, Any
|
20 |
+
import torch
|
21 |
+
import re
|
22 |
+
|
23 |
+
from transformers.image_processing_utils import BatchFeature
|
24 |
+
from transformers.image_utils import ImageInput
|
25 |
+
from transformers.processing_utils import ProcessorMixin
|
26 |
+
from transformers.tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
|
27 |
+
from transformers.utils import TensorType, requires_backends, is_torch_dtype, is_torch_device
|
28 |
+
|
29 |
+
from .image_processing_minicpmv import MiniCPMVBatchFeature
|
30 |
+
|
31 |
+
|
32 |
+
class MiniCPMVProcessor(ProcessorMixin):
|
33 |
+
r"""
|
34 |
+
Constructs a MiniCPMV processor which wraps a MiniCPMV image processor and a MiniCPMV tokenizer into a single processor.
|
35 |
+
|
36 |
+
[`MiniCPMVProcessor`] offers all the functionalities of [`MiniCPMVImageProcessor`] and [`LlamaTokenizerWrapper`]. See the
|
37 |
+
[`~MiniCPMVProcessor.__call__`] and [`~MiniCPMVProcessor.decode`] for more information.
|
38 |
+
|
39 |
+
Args:
|
40 |
+
image_processor ([`MiniCPMVImageProcessor`], *optional*):
|
41 |
+
The image processor is a required input.
|
42 |
+
tokenizer ([`LlamaTokenizerWrapper`], *optional*):
|
43 |
+
The tokenizer is a required input.
|
44 |
+
"""
|
45 |
+
attributes = ["image_processor", "tokenizer"]
|
46 |
+
image_processor_class = "AutoImageProcessor"
|
47 |
+
tokenizer_class = "AutoTokenizer"
|
48 |
+
|
49 |
+
def __init__(self, image_processor=None, tokenizer=None):
|
50 |
+
super().__init__(image_processor, tokenizer)
|
51 |
+
self.version = image_processor.version
|
52 |
+
|
53 |
+
def __call__(
|
54 |
+
self,
|
55 |
+
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
|
56 |
+
images: ImageInput = None,
|
57 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
58 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
59 |
+
max_length: Optional[int] = None,
|
60 |
+
do_pad: Optional[bool] = True,
|
61 |
+
return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
|
62 |
+
) -> MiniCPMVBatchFeature:
|
63 |
+
"""
|
64 |
+
Only support for single input for now. Batched input is coming soon.
|
65 |
+
|
66 |
+
Args:
|
67 |
+
text (`str`):
|
68 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
69 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
70 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
71 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
72 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
73 |
+
tensor. Both channels-first and channels-last formats are supported.
|
74 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
75 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
76 |
+
index) among:
|
77 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
78 |
+
sequence if provided).
|
79 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
80 |
+
acceptable input length for the model if that argument is not provided.
|
81 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
82 |
+
lengths).
|
83 |
+
max_length (`int`, *optional*):
|
84 |
+
Maximum length of the returned list and optionally padding length (see above).
|
85 |
+
do_pad (`bool`, *optional*, defaults to self.do_pad):
|
86 |
+
Whether to pad the image. If `True` will pad the images in the batch to the largest image in the batch
|
87 |
+
and create a pixel mask. Padding will be applied to the bottom and right of the image with zeros.
|
88 |
+
truncation (`bool`, *optional*):
|
89 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
90 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
91 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
92 |
+
|
93 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
94 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
95 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
96 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
97 |
+
|
98 |
+
Returns:
|
99 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
100 |
+
|
101 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
102 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
103 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
104 |
+
`None`).
|
105 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
106 |
+
"""
|
107 |
+
if images is not None:
|
108 |
+
image_inputs = self.image_processor(images, do_pad=do_pad, return_tensors=return_tensors)
|
109 |
+
return self._convert_images_texts_to_inputs(image_inputs, text, max_length=max_length)
|
110 |
+
|
111 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
|
112 |
+
def batch_decode(self, *args, **kwargs):
|
113 |
+
"""
|
114 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
115 |
+
refer to the docstring of this method for more information.
|
116 |
+
"""
|
117 |
+
output_ids = args[0]
|
118 |
+
result_text = []
|
119 |
+
for result in output_ids:
|
120 |
+
result = result[result != 0]
|
121 |
+
if result[0] == self.tokenizer.bos_id:
|
122 |
+
result = result[1:]
|
123 |
+
if result[-1] == self.tokenizer.eos_id:
|
124 |
+
result = result[:-1]
|
125 |
+
result_text.append(self.tokenizer.decode(result, *args[1:], **kwargs).strip())
|
126 |
+
return result_text
|
127 |
+
# return self.tokenizer.batch_decode(*args, **kwargs)
|
128 |
+
|
129 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
|
130 |
+
def decode(self, *args, **kwargs):
|
131 |
+
"""
|
132 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
133 |
+
the docstring of this method for more information.
|
134 |
+
"""
|
135 |
+
result = args[0]
|
136 |
+
result = result[result != 0]
|
137 |
+
if result[0] == self.tokenizer.bos_id:
|
138 |
+
result = result[1:]
|
139 |
+
if result[-1] == self.tokenizer.eos_id or (hasattr(self.tokenizer, "eot_id") and result[-1] == self.tokenizer.eot_id):
|
140 |
+
result = result[:-1]
|
141 |
+
return self.tokenizer.decode(result, *args[1:], **kwargs).strip()
|
142 |
+
|
143 |
+
def _convert(
|
144 |
+
self, input_str, max_inp_length: Optional[int] = None
|
145 |
+
):
|
146 |
+
if self.version == 2.5 or self.tokenizer.add_bos_token:
|
147 |
+
input_ids = self.tokenizer.encode(input_str)
|
148 |
+
else:
|
149 |
+
input_ids = [self.tokenizer.bos_id] + self.tokenizer.encode(input_str)
|
150 |
+
if max_inp_length is not None:
|
151 |
+
input_ids = input_ids[:max_inp_length]
|
152 |
+
input_ids = torch.tensor(input_ids, dtype=torch.int32)
|
153 |
+
|
154 |
+
image_start_tokens = torch.where(input_ids == self.tokenizer.im_start_id)[0]
|
155 |
+
image_start_tokens += 1
|
156 |
+
image_end_tokens = torch.where(input_ids == self.tokenizer.im_end_id)[0]
|
157 |
+
valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
|
158 |
+
image_bounds = torch.hstack(
|
159 |
+
[
|
160 |
+
image_start_tokens[:valid_image_nums].unsqueeze(-1),
|
161 |
+
image_end_tokens[:valid_image_nums].unsqueeze(-1),
|
162 |
+
]
|
163 |
+
)
|
164 |
+
return input_ids.unsqueeze(0), image_bounds
|
165 |
+
|
166 |
+
def _convert_images_texts_to_inputs(self, images, texts, do_pad=False, truncation=None, max_length=None, return_tensors=None):
|
167 |
+
if not len(images):
|
168 |
+
model_inputs = self.tokenizer(texts, return_tensors=return_tensors, padding=do_pad, truncation=truncation, max_length=max_length)
|
169 |
+
return MiniCPMVBatchFeature(data={**model_inputs})
|
170 |
+
|
171 |
+
pattern = "(<image>./</image>)"
|
172 |
+
images, image_sizes, tgt_sizes = images["pixel_values"], images["image_sizes"], images["tgt_sizes"]
|
173 |
+
|
174 |
+
image_tags = re.findall(pattern, texts)
|
175 |
+
assert len(image_tags) == len(image_sizes[0])
|
176 |
+
text_chunks = texts.split(pattern)
|
177 |
+
final_texts = ""
|
178 |
+
for i in range(len(image_tags)):
|
179 |
+
final_texts = final_texts + text_chunks[i] + self.image_processor.get_slice_image_placeholder(image_sizes[0][i])
|
180 |
+
final_texts += text_chunks[-1]
|
181 |
+
input_ids, image_bounds = self._convert(final_texts, max_length)
|
182 |
+
return MiniCPMVBatchFeature(data={
|
183 |
+
"input_ids": input_ids,
|
184 |
+
"pixel_values": images,
|
185 |
+
"image_sizes": image_sizes,
|
186 |
+
"image_bound": [image_bounds],
|
187 |
+
"tgt_sizes": tgt_sizes
|
188 |
+
})
|
189 |
+
|
190 |
+
@property
|
191 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
|
192 |
+
def model_input_names(self):
|
193 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
194 |
+
image_processor_input_names = self.image_processor.model_input_names
|
195 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
196 |
+
|
197 |
+
|
198 |
+
def pad(self, orig_items, key, max_length=None, padding_value=0, padding_side="left"):
|
199 |
+
items = []
|
200 |
+
if isinstance(orig_items[0][key], list):
|
201 |
+
assert isinstance(orig_items[0][key][0], torch.Tensor)
|
202 |
+
for it in orig_items:
|
203 |
+
for tr in it[key]:
|
204 |
+
items.append({key: tr})
|
205 |
+
else:
|
206 |
+
assert isinstance(orig_items[0][key], torch.Tensor)
|
207 |
+
items = orig_items
|
208 |
+
|
209 |
+
batch_size = len(items)
|
210 |
+
shape = items[0][key].shape
|
211 |
+
dim = len(shape)
|
212 |
+
assert dim <= 3
|
213 |
+
if max_length is None:
|
214 |
+
max_length = 0
|
215 |
+
max_length = max(max_length, max(item[key].shape[-1] for item in items))
|
216 |
+
min_length = min(item[key].shape[-1] for item in items)
|
217 |
+
dtype = items[0][key].dtype
|
218 |
+
|
219 |
+
if dim == 1:
|
220 |
+
return torch.cat([item[key] for item in items], dim=0)
|
221 |
+
elif dim == 2:
|
222 |
+
if max_length == min_length:
|
223 |
+
return torch.cat([item[key] for item in items], dim=0)
|
224 |
+
tensor = torch.zeros((batch_size, max_length), dtype=dtype) + padding_value
|
225 |
+
else:
|
226 |
+
tensor = (
|
227 |
+
torch.zeros((batch_size, max_length, shape[-1]), dtype=dtype)
|
228 |
+
+ padding_value
|
229 |
+
)
|
230 |
+
|
231 |
+
for i, item in enumerate(items):
|
232 |
+
if dim == 2:
|
233 |
+
if padding_side == "left":
|
234 |
+
tensor[i, -len(item[key][0]) :] = item[key][0].clone()
|
235 |
+
else:
|
236 |
+
tensor[i, : len(item[key][0])] = item[key][0].clone()
|
237 |
+
elif dim == 3:
|
238 |
+
if padding_side == "left":
|
239 |
+
tensor[i, -len(item[key][0]) :, :] = item[key][0].clone()
|
240 |
+
else:
|
241 |
+
tensor[i, : len(item[key][0]), :] = item[key][0].clone()
|
242 |
+
|
243 |
+
return tensor
|
244 |
+
|
tokenization_minicpmv_fast.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
|
3 |
+
from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
|
4 |
+
|
5 |
+
|
6 |
+
class MiniCPMVTokenizerFast(PreTrainedTokenizerFast):
|
7 |
+
def __init__(self, **kwargs):
|
8 |
+
super().__init__(**kwargs)
|
9 |
+
self.eot_token = "<|eot_id|>"
|
10 |
+
self.im_start = "<image>"
|
11 |
+
self.im_end = "</image>"
|
12 |
+
self.ref_start = "<ref>"
|
13 |
+
self.ref_end = "</ref>"
|
14 |
+
self.box_start = "<box>"
|
15 |
+
self.box_end = "</box>"
|
16 |
+
self.quad_start = "<quad>"
|
17 |
+
self.quad_end = "</quad>"
|
18 |
+
self.slice_start = "<slice>"
|
19 |
+
self.slice_end = "</slice>"
|
20 |
+
|
21 |
+
@property
|
22 |
+
def eos_id(self):
|
23 |
+
return self.eos_token_id
|
24 |
+
|
25 |
+
@property
|
26 |
+
def bos_id(self):
|
27 |
+
return self.bos_token_id
|
28 |
+
|
29 |
+
@property
|
30 |
+
def unk_id(self):
|
31 |
+
return self.unk_token_id
|
32 |
+
|
33 |
+
@property
|
34 |
+
def eot_id(self):
|
35 |
+
return self.convert_tokens_to_ids(self.eot_token)
|
36 |
+
|
37 |
+
@property
|
38 |
+
def im_start_id(self):
|
39 |
+
return self.convert_tokens_to_ids(self.im_start)
|
40 |
+
|
41 |
+
@property
|
42 |
+
def im_end_id(self):
|
43 |
+
return self.convert_tokens_to_ids(self.im_end)
|
44 |
+
|
45 |
+
@staticmethod
|
46 |
+
def escape(text: str) -> str:
|
47 |
+
return text
|
48 |
+
|
49 |
+
@staticmethod
|
50 |
+
def unescape(text: str) -> str:
|
51 |
+
return text
|