hezhihui commited on
Commit
b07c810
1 Parent(s): 52e5139

add processor & image processor

Browse files
configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"framework":"Pytorch","task":"multimodal-dialogue"}
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 CHANGED
@@ -9,6 +9,7 @@ from PIL import Image
9
  from torchvision import transforms
10
  from transformers import LlamaTokenizer, LlamaPreTrainedModel, LlamaForCausalLM, AutoModel, PreTrainedTokenizerFast, TextIteratorStreamer
11
  from transformers.models.idefics2.modeling_idefics2 import Idefics2VisionTransformer
 
12
 
13
  from .configuration_minicpm import MiniCPMVConfig
14
  from .resampler import Resampler
@@ -42,13 +43,13 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
42
 
43
  return model
44
 
45
- def init_resampler(self, embed_dim, vision_dim,):
46
  return Resampler(
47
  num_queries=self.config.query_num,
48
  embed_dim=embed_dim,
49
  num_heads=embed_dim // 128,
50
  kv_dim=vision_dim,
51
- adaptive=True,
52
  )
53
 
54
  def init_transform(self):
@@ -60,17 +61,29 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
60
  ),
61
  ]
62
  )
63
-
64
  def get_input_embeddings(self):
65
  return self.llm.get_input_embeddings()
66
 
67
  def set_input_embeddings(self, value):
68
  self.llm.embed_tokens = value
69
-
 
 
 
 
 
 
 
 
 
 
 
 
70
  def get_vllm_embedding(self, data):
71
  if 'vision_hidden_states' not in data:
72
- dtype = self.llm.model.embed_tokens.weight.dtype
73
- device = self.llm.model.embed_tokens.weight.device
74
  tgt_sizes = data['tgt_sizes']
75
  pixel_values_list = data['pixel_values']
76
  vision_hidden_states = []
@@ -78,9 +91,7 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
78
  img_cnt = []
79
  for pixel_values in pixel_values_list:
80
  img_cnt.append(len(pixel_values))
81
- all_pixel_values.extend([i.flatten(end_dim=1).permute(1, 0) for i in pixel_values])
82
-
83
- # exist image
84
  if all_pixel_values:
85
  tgt_sizes = torch.vstack(tgt_sizes).type(torch.int32)
86
 
@@ -107,7 +118,6 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
107
  single_pixel_values = single_pixel_values.permute(0, 2, 1).reshape(B, 3, -1, L)
108
  single_vision_embedding = self.vpm(single_pixel_values.type(dtype)).last_hidden_state
109
  single_vision_embedding = self.resampler(single_vision_embedding, single_tgt_size.unsqueeze(0))
110
-
111
  vision_embedding.append(single_vision_embedding)
112
  vision_embedding = torch.vstack(vision_embedding)
113
 
@@ -148,18 +158,19 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
148
  cur_vs_hs = vision_hidden_states[i]
149
  if len(cur_vs_hs) > 0:
150
  cur_vllm_emb = vllm_embedding[i]
151
- cur_image_bound = data['image_bound'][i]
152
  if len(cur_image_bound) > 0:
153
  image_indices = torch.stack(
154
  [torch.arange(r[0], r[1], dtype=torch.long) for r in cur_image_bound]
155
  ).to(vllm_embedding.device)
 
156
  cur_vllm_emb.scatter_(0, image_indices.view(-1, 1).repeat(1, cur_vllm_emb.shape[-1]),
157
  cur_vs_hs.view(-1, cur_vs_hs.shape[-1]))
158
  elif self.training:
159
  cur_vllm_emb += cur_vs_hs[0].mean() * 0
160
-
161
- return vllm_embedding, vision_hidden_states
162
 
 
 
163
  def forward(self, data, **kwargs):
164
  vllm_embedding, vision_hidden_states = self.get_vllm_embedding(data)
165
  position_ids = data["position_ids"]
@@ -173,47 +184,18 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
173
  **kwargs
174
  )
175
 
176
- def _convert_to_tensors(
177
- self, tokenizer, input_ids, max_inp_length: Optional[int] = None
178
- ):
179
- if max_inp_length is not None:
180
- input_ids = input_ids[:max_inp_length]
181
- input_ids = torch.tensor(input_ids, dtype=torch.int32)
182
-
183
- image_start_tokens = torch.where(input_ids == tokenizer.im_start_id)[0]
184
- # 跳过 im_start
185
- image_start_tokens += 1
186
- image_end_tokens = torch.where(input_ids == tokenizer.im_end_id)[0]
187
- valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
188
- image_bound = torch.hstack(
189
- [
190
- image_start_tokens[:valid_image_nums].unsqueeze(-1),
191
- image_end_tokens[:valid_image_nums].unsqueeze(-1),
192
- ]
193
- )
194
-
195
- model_input = {}
196
- model_input["input_ids"] = input_ids.unsqueeze(0).to(self.device)
197
- model_input["image_bound"] = image_bound
198
-
199
- return model_input
200
-
201
- def _process_list(
202
- self, tokenizer, input_id_list, max_inp_length: Optional[int] = None
203
- ):
204
- pad_keys = ["input_ids"]
205
- input_tensors = []
206
- for input_ids in input_id_list:
207
- input_tensors.append(
208
- self._convert_to_tensors(tokenizer, input_ids, max_inp_length)
209
- )
210
- padded = {}
211
- for key in pad_keys:
212
- padded[key] = pad(input_tensors, key, padding_side="left").to(self.device)
213
- padded["image_bound"] = [i["image_bound"] for i in input_tensors]
214
- return padded
215
 
216
- def _decode(self, inputs_embeds, tokenizer, **kwargs):
217
  terminators = [
218
  tokenizer.eos_token_id,
219
  tokenizer.convert_tokens_to_ids("<|eot_id|>")
@@ -224,7 +206,9 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
224
  eos_token_id=terminators,
225
  **kwargs
226
  )
227
- return self._decode_text(output, tokenizer)
 
 
228
 
229
  def _decode_stream(self, inputs_embeds, tokenizer, **kwargs):
230
  terminators = [
@@ -245,93 +229,20 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
245
 
246
  return streamer
247
 
248
- def _decode_text(self, result_ids, tokenizer):
249
- result_text = []
250
- for result in result_ids:
251
- result = result[result != 0]
252
- if result[0] == tokenizer.bos_id:
253
- result = result[1:]
254
- if result[-1] == tokenizer.eos_id or result[-1] == tokenizer.eot_id:
255
- result = result[:-1]
256
- result_text.append(tokenizer.decode(result).strip())
257
- return result_text
258
-
259
- def slice_image(self, image):
260
- return slice_image(
261
- image,
262
- self.config.slice_config.max_slice_nums,
263
- self.config.slice_config.scale_resolution,
264
- self.config.slice_config.patch_size,
265
- )
266
-
267
- def get_slice_image_placeholder(self, image, tokenizer):
268
- image_placeholder = (
269
- tokenizer.im_start
270
- + tokenizer.unk_token * self.config.query_num
271
- + tokenizer.im_end
272
- )
273
-
274
- slice_images = []
275
-
276
- source_image, patches, best_grid = slice_image(
277
- image,
278
- self.config.slice_config.max_slice_nums,
279
- self.config.slice_config.scale_resolution,
280
- self.config.slice_config.patch_size,
281
- )
282
-
283
- slice_images.append(source_image)
284
- final_placeholder = image_placeholder
285
-
286
- if len(patches) > 0:
287
- for i in range(len(patches)):
288
- for j in range(len(patches[0])):
289
- slice_images.append(patches[i][j])
290
-
291
- final_placeholder += get_grid_placeholder(
292
- tokenizer, best_grid, self.config.query_num
293
- )
294
-
295
- return slice_images, final_placeholder
296
-
297
- def reshape_by_patch(self, image_tensor):
298
- """
299
- :param image_tensor: shape [3, H, W]
300
- :param patch_size:
301
- :return: [3, patch_size, HW/patch_size]
302
- """
303
- patch_size = self.config.patch_size
304
- patches = torch.nn.functional.unfold(
305
- image_tensor,
306
- (patch_size, patch_size),
307
- stride=(patch_size, patch_size)
308
- )
309
-
310
- patches = patches.reshape(image_tensor.size(0), patch_size, patch_size, -1)
311
- patches = patches.permute(0, 1, 3, 2).reshape(image_tensor.size(0), patch_size, -1)
312
- return patches
313
-
314
  def generate(
315
  self,
316
- input_id_list=None,
317
- img_list=None,
318
- tgt_sizes=None,
319
  tokenizer=None,
320
- max_inp_length: Optional[int] = None,
321
  vision_hidden_states=None,
322
- return_vision_hidden_states=False,
323
  stream=False,
324
  **kwargs
325
  ):
326
-
327
- assert input_id_list is not None
328
- bs = len(input_id_list)
329
- if img_list == None:
330
  img_list = [[] for i in range(bs)]
331
  assert bs == len(img_list)
332
-
333
- model_inputs = self._process_list(tokenizer, input_id_list, max_inp_length)
334
-
335
  if vision_hidden_states is None:
336
  pixel_values = []
337
  for i in range(bs):
@@ -347,19 +258,17 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
347
  else:
348
  model_inputs["vision_hidden_states"] = vision_hidden_states
349
 
350
- with torch.inference_mode():
351
- (
352
- model_inputs["inputs_embeds"],
353
- vision_hidden_states,
354
- ) = self.get_vllm_embedding(model_inputs)
355
 
356
- if stream:
357
- result = self._decode_stream(model_inputs["inputs_embeds"], tokenizer, **kwargs)
358
- else:
359
- result = self._decode(model_inputs["inputs_embeds"], tokenizer, **kwargs)
360
-
361
- if return_vision_hidden_states:
362
- return result, vision_hidden_states
363
 
364
  return result
365
 
@@ -368,6 +277,7 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
368
  image,
369
  msgs,
370
  tokenizer,
 
371
  vision_hidden_states=None,
372
  max_new_tokens=1024,
373
  sampling=True,
@@ -376,61 +286,22 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
376
  stream=False,
377
  **kwargs
378
  ):
 
 
379
  if isinstance(msgs, str):
380
  msgs = json.loads(msgs)
381
 
382
- copy_msgs = deepcopy(msgs)
383
- assert len(copy_msgs) > 0, 'msgs is empty'
384
  assert sampling or not stream, 'if use stream mode, make sure sampling=True'
385
 
386
- if image is not None and isinstance(copy_msgs[0]['content'], str):
387
- copy_msgs[0]['content'] = [image, copy_msgs[0]['content']]
388
-
389
- images = []
390
- tgt_sizes = []
391
- for i, msg in enumerate(copy_msgs):
392
- role = msg["role"]
393
- content = msg["content"]
394
- assert role in ["user", "assistant"]
395
- if i == 0:
396
- assert role == "user", "The role of first msg should be user"
397
- if isinstance(content, str):
398
- content = [content]
399
-
400
- cur_msgs = []
401
- for c in content:
402
- if isinstance(c, Image.Image):
403
- image = c
404
- if self.config.slice_mode:
405
- slice_images, image_placeholder = self.get_slice_image_placeholder(
406
- image, tokenizer
407
- )
408
- cur_msgs.append(image_placeholder)
409
- for slice_image in slice_images:
410
- slice_image = self.transform(slice_image)
411
- H, W = slice_image.shape[1:]
412
- images.append(self.reshape_by_patch(slice_image))
413
- tgt_sizes.append(torch.Tensor([H // self.config.patch_size, W // self.config.patch_size]).type(torch.int32))
414
- else:
415
- images.append(self.transform(image))
416
- cur_msgs.append(
417
- tokenizer.im_start
418
- + tokenizer.unk_token * self.config.query_num
419
- + tokenizer.im_end
420
- )
421
- elif isinstance(c, str):
422
- cur_msgs.append(c)
423
-
424
-
425
- msg['content'] = '\n'.join(cur_msgs)
426
- if tgt_sizes:
427
- tgt_sizes = torch.vstack(tgt_sizes)
428
-
429
  if system_prompt:
430
  sys_msg = {'role': 'system', 'content': system_prompt}
431
- copy_msgs = [sys_msg] + copy_msgs
432
 
433
- input_ids = tokenizer.apply_chat_template(copy_msgs, tokenize=True, add_generation_prompt=False)
 
434
 
435
  if sampling:
436
  generation_config = {
@@ -449,21 +320,17 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
449
  generation_config.update(
450
  (k, kwargs[k]) for k in generation_config.keys() & kwargs.keys()
451
  )
452
-
453
  with torch.inference_mode():
454
- res, vision_hidden_states = self.generate(
455
- input_id_list=[input_ids],
456
- max_inp_length=max_inp_length,
457
- img_list=[images],
458
- tgt_sizes=[tgt_sizes],
459
  tokenizer=tokenizer,
460
  max_new_tokens=max_new_tokens,
461
  vision_hidden_states=vision_hidden_states,
462
- return_vision_hidden_states=True,
463
  stream=stream,
 
464
  **generation_config
465
  )
466
-
467
  if stream:
468
  def stream_gen():
469
  for text in res:
@@ -474,229 +341,3 @@ class MiniCPMV(MiniCPMVPreTrainedModel):
474
  else:
475
  answer = res[0]
476
  return answer
477
-
478
-
479
- class PreTrainedTokenizerFastWrapper(PreTrainedTokenizerFast):
480
- def __init__(self, **kwargs):
481
- super().__init__(**kwargs)
482
- self.eot_token = "<|eot_id|>"
483
- self.im_start = "<image>"
484
- self.im_end = "</image>"
485
- self.ref_start = "<ref>"
486
- self.ref_end = "</ref>"
487
- self.box_start = "<box>"
488
- self.box_end = "</box>"
489
- self.quad_start = "<quad>"
490
- self.quad_end = "</quad>"
491
- self.slice_start = "<slice>"
492
- self.slice_end = "</slice>"
493
-
494
- @property
495
- def eos_id(self):
496
- return self.eos_token_id
497
-
498
- @property
499
- def bos_id(self):
500
- return self.bos_token_id
501
-
502
- @property
503
- def unk_id(self):
504
- return self.unk_token_id
505
-
506
- @property
507
- def eot_id(self):
508
- return self.convert_tokens_to_ids(self.eot_token)
509
-
510
- @property
511
- def im_start_id(self):
512
- return self.convert_tokens_to_ids(self.im_start)
513
-
514
- @property
515
- def im_end_id(self):
516
- return self.convert_tokens_to_ids(self.im_end)
517
-
518
- @staticmethod
519
- def escape(text: str) -> str:
520
- return text
521
-
522
- @staticmethod
523
- def unescape(text: str) -> str:
524
- return text
525
-
526
-
527
- def pad(orig_items, key, max_length=None, padding_value=0, padding_side="left"):
528
- items = []
529
- if isinstance(orig_items[0][key], list):
530
- assert isinstance(orig_items[0][key][0], torch.Tensor)
531
- for it in orig_items:
532
- for tr in it[key]:
533
- items.append({key: tr})
534
- else:
535
- assert isinstance(orig_items[0][key], torch.Tensor)
536
- items = orig_items
537
-
538
- batch_size = len(items)
539
- shape = items[0][key].shape
540
- dim = len(shape)
541
- assert dim <= 3
542
- if max_length is None:
543
- max_length = 0
544
- max_length = max(max_length, max(item[key].shape[-1] for item in items))
545
- min_length = min(item[key].shape[-1] for item in items)
546
- dtype = items[0][key].dtype
547
-
548
- if dim == 1:
549
- return torch.cat([item[key] for item in items], dim=0)
550
- elif dim == 2:
551
- if max_length == min_length:
552
- return torch.cat([item[key] for item in items], dim=0)
553
- tensor = torch.zeros((batch_size, max_length), dtype=dtype) + padding_value
554
- else:
555
- tensor = (
556
- torch.zeros((batch_size, max_length, shape[-1]), dtype=dtype)
557
- + padding_value
558
- )
559
-
560
- for i, item in enumerate(items):
561
- if dim == 2:
562
- if padding_side == "left":
563
- tensor[i, -len(item[key][0]) :] = item[key][0].clone()
564
- else:
565
- tensor[i, : len(item[key][0])] = item[key][0].clone()
566
- elif dim == 3:
567
- if padding_side == "left":
568
- tensor[i, -len(item[key][0]) :, :] = item[key][0].clone()
569
- else:
570
- tensor[i, : len(item[key][0]), :] = item[key][0].clone()
571
-
572
- return tensor
573
-
574
-
575
- def slice_image(
576
- image, max_slice_nums=9, scale_resolution=448, patch_size=14, never_split=False
577
- ):
578
- original_size = image.size
579
- original_width, original_height = original_size
580
- log_ratio = math.log(original_width / original_height)
581
- ratio = original_width * original_height / (scale_resolution * scale_resolution)
582
- multiple = min(math.ceil(ratio), max_slice_nums)
583
-
584
- source_image = None
585
- best_grid = None
586
- patches = []
587
-
588
- if multiple <= 1 or never_split:
589
- # dont need to slice, upsample
590
- best_size = find_best_resize(
591
- original_size, scale_resolution, patch_size, allow_upscale=True
592
- )
593
- source_image = image.resize(best_size, Image.Resampling.BICUBIC)
594
- else:
595
- candidate_split_grids_nums = []
596
- for i in [multiple - 1, multiple, multiple + 1]:
597
- if i == 1 or i > max_slice_nums:
598
- continue
599
- candidate_split_grids_nums.append(i)
600
-
601
- # source image, down-sampling and ensure divided by patch_size
602
- best_resize = find_best_resize(original_size, scale_resolution, patch_size)
603
- source_image = image.copy().resize(best_resize, Image.Resampling.BICUBIC)
604
- candidate_grids = []
605
-
606
- # find best grid
607
- for split_grids_nums in candidate_split_grids_nums:
608
- m = 1
609
- while m <= split_grids_nums:
610
- if split_grids_nums % m == 0:
611
- candidate_grids.append([m, split_grids_nums // m])
612
- m += 1
613
-
614
- best_grid = [1, 1]
615
- min_error = float("inf")
616
- for grid in candidate_grids:
617
- error = abs(log_ratio - math.log(grid[0] / grid[1]))
618
- if error < min_error:
619
- best_grid = grid
620
- min_error = error
621
-
622
- refine_size = get_refine_size(
623
- original_size, best_grid, scale_resolution, patch_size, allow_upscale=True
624
- )
625
-
626
- refine_image = image.resize(refine_size, Image.Resampling.BICUBIC)
627
- patches = split_to_patches(refine_image, best_grid)
628
-
629
- return source_image, patches, best_grid
630
-
631
-
632
- def ensure_divide(length, patch_size):
633
- return max(round(length / patch_size) * patch_size, patch_size)
634
-
635
-
636
- def find_best_resize(original_size, scale_resolution, patch_size, allow_upscale=False):
637
- width, height = original_size
638
- if (width * height > scale_resolution * scale_resolution) or allow_upscale:
639
- r = width / height
640
- height = int(scale_resolution / math.sqrt(r))
641
- width = int(height * r)
642
- best_width = ensure_divide(width, patch_size)
643
- best_height = ensure_divide(height, patch_size)
644
- return (best_width, best_height)
645
-
646
-
647
- def get_refine_size(
648
- original_size, grid, scale_resolution, patch_size, allow_upscale=False
649
- ):
650
- width, height = original_size
651
- grid_x, grid_y = grid
652
-
653
- refine_width = ensure_divide(width, grid_x)
654
- refine_height = ensure_divide(height, grid_y)
655
-
656
- grid_width = refine_width / grid_x
657
- grid_height = refine_height / grid_y
658
-
659
- best_grid_size = find_best_resize(
660
- (grid_width, grid_height),
661
- scale_resolution,
662
- patch_size,
663
- allow_upscale=allow_upscale,
664
- )
665
-
666
- refine_size = (best_grid_size[0] * grid_x, best_grid_size[1] * grid_y)
667
-
668
- return refine_size
669
-
670
-
671
- def split_to_patches(image, grid):
672
- patches = []
673
- width, height = image.size
674
- grid_x = int(width / grid[0])
675
- grid_y = int(height / grid[1])
676
-
677
- for i in range(0, height, grid_y):
678
- images = []
679
- for j in range(0, width, grid_x):
680
- box = (j, i, j + grid_x, i + grid_y)
681
- patch = image.crop(box)
682
- images.append(patch)
683
- patches.append(images)
684
-
685
- return patches
686
-
687
-
688
- def get_grid_placeholder(tokenizer, grid, query_num):
689
- image_placeholder = (
690
- tokenizer.im_start + tokenizer.unk_token * query_num + tokenizer.im_end
691
- )
692
-
693
- cols = grid[0]
694
- rows = grid[1]
695
- slices = []
696
- for i in range(rows):
697
- lines = []
698
- for j in range(cols):
699
- lines.append(image_placeholder)
700
- slices.append("".join(lines))
701
- slice_placeholder = tokenizer.slice_start + "\n".join(slices) + tokenizer.slice_end
702
- return slice_placeholder
 
9
  from torchvision import transforms
10
  from transformers import LlamaTokenizer, LlamaPreTrainedModel, LlamaForCausalLM, AutoModel, PreTrainedTokenizerFast, TextIteratorStreamer
11
  from transformers.models.idefics2.modeling_idefics2 import Idefics2VisionTransformer
12
+ from transformers import AutoProcessor
13
 
14
  from .configuration_minicpm import MiniCPMVConfig
15
  from .resampler import Resampler
 
43
 
44
  return model
45
 
46
+ def init_resampler(self, embed_dim, vision_dim):
47
  return Resampler(
48
  num_queries=self.config.query_num,
49
  embed_dim=embed_dim,
50
  num_heads=embed_dim // 128,
51
  kv_dim=vision_dim,
52
+ adaptive=True
53
  )
54
 
55
  def init_transform(self):
 
61
  ),
62
  ]
63
  )
64
+
65
  def get_input_embeddings(self):
66
  return self.llm.get_input_embeddings()
67
 
68
  def set_input_embeddings(self, value):
69
  self.llm.embed_tokens = value
70
+
71
+ def get_output_embeddings(self):
72
+ return self.llm.lm_head
73
+
74
+ def set_output_embeddings(self, new_embeddings):
75
+ self.llm.lm_head = new_embeddings
76
+
77
+ def set_decoder(self, decoder):
78
+ self.llm = decoder
79
+
80
+ def get_decoder(self):
81
+ return self.llm
82
+
83
  def get_vllm_embedding(self, data):
84
  if 'vision_hidden_states' not in data:
85
+ dtype = self.vpm.embeddings.position_embedding.weight.dtype
86
+ device = self.vpm.embeddings.position_embedding.weight.device
87
  tgt_sizes = data['tgt_sizes']
88
  pixel_values_list = data['pixel_values']
89
  vision_hidden_states = []
 
91
  img_cnt = []
92
  for pixel_values in pixel_values_list:
93
  img_cnt.append(len(pixel_values))
94
+ all_pixel_values.extend([i.flatten(end_dim=1).permute(1, 0) for i in pixel_values]) # exist image
 
 
95
  if all_pixel_values:
96
  tgt_sizes = torch.vstack(tgt_sizes).type(torch.int32)
97
 
 
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
 
 
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_bounds'][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"]
 
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|>")
 
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 = [
 
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):
 
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
 
 
277
  image,
278
  msgs,
279
  tokenizer,
280
+ processor=None,
281
  vision_hidden_states=None,
282
  max_new_tokens=1024,
283
  sampling=True,
 
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
 
294
+ assert len(msgs) > 0, 'msgs is empty'
 
295
  assert sampling or not stream, 'if use stream mode, make sure sampling=True'
296
 
297
+ if image is not None and isinstance(msgs[0]['content'], str):
298
+ msgs[0]['content'] = '(<image>./</image>)\n' + msgs[0]['content']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  if system_prompt:
300
  sys_msg = {'role': 'system', 'content': system_prompt}
301
+ copy_msgs = [sys_msg] + copy_msgs
302
 
303
+ prompt = processor.tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
304
+ inputs = processor(prompt, [image], return_tensors="pt", max_length=max_inp_length).to(self.device)
305
 
306
  if sampling:
307
  generation_config = {
 
320
  generation_config.update(
321
  (k, kwargs[k]) for k in generation_config.keys() & kwargs.keys()
322
  )
 
323
  with torch.inference_mode():
324
+ res = self.generate(
325
+ inputs,
 
 
 
326
  tokenizer=tokenizer,
327
  max_new_tokens=max_new_tokens,
328
  vision_hidden_states=vision_hidden_states,
 
329
  stream=stream,
330
+ decode_text=True,
331
  **generation_config
332
  )
333
+
334
  if stream:
335
  def stream_gen():
336
  for text in res:
 
341
  else:
342
  answer = res[0]
343
  return answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
preprocessor_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor_type": "MiniCPMVImageProcessor",
3
+ "auto_map": {
4
+ "AutoProcessor": "processing_minicpmv.MiniCPMVProcessor",
5
+ "AutoImageProcessor": "image_processing_minicpmv.MiniCPMVImageProcessor"
6
+ },
7
+ "processor_class": "MiniCPMVProcessor",
8
+ "max_slice_nums": 9,
9
+ "scale_resolution": 448,
10
+ "patch_size": 14,
11
+ "image_feature_size": 96,
12
+ "im_start": "<image>",
13
+ "im_end": "</image>",
14
+ "slice_start": "<slice>",
15
+ "slice_end": "</slice>",
16
+ "unk": "<unk>",
17
+ "norm_mean": [0.5, 0.5, 0.5],
18
+ "norm_std": [0.5, 0.5, 0.5],
19
+ "version": 2.5
20
+ }
processing_minicpmv.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
65
+ and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
66
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
67
+ LlavaNextImageProcessor's [`~LlavaNextImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
68
+ of the above two methods for more information.
69
+
70
+ Args:
71
+ text (`str`, `List[str]`, `List[List[str]]`):
72
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
73
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
74
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
75
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
76
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
77
+ tensor. Both channels-first and channels-last formats are supported.
78
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
79
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
80
+ index) among:
81
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
82
+ sequence if provided).
83
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
84
+ acceptable input length for the model if that argument is not provided.
85
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
86
+ lengths).
87
+ max_length (`int`, *optional*):
88
+ Maximum length of the returned list and optionally padding length (see above).
89
+ do_pad (`bool`, *optional*, defaults to self.do_pad):
90
+ Whether to pad the image. If `True` will pad the images in the batch to the largest image in the batch
91
+ and create a pixel mask. Padding will be applied to the bottom and right of the image with zeros.
92
+ truncation (`bool`, *optional*):
93
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
94
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
95
+ If set, will return tensors of a particular framework. Acceptable values are:
96
+
97
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
98
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
99
+ - `'np'`: Return NumPy `np.ndarray` objects.
100
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
101
+
102
+ Returns:
103
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
104
+
105
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
106
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
107
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
108
+ `None`).
109
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
110
+ """
111
+ if images is not None:
112
+ image_inputs = self.image_processor(images, do_pad=do_pad, return_tensors=return_tensors)
113
+ return self._convert_images_texts_to_inputs(image_inputs, text, max_length=max_length)
114
+
115
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
116
+ def batch_decode(self, *args, **kwargs):
117
+ """
118
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
119
+ refer to the docstring of this method for more information.
120
+ """
121
+ output_ids = args[0]
122
+ result_text = []
123
+ for result in output_ids:
124
+ result = result[result != 0]
125
+ if result[0] == self.tokenizer.bos_id:
126
+ result = result[1:]
127
+ if result[-1] == self.tokenizer.eos_id:
128
+ result = result[:-1]
129
+ result_text.append(self.tokenizer.decode(result, *args[1:], **kwargs).strip())
130
+ return result_text
131
+ # return self.tokenizer.batch_decode(*args, **kwargs)
132
+
133
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
134
+ def decode(self, *args, **kwargs):
135
+ """
136
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
137
+ the docstring of this method for more information.
138
+ """
139
+ result = args[0]
140
+ result = result[result != 0]
141
+ if result[0] == self.tokenizer.bos_id:
142
+ result = result[1:]
143
+ if result[-1] == self.tokenizer.eos_id or (hasattr(self.tokenizer, "eot_id") and result[-1] == self.tokenizer.eot_id):
144
+ result = result[:-1]
145
+ return self.tokenizer.decode(result, *args[1:], **kwargs).strip()
146
+
147
+ def _convert(
148
+ self, input_str, max_inp_length: Optional[int] = None
149
+ ):
150
+ if self.version == 2.5 or self.tokenizer.add_bos_token:
151
+ input_ids = self.tokenizer.encode(input_str)
152
+ else:
153
+ input_ids = [self.tokenizer.bos_id] + self.tokenizer.encode(input_str)
154
+ if max_inp_length is not None:
155
+ input_ids = input_ids[:max_inp_length]
156
+ input_ids = torch.tensor(input_ids, dtype=torch.int32)
157
+
158
+ image_start_tokens = torch.where(input_ids == self.tokenizer.im_start_id)[0]
159
+ image_start_tokens += 1
160
+ image_end_tokens = torch.where(input_ids == self.tokenizer.im_end_id)[0]
161
+ valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
162
+ image_bounds = torch.hstack(
163
+ [
164
+ image_start_tokens[:valid_image_nums].unsqueeze(-1),
165
+ image_end_tokens[:valid_image_nums].unsqueeze(-1),
166
+ ]
167
+ )
168
+ return input_ids.unsqueeze(0), image_bounds
169
+
170
+ def _convert_images_texts_to_inputs(self, images, texts, do_pad=False, truncation=None, max_length=None, return_tensors=None):
171
+ if not len(images):
172
+ model_inputs = self.tokenizer(texts, return_tensors=return_tensors, padding=do_pad, truncation=truncation, max_length=max_length)
173
+ return MiniCPMVBatchFeature(data={**model_inputs})
174
+
175
+ pattern = "(<image>./</image>)"
176
+ images, image_sizes, tgt_sizes = images["pixel_values"], images["image_sizes"], images["tgt_sizes"]
177
+
178
+ image_tags = re.findall(pattern, texts)
179
+ assert len(image_tags) == len(image_sizes)
180
+ text_chunks = texts.split(pattern)
181
+ final_texts = ""
182
+ for i in range(len(image_tags)):
183
+ final_texts = final_texts + text_chunks[i] + self.image_processor.get_slice_image_placeholder(image_sizes[i])
184
+ final_texts += text_chunks[-1]
185
+ input_ids, image_bounds = self._convert(final_texts, max_length)
186
+ return MiniCPMVBatchFeature(data={
187
+ "input_ids": input_ids,
188
+ "pixel_values": [images],
189
+ "image_sizes": [image_sizes],
190
+ "image_bounds": [image_bounds],
191
+ "tgt_sizes": [tgt_sizes]
192
+ })
193
+
194
+ @property
195
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
196
+ def model_input_names(self):
197
+ tokenizer_input_names = self.tokenizer.model_input_names
198
+ image_processor_input_names = self.image_processor.model_input_names
199
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
200
+
201
+
202
+ def pad(self, orig_items, key, max_length=None, padding_value=0, padding_side="left"):
203
+ items = []
204
+ if isinstance(orig_items[0][key], list):
205
+ assert isinstance(orig_items[0][key][0], torch.Tensor)
206
+ for it in orig_items:
207
+ for tr in it[key]:
208
+ items.append({key: tr})
209
+ else:
210
+ assert isinstance(orig_items[0][key], torch.Tensor)
211
+ items = orig_items
212
+
213
+ batch_size = len(items)
214
+ shape = items[0][key].shape
215
+ dim = len(shape)
216
+ assert dim <= 3
217
+ if max_length is None:
218
+ max_length = 0
219
+ max_length = max(max_length, max(item[key].shape[-1] for item in items))
220
+ min_length = min(item[key].shape[-1] for item in items)
221
+ dtype = items[0][key].dtype
222
+
223
+ if dim == 1:
224
+ return torch.cat([item[key] for item in items], dim=0)
225
+ elif dim == 2:
226
+ if max_length == min_length:
227
+ return torch.cat([item[key] for item in items], dim=0)
228
+ tensor = torch.zeros((batch_size, max_length), dtype=dtype) + padding_value
229
+ else:
230
+ tensor = (
231
+ torch.zeros((batch_size, max_length, shape[-1]), dtype=dtype)
232
+ + padding_value
233
+ )
234
+
235
+ for i, item in enumerate(items):
236
+ if dim == 2:
237
+ if padding_side == "left":
238
+ tensor[i, -len(item[key][0]) :] = item[key][0].clone()
239
+ else:
240
+ tensor[i, : len(item[key][0])] = item[key][0].clone()
241
+ elif dim == 3:
242
+ if padding_side == "left":
243
+ tensor[i, -len(item[key][0]) :, :] = item[key][0].clone()
244
+ else:
245
+ tensor[i, : len(item[key][0]), :] = item[key][0].clone()
246
+
247
+ return tensor
resampler.py CHANGED
@@ -1,17 +1,9 @@
1
  from functools import partial
2
  import numpy as np
3
- import warnings
4
- from typing import Optional, Tuple
5
  import torch
6
  from torch import nn
7
- from torch import Tensor
8
- import torch.nn.functional as F
9
- from torch.nn.functional import *
10
- from torch.nn.modules.activation import *
11
  from torch.nn.init import trunc_normal_
12
- from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
13
- from transformers import PreTrainedModel
14
- from transformers.integrations import is_deepspeed_zero3_enabled
15
 
16
  def get_2d_sincos_pos_embed(embed_dim, image_size):
17
  """
@@ -63,7 +55,7 @@ def get_1d_sincos_pos_embed_from_grid_new(embed_dim, pos):
63
  emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (H, W, D)
64
  return emb
65
 
66
-
67
  class Resampler(nn.Module):
68
  """
69
  A 2D perceiver-resampler network with one cross attention layers by
@@ -90,13 +82,14 @@ class Resampler(nn.Module):
90
  self.max_size = max_size
91
 
92
  self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
 
93
 
94
  if kv_dim is not None and kv_dim != embed_dim:
95
  self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
96
  else:
97
  self.kv_proj = nn.Identity()
98
 
99
- self.attn = MultiheadAttention(embed_dim, num_heads)
100
  self.ln_q = norm_layer(embed_dim)
101
  self.ln_kv = norm_layer(embed_dim)
102
 
@@ -104,10 +97,9 @@ class Resampler(nn.Module):
104
  self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
105
 
106
  self._set_2d_pos_cache(self.max_size)
 
107
 
108
  def _set_2d_pos_cache(self, max_size, device='cpu'):
109
- if is_deepspeed_zero3_enabled():
110
- device='cuda'
111
  pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.embed_dim, max_size)).float().to(device)
112
  self.register_buffer("pos_embed", pos_embed, persistent=False)
113
 
@@ -168,645 +160,4 @@ class Resampler(nn.Module):
168
  return x
169
 
170
  def _repeat(self, query, N: int):
171
- return query.unsqueeze(1).repeat(1, N, 1)
172
-
173
-
174
- class MultiheadAttention(nn.MultiheadAttention):
175
- def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False,
176
- add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None):
177
- super().__init__(embed_dim, num_heads, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first, device, dtype)
178
-
179
- # rewrite out_proj layer,with nn.Linear
180
- self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias, device=device, dtype=dtype)
181
-
182
- def forward(
183
- self,
184
- query: Tensor,
185
- key: Tensor,
186
- value: Tensor,
187
- key_padding_mask: Optional[Tensor] = None,
188
- need_weights: bool = True,
189
- attn_mask: Optional[Tensor] = None,
190
- average_attn_weights: bool = True,
191
- is_causal : bool = False) -> Tuple[Tensor, Optional[Tensor]]:
192
- why_not_fast_path = ''
193
- if ((attn_mask is not None and torch.is_floating_point(attn_mask))
194
- or (key_padding_mask is not None) and torch.is_floating_point(key_padding_mask)):
195
- why_not_fast_path = "floating-point masks are not supported for fast path."
196
-
197
- is_batched = query.dim() == 3
198
-
199
- key_padding_mask = F._canonical_mask(
200
- mask=key_padding_mask,
201
- mask_name="key_padding_mask",
202
- other_type=F._none_or_dtype(attn_mask),
203
- other_name="attn_mask",
204
- target_type=query.dtype
205
- )
206
-
207
- attn_mask = F._canonical_mask(
208
- mask=attn_mask,
209
- mask_name="attn_mask",
210
- other_type=None,
211
- other_name="",
212
- target_type=query.dtype,
213
- check_other=False,
214
- )
215
-
216
-
217
- if not is_batched:
218
- why_not_fast_path = f"input not batched; expected query.dim() of 3 but got {query.dim()}"
219
- elif query is not key or key is not value:
220
- # When lifting this restriction, don't forget to either
221
- # enforce that the dtypes all match or test cases where
222
- # they don't!
223
- why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
224
- elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
225
- why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
226
- elif self.in_proj_weight is None:
227
- why_not_fast_path = "in_proj_weight was None"
228
- elif query.dtype != self.in_proj_weight.dtype:
229
- # this case will fail anyway, but at least they'll get a useful error message.
230
- why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
231
- elif self.training:
232
- why_not_fast_path = "training is enabled"
233
- elif (self.num_heads % 2) != 0:
234
- why_not_fast_path = "self.num_heads is not even"
235
- elif not self.batch_first:
236
- why_not_fast_path = "batch_first was not True"
237
- elif self.bias_k is not None:
238
- why_not_fast_path = "self.bias_k was not None"
239
- elif self.bias_v is not None:
240
- why_not_fast_path = "self.bias_v was not None"
241
- elif self.add_zero_attn:
242
- why_not_fast_path = "add_zero_attn was enabled"
243
- elif not self._qkv_same_embed_dim:
244
- why_not_fast_path = "_qkv_same_embed_dim was not True"
245
- elif query.is_nested and (key_padding_mask is not None or attn_mask is not None):
246
- why_not_fast_path = "supplying both src_key_padding_mask and src_mask at the same time \
247
- is not supported with NestedTensor input"
248
- elif torch.is_autocast_enabled():
249
- why_not_fast_path = "autocast is enabled"
250
-
251
- if not why_not_fast_path:
252
- tensor_args = (
253
- query,
254
- key,
255
- value,
256
- self.in_proj_weight,
257
- self.in_proj_bias,
258
- self.out_proj.weight,
259
- self.out_proj.bias,
260
- )
261
- # We have to use list comprehensions below because TorchScript does not support
262
- # generator expressions.
263
- if torch.overrides.has_torch_function(tensor_args):
264
- why_not_fast_path = "some Tensor argument has_torch_function"
265
- elif _is_make_fx_tracing():
266
- why_not_fast_path = "we are running make_fx tracing"
267
- elif not all(_check_arg_device(x) for x in tensor_args):
268
- why_not_fast_path = ("some Tensor argument's device is neither one of "
269
- f"cpu, cuda or {torch.utils.backend_registration._privateuse1_backend_name}")
270
- elif torch.is_grad_enabled() and any(_arg_requires_grad(x) for x in tensor_args):
271
- why_not_fast_path = ("grad is enabled and at least one of query or the "
272
- "input/output projection weights or biases requires_grad")
273
- if not why_not_fast_path:
274
- merged_mask, mask_type = self.merge_masks(attn_mask, key_padding_mask, query)
275
-
276
- if self.in_proj_bias is not None and self.in_proj_weight is not None:
277
- return torch._native_multi_head_attention(
278
- query,
279
- key,
280
- value,
281
- self.embed_dim,
282
- self.num_heads,
283
- self.in_proj_weight,
284
- self.in_proj_bias,
285
- self.out_proj.weight,
286
- self.out_proj.bias,
287
- merged_mask,
288
- need_weights,
289
- average_attn_weights,
290
- mask_type)
291
-
292
- any_nested = query.is_nested or key.is_nested or value.is_nested
293
- assert not any_nested, ("MultiheadAttention does not support NestedTensor outside of its fast path. " +
294
- f"The fast path was not hit because {why_not_fast_path}")
295
-
296
- if self.batch_first and is_batched:
297
- # make sure that the transpose op does not affect the "is" property
298
- if key is value:
299
- if query is key:
300
- query = key = value = query.transpose(1, 0)
301
- else:
302
- query, key = (x.transpose(1, 0) for x in (query, key))
303
- value = key
304
- else:
305
- query, key, value = (x.transpose(1, 0) for x in (query, key, value))
306
-
307
- if not self._qkv_same_embed_dim:
308
- attn_output, attn_output_weights = self.multi_head_attention_forward(
309
- query, key, value, self.embed_dim, self.num_heads,
310
- self.in_proj_weight, self.in_proj_bias,
311
- self.bias_k, self.bias_v, self.add_zero_attn,
312
- self.dropout, self.out_proj.weight, self.out_proj.bias,
313
- training=self.training,
314
- key_padding_mask=key_padding_mask, need_weights=need_weights,
315
- attn_mask=attn_mask,
316
- use_separate_proj_weight=True,
317
- q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight,
318
- v_proj_weight=self.v_proj_weight,
319
- average_attn_weights=average_attn_weights,
320
- is_causal=is_causal)
321
- else:
322
- attn_output, attn_output_weights = self.multi_head_attention_forward(
323
- query, key, value, self.embed_dim, self.num_heads,
324
- self.in_proj_weight, self.in_proj_bias,
325
- self.bias_k, self.bias_v, self.add_zero_attn,
326
- self.dropout, self.out_proj.weight, self.out_proj.bias,
327
- training=self.training,
328
- key_padding_mask=key_padding_mask,
329
- need_weights=need_weights,
330
- attn_mask=attn_mask,
331
- average_attn_weights=average_attn_weights,
332
- is_causal=is_causal)
333
- if self.batch_first and is_batched:
334
- return attn_output.transpose(1, 0), attn_output_weights
335
- else:
336
- return attn_output, attn_output_weights
337
-
338
- def multi_head_attention_forward(
339
- self,
340
- query: Tensor,
341
- key: Tensor,
342
- value: Tensor,
343
- embed_dim_to_check: int,
344
- num_heads: int,
345
- in_proj_weight: Optional[Tensor],
346
- in_proj_bias: Optional[Tensor],
347
- bias_k: Optional[Tensor],
348
- bias_v: Optional[Tensor],
349
- add_zero_attn: bool,
350
- dropout_p: float,
351
- out_proj_weight: Tensor,
352
- out_proj_bias: Optional[Tensor],
353
- training: bool = True,
354
- key_padding_mask: Optional[Tensor] = None,
355
- need_weights: bool = True,
356
- attn_mask: Optional[Tensor] = None,
357
- use_separate_proj_weight: bool = False,
358
- q_proj_weight: Optional[Tensor] = None,
359
- k_proj_weight: Optional[Tensor] = None,
360
- v_proj_weight: Optional[Tensor] = None,
361
- static_k: Optional[Tensor] = None,
362
- static_v: Optional[Tensor] = None,
363
- average_attn_weights: bool = True,
364
- is_causal: bool = False,
365
- ) -> Tuple[Tensor, Optional[Tensor]]:
366
- tens_ops = (query, key, value, in_proj_weight, in_proj_bias, bias_k, bias_v, out_proj_weight, out_proj_bias)
367
- if has_torch_function(tens_ops):
368
- return handle_torch_function(
369
- multi_head_attention_forward,
370
- tens_ops,
371
- query,
372
- key,
373
- value,
374
- embed_dim_to_check,
375
- num_heads,
376
- in_proj_weight,
377
- in_proj_bias,
378
- bias_k,
379
- bias_v,
380
- add_zero_attn,
381
- dropout_p,
382
- out_proj_weight,
383
- out_proj_bias,
384
- training=training,
385
- key_padding_mask=key_padding_mask,
386
- need_weights=need_weights,
387
- attn_mask=attn_mask,
388
- is_causal=is_causal,
389
- use_separate_proj_weight=use_separate_proj_weight,
390
- q_proj_weight=q_proj_weight,
391
- k_proj_weight=k_proj_weight,
392
- v_proj_weight=v_proj_weight,
393
- static_k=static_k,
394
- static_v=static_v,
395
- average_attn_weights=average_attn_weights,
396
- )
397
-
398
- is_batched = _mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
399
-
400
- # For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
401
- # is batched, run the computation and before returning squeeze the
402
- # batch dimension so that the output doesn't carry this temporary batch dimension.
403
- if not is_batched:
404
- # unsqueeze if the input is unbatched
405
- query = query.unsqueeze(1)
406
- key = key.unsqueeze(1)
407
- value = value.unsqueeze(1)
408
- if key_padding_mask is not None:
409
- key_padding_mask = key_padding_mask.unsqueeze(0)
410
-
411
- # set up shape vars
412
- tgt_len, bsz, embed_dim = query.shape
413
- src_len, _, _ = key.shape
414
-
415
- key_padding_mask = _canonical_mask(
416
- mask=key_padding_mask,
417
- mask_name="key_padding_mask",
418
- other_type=_none_or_dtype(attn_mask),
419
- other_name="attn_mask",
420
- target_type=query.dtype
421
- )
422
-
423
- if is_causal and attn_mask is None:
424
- raise RuntimeError(
425
- "Need attn_mask if specifying the is_causal hint. "
426
- "You may use the Transformer module method "
427
- "`generate_square_subsequent_mask` to create this mask."
428
- )
429
-
430
- if is_causal and key_padding_mask is None and not need_weights:
431
- # when we have a kpm or need weights, we need attn_mask
432
- # Otherwise, we use the is_causal hint go as is_causal
433
- # indicator to SDPA.
434
- attn_mask = None
435
- else:
436
- attn_mask = _canonical_mask(
437
- mask=attn_mask,
438
- mask_name="attn_mask",
439
- other_type=None,
440
- other_name="",
441
- target_type=query.dtype,
442
- check_other=False,
443
- )
444
-
445
- if key_padding_mask is not None:
446
- # We have the attn_mask, and use that to merge kpm into it.
447
- # Turn off use of is_causal hint, as the merged mask is no
448
- # longer causal.
449
- is_causal = False
450
-
451
- assert embed_dim == embed_dim_to_check, \
452
- f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
453
- if isinstance(embed_dim, torch.Tensor):
454
- # embed_dim can be a tensor when JIT tracing
455
- head_dim = embed_dim.div(num_heads, rounding_mode='trunc')
456
- else:
457
- head_dim = embed_dim // num_heads
458
- assert head_dim * num_heads == embed_dim, f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
459
- if use_separate_proj_weight:
460
- # allow MHA to have different embedding dimensions when separate projection weights are used
461
- assert key.shape[:2] == value.shape[:2], \
462
- f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
463
- else:
464
- assert key.shape == value.shape, f"key shape {key.shape} does not match value shape {value.shape}"
465
-
466
- #
467
- # compute in-projection
468
- #
469
- if not use_separate_proj_weight:
470
- assert in_proj_weight is not None, "use_separate_proj_weight is False but in_proj_weight is None"
471
- q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
472
- else:
473
- assert q_proj_weight is not None, "use_separate_proj_weight is True but q_proj_weight is None"
474
- assert k_proj_weight is not None, "use_separate_proj_weight is True but k_proj_weight is None"
475
- assert v_proj_weight is not None, "use_separate_proj_weight is True but v_proj_weight is None"
476
- if in_proj_bias is None:
477
- b_q = b_k = b_v = None
478
- else:
479
- b_q, b_k, b_v = in_proj_bias.chunk(3)
480
- q, k, v = _in_projection(query, key, value, q_proj_weight, k_proj_weight, v_proj_weight, b_q, b_k, b_v)
481
-
482
- # prep attention mask
483
-
484
- if attn_mask is not None:
485
- # ensure attn_mask's dim is 3
486
- if attn_mask.dim() == 2:
487
- correct_2d_size = (tgt_len, src_len)
488
- if attn_mask.shape != correct_2d_size:
489
- raise RuntimeError(f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}.")
490
- attn_mask = attn_mask.unsqueeze(0)
491
- elif attn_mask.dim() == 3:
492
- correct_3d_size = (bsz * num_heads, tgt_len, src_len)
493
- if attn_mask.shape != correct_3d_size:
494
- raise RuntimeError(f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}.")
495
- else:
496
- raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
497
-
498
- # add bias along batch dimension (currently second)
499
- if bias_k is not None and bias_v is not None:
500
- assert static_k is None, "bias cannot be added to static key."
501
- assert static_v is None, "bias cannot be added to static value."
502
- k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
503
- v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
504
- if attn_mask is not None:
505
- attn_mask = pad(attn_mask, (0, 1))
506
- if key_padding_mask is not None:
507
- key_padding_mask = pad(key_padding_mask, (0, 1))
508
- else:
509
- assert bias_k is None
510
- assert bias_v is None
511
-
512
- #
513
- # reshape q, k, v for multihead attention and make em batch first
514
- #
515
- q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
516
- if static_k is None:
517
- k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
518
- else:
519
- # TODO finish disentangling control flow so we don't do in-projections when statics are passed
520
- assert static_k.size(0) == bsz * num_heads, \
521
- f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
522
- assert static_k.size(2) == head_dim, \
523
- f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
524
- k = static_k
525
- if static_v is None:
526
- v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
527
- else:
528
- # TODO finish disentangling control flow so we don't do in-projections when statics are passed
529
- assert static_v.size(0) == bsz * num_heads, \
530
- f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
531
- assert static_v.size(2) == head_dim, \
532
- f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
533
- v = static_v
534
-
535
- # add zero attention along batch dimension (now first)
536
- if add_zero_attn:
537
- zero_attn_shape = (bsz * num_heads, 1, head_dim)
538
- k = torch.cat([k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1)
539
- v = torch.cat([v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1)
540
- if attn_mask is not None:
541
- attn_mask = pad(attn_mask, (0, 1))
542
- if key_padding_mask is not None:
543
- key_padding_mask = pad(key_padding_mask, (0, 1))
544
-
545
- # update source sequence length after adjustments
546
- src_len = k.size(1)
547
-
548
- # merge key padding and attention masks
549
- if key_padding_mask is not None:
550
- assert key_padding_mask.shape == (bsz, src_len), \
551
- f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
552
- key_padding_mask = key_padding_mask.view(bsz, 1, 1, src_len). \
553
- expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
554
- if attn_mask is None:
555
- attn_mask = key_padding_mask
556
- else:
557
- attn_mask = attn_mask + key_padding_mask
558
-
559
- # adjust dropout probability
560
- if not training:
561
- dropout_p = 0.0
562
-
563
- #
564
- # (deep breath) calculate attention and out projection
565
- #
566
-
567
- if need_weights:
568
- B, Nt, E = q.shape
569
- q_scaled = q / math.sqrt(E)
570
-
571
- assert not (is_causal and attn_mask is None), "FIXME: is_causal not implemented for need_weights"
572
-
573
- if attn_mask is not None:
574
- attn_output_weights = torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1))
575
- else:
576
- attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
577
- attn_output_weights = softmax(attn_output_weights, dim=-1)
578
- if dropout_p > 0.0:
579
- attn_output_weights = dropout(attn_output_weights, p=dropout_p)
580
-
581
- attn_output = torch.bmm(attn_output_weights, v)
582
-
583
- attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
584
- attn_output = self.out_proj(attn_output)
585
- attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
586
-
587
- # optionally average attention weights over heads
588
- attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
589
- if average_attn_weights:
590
- attn_output_weights = attn_output_weights.mean(dim=1)
591
-
592
- if not is_batched:
593
- # squeeze the output if input was unbatched
594
- attn_output = attn_output.squeeze(1)
595
- attn_output_weights = attn_output_weights.squeeze(0)
596
- return attn_output, attn_output_weights
597
- else:
598
- # attn_mask can be either (L,S) or (N*num_heads, L, S)
599
- # if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
600
- # in order to match the input for SDPA of (N, num_heads, L, S)
601
- if attn_mask is not None:
602
- if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
603
- attn_mask = attn_mask.unsqueeze(0)
604
- else:
605
- attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
606
-
607
- q = q.view(bsz, num_heads, tgt_len, head_dim)
608
- k = k.view(bsz, num_heads, src_len, head_dim)
609
- v = v.view(bsz, num_heads, src_len, head_dim)
610
-
611
- attn_output = F.scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
612
- attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
613
-
614
- attn_output = self.out_proj(attn_output)
615
- attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
616
- if not is_batched:
617
- # squeeze the output if input was unbatched
618
- attn_output = attn_output.squeeze(1)
619
- return attn_output, None
620
-
621
-
622
- def _mha_shape_check(query: Tensor, key: Tensor, value: Tensor,
623
- key_padding_mask: Optional[Tensor], attn_mask: Optional[Tensor], num_heads: int):
624
- # Verifies the expected shape for `query, `key`, `value`, `key_padding_mask` and `attn_mask`
625
- # and returns if the input is batched or not.
626
- # Raises an error if `query` is not 2-D (unbatched) or 3-D (batched) tensor.
627
-
628
- # Shape check.
629
- if query.dim() == 3:
630
- # Batched Inputs
631
- is_batched = True
632
- assert key.dim() == 3 and value.dim() == 3, \
633
- ("For batched (3-D) `query`, expected `key` and `value` to be 3-D"
634
- f" but found {key.dim()}-D and {value.dim()}-D tensors respectively")
635
- if key_padding_mask is not None:
636
- assert key_padding_mask.dim() == 2, \
637
- ("For batched (3-D) `query`, expected `key_padding_mask` to be `None` or 2-D"
638
- f" but found {key_padding_mask.dim()}-D tensor instead")
639
- if attn_mask is not None:
640
- assert attn_mask.dim() in (2, 3), \
641
- ("For batched (3-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
642
- f" but found {attn_mask.dim()}-D tensor instead")
643
- elif query.dim() == 2:
644
- # Unbatched Inputs
645
- is_batched = False
646
- assert key.dim() == 2 and value.dim() == 2, \
647
- ("For unbatched (2-D) `query`, expected `key` and `value` to be 2-D"
648
- f" but found {key.dim()}-D and {value.dim()}-D tensors respectively")
649
-
650
- if key_padding_mask is not None:
651
- assert key_padding_mask.dim() == 1, \
652
- ("For unbatched (2-D) `query`, expected `key_padding_mask` to be `None` or 1-D"
653
- f" but found {key_padding_mask.dim()}-D tensor instead")
654
-
655
- if attn_mask is not None:
656
- assert attn_mask.dim() in (2, 3), \
657
- ("For unbatched (2-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
658
- f" but found {attn_mask.dim()}-D tensor instead")
659
- if attn_mask.dim() == 3:
660
- expected_shape = (num_heads, query.shape[0], key.shape[0])
661
- assert attn_mask.shape == expected_shape, \
662
- (f"Expected `attn_mask` shape to be {expected_shape} but got {attn_mask.shape}")
663
- else:
664
- raise AssertionError(
665
- f"query should be unbatched 2D or batched 3D tensor but received {query.dim()}-D query tensor")
666
-
667
- return is_batched
668
-
669
-
670
- def _canonical_mask(
671
- mask: Optional[Tensor],
672
- mask_name: str,
673
- other_type: Optional[DType],
674
- other_name: str,
675
- target_type: DType,
676
- check_other: bool = True,
677
- ) -> Optional[Tensor]:
678
-
679
- if mask is not None:
680
- _mask_dtype = mask.dtype
681
- _mask_is_float = torch.is_floating_point(mask)
682
- if _mask_dtype != torch.bool and not _mask_is_float:
683
- raise AssertionError(
684
- f"only bool and floating types of {mask_name} are supported")
685
- if check_other and other_type is not None:
686
- if _mask_dtype != other_type:
687
- warnings.warn(
688
- f"Support for mismatched {mask_name} and {other_name} "
689
- "is deprecated. Use same type for both instead."
690
- )
691
- if not _mask_is_float:
692
- mask = (
693
- torch.zeros_like(mask, dtype=target_type)
694
- .masked_fill_(mask, float("-inf"))
695
- )
696
- return mask
697
-
698
-
699
- def _none_or_dtype(input: Optional[Tensor]) -> Optional[DType]:
700
- if input is None:
701
- return None
702
- elif isinstance(input, torch.Tensor):
703
- return input.dtype
704
- raise RuntimeError("input to _none_or_dtype() must be None or torch.Tensor")
705
-
706
- def _in_projection_packed(
707
- q: Tensor,
708
- k: Tensor,
709
- v: Tensor,
710
- w: Tensor,
711
- b: Optional[Tensor] = None,
712
- ) -> List[Tensor]:
713
- r"""
714
- Performs the in-projection step of the attention operation, using packed weights.
715
- Output is a triple containing projection tensors for query, key and value.
716
- Args:
717
- q, k, v: query, key and value tensors to be projected. For self-attention,
718
- these are typically the same tensor; for encoder-decoder attention,
719
- k and v are typically the same tensor. (We take advantage of these
720
- identities for performance if they are present.) Regardless, q, k and v
721
- must share a common embedding dimension; otherwise their shapes may vary.
722
- w: projection weights for q, k and v, packed into a single tensor. Weights
723
- are packed along dimension 0, in q, k, v order.
724
- b: optional projection biases for q, k and v, packed into a single tensor
725
- in q, k, v order.
726
- Shape:
727
- Inputs:
728
- - q: :math:`(..., E)` where E is the embedding dimension
729
- - k: :math:`(..., E)` where E is the embedding dimension
730
- - v: :math:`(..., E)` where E is the embedding dimension
731
- - w: :math:`(E * 3, E)` where E is the embedding dimension
732
- - b: :math:`E * 3` where E is the embedding dimension
733
- Output:
734
- - in output list :math:`[q', k', v']`, each output tensor will have the
735
- same shape as the corresponding input tensor.
736
- """
737
- E = q.size(-1)
738
- if k is v:
739
- if q is k:
740
- # self-attention
741
- proj = linear(q, w, b)
742
- # reshape to 3, E and not E, 3 is deliberate for better memory coalescing and keeping same order as chunk()
743
- proj = proj.unflatten(-1, (3, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
744
- return proj[0], proj[1], proj[2]
745
- else:
746
- # encoder-decoder attention
747
- w_q, w_kv = w.split([E, E * 2])
748
- if b is None:
749
- b_q = b_kv = None
750
- else:
751
- b_q, b_kv = b.split([E, E * 2])
752
- q_proj = linear(q, w_q, b_q)
753
- kv_proj = linear(k, w_kv, b_kv)
754
- # reshape to 2, E and not E, 2 is deliberate for better memory coalescing and keeping same order as chunk()
755
- kv_proj = kv_proj.unflatten(-1, (2, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
756
- return (q_proj, kv_proj[0], kv_proj[1])
757
- else:
758
- w_q, w_k, w_v = w.chunk(3)
759
- if b is None:
760
- b_q = b_k = b_v = None
761
- else:
762
- b_q, b_k, b_v = b.chunk(3)
763
- return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
764
-
765
-
766
- def _in_projection(
767
- q: Tensor,
768
- k: Tensor,
769
- v: Tensor,
770
- w_q: Tensor,
771
- w_k: Tensor,
772
- w_v: Tensor,
773
- b_q: Optional[Tensor] = None,
774
- b_k: Optional[Tensor] = None,
775
- b_v: Optional[Tensor] = None,
776
- ) -> Tuple[Tensor, Tensor, Tensor]:
777
- r"""
778
- Performs the in-projection step of the attention operation. This is simply
779
- a triple of linear projections, with shape constraints on the weights which
780
- ensure embedding dimension uniformity in the projected outputs.
781
- Output is a triple containing projection tensors for query, key and value.
782
- Args:
783
- q, k, v: query, key and value tensors to be projected.
784
- w_q, w_k, w_v: weights for q, k and v, respectively.
785
- b_q, b_k, b_v: optional biases for q, k and v, respectively.
786
- Shape:
787
- Inputs:
788
- - q: :math:`(Qdims..., Eq)` where Eq is the query embedding dimension and Qdims are any
789
- number of leading dimensions.
790
- - k: :math:`(Kdims..., Ek)` where Ek is the key embedding dimension and Kdims are any
791
- number of leading dimensions.
792
- - v: :math:`(Vdims..., Ev)` where Ev is the value embedding dimension and Vdims are any
793
- number of leading dimensions.
794
- - w_q: :math:`(Eq, Eq)`
795
- - w_k: :math:`(Eq, Ek)`
796
- - w_v: :math:`(Eq, Ev)`
797
- - b_q: :math:`(Eq)`
798
- - b_k: :math:`(Eq)`
799
- - b_v: :math:`(Eq)`
800
- Output: in output triple :math:`(q', k', v')`,
801
- - q': :math:`[Qdims..., Eq]`
802
- - k': :math:`[Kdims..., Eq]`
803
- - v': :math:`[Vdims..., Eq]`
804
- """
805
- Eq, Ek, Ev = q.size(-1), k.size(-1), v.size(-1)
806
- assert w_q.shape == (Eq, Eq), f"expecting query weights shape of {(Eq, Eq)}, but got {w_q.shape}"
807
- assert w_k.shape == (Eq, Ek), f"expecting key weights shape of {(Eq, Ek)}, but got {w_k.shape}"
808
- assert w_v.shape == (Eq, Ev), f"expecting value weights shape of {(Eq, Ev)}, but got {w_v.shape}"
809
- assert b_q is None or b_q.shape == (Eq,), f"expecting query bias shape of {(Eq,)}, but got {b_q.shape}"
810
- assert b_k is None or b_k.shape == (Eq,), f"expecting key bias shape of {(Eq,)}, but got {b_k.shape}"
811
- assert b_v is None or b_v.shape == (Eq,), f"expecting value bias shape of {(Eq,)}, but got {b_v.shape}"
812
- return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
 
1
  from functools import partial
2
  import numpy as np
3
+
 
4
  import torch
5
  from torch import nn
 
 
 
 
6
  from torch.nn.init import trunc_normal_
 
 
 
7
 
8
  def get_2d_sincos_pos_embed(embed_dim, image_size):
9
  """
 
55
  emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (H, W, D)
56
  return emb
57
 
58
+
59
  class Resampler(nn.Module):
60
  """
61
  A 2D perceiver-resampler network with one cross attention layers by
 
82
  self.max_size = max_size
83
 
84
  self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
85
+ trunc_normal_(self.query, std=.02)
86
 
87
  if kv_dim is not None and kv_dim != embed_dim:
88
  self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
89
  else:
90
  self.kv_proj = nn.Identity()
91
 
92
+ self.attn = nn.MultiheadAttention(embed_dim, num_heads)
93
  self.ln_q = norm_layer(embed_dim)
94
  self.ln_kv = norm_layer(embed_dim)
95
 
 
97
  self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
98
 
99
  self._set_2d_pos_cache(self.max_size)
100
+ self.apply(self._init_weights)
101
 
102
  def _set_2d_pos_cache(self, max_size, device='cpu'):
 
 
103
  pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.embed_dim, max_size)).float().to(device)
104
  self.register_buffer("pos_embed", pos_embed, persistent=False)
105
 
 
160
  return x
161
 
162
  def _repeat(self, query, N: int):
163
+ return query.unsqueeze(1).repeat(1, N, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
tokenizer_config.json CHANGED
@@ -2051,7 +2051,7 @@
2051
  },
2052
  "auto_map": {
2053
  "AutoTokenizer": [
2054
- "modeling_minicpmv.PreTrainedTokenizerFastWrapper",
2055
  null
2056
  ]
2057
  },
@@ -2063,10 +2063,10 @@
2063
  "input_ids",
2064
  "attention_mask"
2065
  ],
2066
- "model_max_length": 1000000000000000019884624838656,
2067
  "pad_token": "!",
2068
  "padding_side": "right",
2069
- "tokenizer_class": "PreTrainedTokenizerFastWrapper",
2070
  "truncation_side": "right",
2071
  "unk_token": "<unk>"
2072
  }
 
2051
  },
2052
  "auto_map": {
2053
  "AutoTokenizer": [
2054
+ "tokenization_minicpmv_fast.MiniCPMVTokenizerFast",
2055
  null
2056
  ]
2057
  },
 
2063
  "input_ids",
2064
  "attention_mask"
2065
  ],
2066
+ "model_max_length": 2048,
2067
  "pad_token": "!",
2068
  "padding_side": "right",
2069
+ "tokenizer_class": "MiniCPMVTokenizerFast",
2070
  "truncation_side": "right",
2071
  "unk_token": "<unk>"
2072
  }