osmanio2 commited on
Commit
7b5f16e
1 Parent(s): a8d286c

Upload folder using huggingface_hub

Browse files
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)
modeling_minicpmv.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import json
3
+ import torch
4
+ from threading import Thread
5
+ from copy import deepcopy
6
+ from PIL import Image
7
+ from torchvision import transforms
8
+ from transformers import LlamaPreTrainedModel, LlamaForCausalLM, TextIteratorStreamer
9
+ from transformers.models.idefics2.modeling_idefics2 import Idefics2VisionTransformer
10
+ from transformers import AutoProcessor
11
+
12
+ from .configuration_minicpm import MiniCPMVConfig
13
+ from .resampler import Resampler
14
+
15
+ IMAGENET_INCEPTION_MEAN = (0.5, 0.5, 0.5) # timm.data.IMAGENET_INCEPTION_MEAN
16
+ IMAGENET_INCEPTION_STD = (0.5, 0.5, 0.5) # timm.data.IMAGENET_INCEPTION_STD
17
+
18
+ class MiniCPMVPreTrainedModel(LlamaPreTrainedModel):
19
+ config_class = MiniCPMVConfig
20
+
21
+
22
+ class MiniCPMV(MiniCPMVPreTrainedModel):
23
+ def __init__(self, config):
24
+ super().__init__(config)
25
+
26
+ self.llm = LlamaForCausalLM(config)
27
+ self.vpm = self.init_vision_module()
28
+ self.vision_dim = self.vpm.embed_dim
29
+ self.embed_dim = self.llm.config.hidden_size
30
+ self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
31
+ self.transform = self.init_transform()
32
+
33
+ def init_vision_module(self):
34
+ # same as HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit
35
+ model = Idefics2VisionTransformer(self.config.vision_config)
36
+ if self.config.drop_vision_last_layer:
37
+ model.encoder.layers = model.encoder.layers[:-1]
38
+
39
+ setattr(model, 'embed_dim', model.embeddings.embed_dim)
40
+ setattr(model, 'patch_size', model.embeddings.patch_size)
41
+
42
+ return model
43
+
44
+ def init_resampler(self, embed_dim, vision_dim):
45
+ return Resampler(
46
+ num_queries=self.config.query_num,
47
+ embed_dim=embed_dim,
48
+ num_heads=embed_dim // 128,
49
+ kv_dim=vision_dim,
50
+ adaptive=True
51
+ )
52
+
53
+ def init_transform(self):
54
+ return transforms.Compose(
55
+ [
56
+ transforms.ToTensor(),
57
+ transforms.Normalize(
58
+ mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD
59
+ ),
60
+ ]
61
+ )
62
+
63
+ def get_input_embeddings(self):
64
+ return self.llm.get_input_embeddings()
65
+
66
+ def set_input_embeddings(self, value):
67
+ self.llm.embed_tokens = value
68
+
69
+ def get_output_embeddings(self):
70
+ return self.llm.lm_head
71
+
72
+ def set_output_embeddings(self, new_embeddings):
73
+ self.llm.lm_head = new_embeddings
74
+
75
+ def set_decoder(self, decoder):
76
+ self.llm = decoder
77
+
78
+ def get_decoder(self):
79
+ return self.llm
80
+
81
+ def get_vllm_embedding(self, data):
82
+ if 'vision_hidden_states' not in data:
83
+ dtype = self.llm.model.embed_tokens.weight.dtype
84
+ device = self.llm.model.embed_tokens.weight.device
85
+ tgt_sizes = data['tgt_sizes']
86
+ pixel_values_list = data['pixel_values']
87
+ vision_hidden_states = []
88
+ all_pixel_values = []
89
+ img_cnt = []
90
+ for pixel_values in pixel_values_list:
91
+ img_cnt.append(len(pixel_values))
92
+ all_pixel_values.extend([i.flatten(end_dim=1).permute(1, 0) for i in pixel_values])
93
+
94
+ # exist image
95
+ if all_pixel_values:
96
+ tgt_sizes = torch.vstack(tgt_sizes).type(torch.int32)
97
+
98
+ if self.config.batch_vision_input:
99
+ max_patches = torch.max(tgt_sizes[:, 0] * tgt_sizes[:, 1])
100
+
101
+ all_pixel_values = torch.nn.utils.rnn.pad_sequence(all_pixel_values, batch_first=True,
102
+ padding_value=0.0)
103
+ B, L, _ = all_pixel_values.shape
104
+ all_pixel_values = all_pixel_values.permute(0, 2, 1).reshape(B, 3, -1, L)
105
+
106
+ patch_attn_mask = torch.zeros((B, 1, max_patches), dtype=torch.bool, device=device)
107
+ for i in range(B):
108
+ patch_attn_mask[i, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
109
+
110
+ vision_embedding = self.vpm(all_pixel_values.type(dtype), patch_attention_mask=patch_attn_mask).last_hidden_state
111
+ vision_embedding = self.resampler(vision_embedding, tgt_sizes)
112
+ else:
113
+ # get vision_embedding foreach
114
+ vision_embedding = []
115
+ for single_tgt_size, single_pixel_values in zip(tgt_sizes, all_pixel_values):
116
+ single_pixel_values = single_pixel_values.unsqueeze(0)
117
+ B, L, _ = single_pixel_values.shape
118
+ single_pixel_values = single_pixel_values.permute(0, 2, 1).reshape(B, 3, -1, L)
119
+ single_vision_embedding = self.vpm(single_pixel_values.type(dtype)).last_hidden_state
120
+ single_vision_embedding = self.resampler(single_vision_embedding, single_tgt_size.unsqueeze(0))
121
+ vision_embedding.append(single_vision_embedding)
122
+ vision_embedding = torch.vstack(vision_embedding)
123
+
124
+ start = 0
125
+ for pixel_values in pixel_values_list:
126
+ img_cnt = len(pixel_values)
127
+ if img_cnt > 0:
128
+ vision_hidden_states.append(vision_embedding[start: start + img_cnt])
129
+ start += img_cnt
130
+ else:
131
+ vision_hidden_states.append([])
132
+ else: # no image
133
+ if self.training:
134
+ dummy_image = torch.zeros(
135
+ (1, 3, 224, 224),
136
+ device=device, dtype=dtype
137
+ )
138
+ tgt_sizes = torch.Tensor([[(224 // self.config.patch_size), math.ceil(224 / self.config.patch_size)]]).type(torch.int32)
139
+ dummy_feature = self.resampler(self.vpm(dummy_image).last_hidden_state, tgt_sizes)
140
+ else:
141
+ dummy_feature = []
142
+ for _ in range(len(pixel_values_list)):
143
+ vision_hidden_states.append(dummy_feature)
144
+
145
+ else:
146
+ vision_hidden_states = data['vision_hidden_states']
147
+
148
+ if hasattr(self.llm.config, 'scale_emb'):
149
+ vllm_embedding = self.llm.model.embed_tokens(data['input_ids']) * self.llm.config.scale_emb
150
+ else:
151
+ vllm_embedding = self.llm.model.embed_tokens(data['input_ids'])
152
+
153
+ vision_hidden_states = [i.type(vllm_embedding.dtype) if isinstance(
154
+ i, torch.Tensor) else i for i in vision_hidden_states]
155
+
156
+ bs = len(data['input_ids'])
157
+ for i in range(bs):
158
+ cur_vs_hs = vision_hidden_states[i]
159
+ if len(cur_vs_hs) > 0:
160
+ cur_vllm_emb = vllm_embedding[i]
161
+ cur_image_bound = data['image_bound'][i]
162
+ if len(cur_image_bound) > 0:
163
+ image_indices = torch.stack(
164
+ [torch.arange(r[0], r[1], dtype=torch.long) for r in cur_image_bound]
165
+ ).to(vllm_embedding.device)
166
+
167
+ cur_vllm_emb.scatter_(0, image_indices.view(-1, 1).repeat(1, cur_vllm_emb.shape[-1]),
168
+ cur_vs_hs.view(-1, cur_vs_hs.shape[-1]))
169
+ elif self.training:
170
+ cur_vllm_emb += cur_vs_hs[0].mean() * 0
171
+
172
+ return vllm_embedding, vision_hidden_states
173
+
174
+ def forward(self, data, **kwargs):
175
+ vllm_embedding, vision_hidden_states = self.get_vllm_embedding(data)
176
+ position_ids = data["position_ids"]
177
+ if position_ids.dtype != torch.int64:
178
+ position_ids = position_ids.long()
179
+
180
+ return self.llm(
181
+ input_ids=None,
182
+ position_ids=position_ids,
183
+ inputs_embeds=vllm_embedding,
184
+ **kwargs
185
+ )
186
+
187
+ def _decode_text(self, result_ids, tokenizer):
188
+ result_text = []
189
+ for result in result_ids:
190
+ result = result[result != 0]
191
+ if result[0] == tokenizer.bos_id:
192
+ result = result[1:]
193
+ if result[-1] == tokenizer.eos_id or result[-1] == tokenizer.eot_id:
194
+ result = result[:-1]
195
+ result_text.append(tokenizer.decode(result).strip())
196
+ return result_text
197
+
198
+ def _decode(self, inputs_embeds, tokenizer, decode_text=False, **kwargs):
199
+ terminators = [
200
+ tokenizer.eos_token_id,
201
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
202
+ ]
203
+ output = self.llm.generate(
204
+ inputs_embeds=inputs_embeds,
205
+ pad_token_id=0,
206
+ eos_token_id=terminators,
207
+ **kwargs
208
+ )
209
+ if decode_text:
210
+ return self._decode_text(output, tokenizer)
211
+ return output
212
+
213
+ def _decode_stream(self, inputs_embeds, tokenizer, **kwargs):
214
+ terminators = [
215
+ tokenizer.eos_token_id,
216
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
217
+ ]
218
+ streamer = TextIteratorStreamer(tokenizer=tokenizer)
219
+ generation_kwargs = {
220
+ 'inputs_embeds': inputs_embeds,
221
+ 'pad_token_id': 0,
222
+ 'eos_token_id': terminators,
223
+ 'streamer': streamer
224
+ }
225
+ generation_kwargs.update(kwargs)
226
+
227
+ thread = Thread(target=self.llm.generate, kwargs=generation_kwargs)
228
+ thread.start()
229
+
230
+ return streamer
231
+
232
+ def generate(
233
+ self,
234
+ model_inputs,
235
+ tokenizer=None,
236
+ vision_hidden_states=None,
237
+ stream=False,
238
+ **kwargs
239
+ ):
240
+ bs = len(model_inputs["input_ids"])
241
+ img_list = model_inputs["pixel_values"]
242
+ tgt_sizes = model_inputs["tgt_sizes"]
243
+ if img_list is None:
244
+ img_list = [[] for i in range(bs)]
245
+ assert bs == len(img_list)
246
+ if vision_hidden_states is None:
247
+ pixel_values = []
248
+ for i in range(bs):
249
+ img_inps = []
250
+ for img in img_list[i]:
251
+ img_inps.append(img.to(self.device))
252
+ if img_inps:
253
+ pixel_values.append(img_inps)
254
+ else:
255
+ pixel_values.append([])
256
+ model_inputs["pixel_values"] = pixel_values
257
+ model_inputs['tgt_sizes'] = tgt_sizes
258
+ else:
259
+ model_inputs["vision_hidden_states"] = vision_hidden_states
260
+
261
+ (
262
+ input_embeds,
263
+ vision_hidden_states,
264
+ ) = self.get_vllm_embedding(model_inputs)
265
+
266
+ # output_ids = self._decode(input_embeds, tokenizer, **kwargs)
267
+ if stream:
268
+ kwargs.pop("decode_text")
269
+ result = self._decode_stream(input_embeds, tokenizer, **kwargs)
270
+ else:
271
+ result = self._decode(input_embeds, tokenizer, **kwargs)
272
+
273
+ return result
274
+
275
+ def chat(
276
+ self,
277
+ image,
278
+ msgs,
279
+ tokenizer,
280
+ processor=None,
281
+ vision_hidden_states=None,
282
+ max_new_tokens=1024,
283
+ sampling=True,
284
+ max_inp_length=2048,
285
+ system_prompt='',
286
+ stream=False,
287
+ **kwargs
288
+ ):
289
+ if processor is None:
290
+ processor = AutoProcessor.from_pretrained(self.config._name_or_path, trust_remote_code=True)
291
+ if isinstance(msgs, str):
292
+ msgs = json.loads(msgs)
293
+ copy_msgs = deepcopy(msgs)
294
+
295
+ assert len(msgs) > 0, "msgs is empty"
296
+ assert sampling or not stream, "if use stream mode, make sure sampling=True"
297
+
298
+ if image is not None and isinstance(copy_msgs[0]["content"], str):
299
+ # copy_msgs[0]['content'] = '(<image>./</image>)\n' + copy_msgs[0]['content']
300
+ copy_msgs[0]["content"] = [image, copy_msgs[0]["content"]]
301
+
302
+ images = []
303
+ for i, msg in enumerate(copy_msgs):
304
+ role = msg["role"]
305
+ content = msg["content"]
306
+ assert role in ["user", "assistant"]
307
+ if i == 0:
308
+ assert role == "user", "The role of first msg should be user"
309
+ if isinstance(content, str):
310
+ content = [content]
311
+ cur_msgs = []
312
+ for c in content:
313
+ if isinstance(c, Image.Image):
314
+ images.append(c)
315
+ cur_msgs.append("(<image>./</image>)")
316
+ elif isinstance(c, str):
317
+ cur_msgs.append(c)
318
+ msg["content"] = "\n".join(cur_msgs)
319
+
320
+ if system_prompt:
321
+ sys_msg = {'role': 'system', 'content': system_prompt}
322
+ copy_msgs = [sys_msg] + copy_msgs
323
+
324
+ prompt = processor.tokenizer.apply_chat_template(copy_msgs, tokenize=False, add_generation_prompt=True)
325
+ inputs = processor(prompt, images, return_tensors="pt", max_length=max_inp_length).to(self.device)
326
+
327
+ if sampling:
328
+ generation_config = {
329
+ "top_p": 0.8,
330
+ "top_k": 100,
331
+ "temperature": 0.7,
332
+ "do_sample": True,
333
+ "repetition_penalty": 1.05
334
+ }
335
+ else:
336
+ generation_config = {
337
+ "num_beams": 3,
338
+ "repetition_penalty": 1.2,
339
+ }
340
+
341
+ generation_config.update(
342
+ (k, kwargs[k]) for k in generation_config.keys() & kwargs.keys()
343
+ )
344
+ with torch.inference_mode():
345
+ res = self.generate(
346
+ inputs,
347
+ tokenizer=tokenizer,
348
+ max_new_tokens=max_new_tokens,
349
+ vision_hidden_states=vision_hidden_states,
350
+ stream=stream,
351
+ decode_text=True,
352
+ **generation_config
353
+ )
354
+
355
+ if stream:
356
+ def stream_gen():
357
+ for text in res:
358
+ text = text.replace(tokenizer.eot_token, '').replace(tokenizer.eos_token, '')
359
+ yield text
360
+ return stream_gen()
361
+
362
+ else:
363
+ answer = res[0]
364
+ return answer
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
+