tc-mb commited on
Commit
1426671
·
1 Parent(s): 15743f7

Initial commit: MiniCPM-V-4_5 model

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.json filter=lfs diff=lfs merge=lfs -text
37
+ *.gguf filter=lfs diff=lfs merge=lfs -text
38
+ *.txt filter=lfs diff=lfs merge=lfs -text
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f41288392d77dd5dd9f235bdef78a3152d41651ff56b15ebdec476e3aa1cb7f
3
+ size 2862
config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6ce6abb70fe38a373d1f379177fdcd5f098d57148216ab860ba9f378e45b394
3
+ size 1995
configuration_minicpm.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ """ MiniCPMV model configuration"""
3
+
4
+ import os
5
+ from typing import Union
6
+
7
+ from transformers.utils import logging
8
+ from transformers import Qwen3Config, PretrainedConfig
9
+ from .modeling_navit_siglip import SiglipVisionConfig
10
+
11
+ logger = logging.get_logger(__name__)
12
+
13
+
14
+ class MiniCPMVSliceConfig(PretrainedConfig):
15
+ model_type = "minicpmv"
16
+
17
+ def __init__(
18
+ self,
19
+ patch_size=14,
20
+ max_slice_nums=9,
21
+ scale_resolution=448,
22
+ **kwargs,
23
+ ):
24
+ super().__init__(**kwargs)
25
+ self.patch_size = patch_size
26
+ self.max_slice_nums = max_slice_nums
27
+ self.scale_resolution = scale_resolution
28
+
29
+ @classmethod
30
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
31
+ cls._set_token_in_kwargs(kwargs)
32
+
33
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
34
+
35
+ if config_dict.get("model_type") == "minicpmv":
36
+ config_dict = config_dict["slice_config"]
37
+
38
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
39
+ logger.warning(
40
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
41
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
42
+ )
43
+
44
+ return cls.from_dict(config_dict, **kwargs)
45
+
46
+
47
+
48
+ class MiniCPMVConfig(Qwen3Config):
49
+ model_type = "minicpmv"
50
+ keys_to_ignore_at_inference = ["past_key_values"]
51
+
52
+ default_vision_config = {
53
+ "hidden_size": 1152,
54
+ "image_size": 980,
55
+ "intermediate_size": 4304,
56
+ "model_type": "siglip",
57
+ "num_attention_heads": 16,
58
+ "num_hidden_layers": 27,
59
+ "patch_size": 14,
60
+ }
61
+
62
+ def __init__(
63
+ self,
64
+ use_cache=True,
65
+ query_num=64,
66
+ image_size=448,
67
+ drop_vision_last_layer=True,
68
+ batch_vision_input=True,
69
+ slice_config=None,
70
+ vision_config=None,
71
+ use_image_id=True,
72
+ vision_batch_size=16,
73
+ batch_3d_resampler=True,
74
+ **kwargs,
75
+ ):
76
+ self.use_cache = use_cache
77
+ self.query_num = query_num
78
+ self.image_size = image_size
79
+ self.drop_vision_last_layer = drop_vision_last_layer
80
+ self.batch_vision_input = batch_vision_input
81
+ self.use_image_id = use_image_id
82
+ self.vision_batch_size = vision_batch_size
83
+ self.batch_3d_resampler = batch_3d_resampler
84
+
85
+ if slice_config is None:
86
+ self.slice_config = MiniCPMVSliceConfig(max_slice_nums=1)
87
+ else:
88
+ self.slice_config = MiniCPMVSliceConfig(**slice_config)
89
+ self.slice_mode = True
90
+
91
+ # same as HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit add tgt_sizes
92
+ if vision_config is None:
93
+ self.vision_config = SiglipVisionConfig(**self.default_vision_config)
94
+ #logger.info("vision_config is None, using default vision config")
95
+ elif isinstance(vision_config, dict):
96
+ self.vision_config = SiglipVisionConfig(**vision_config)
97
+ elif isinstance(vision_config, SiglipVisionConfig):
98
+ self.vision_config = vision_config
99
+
100
+ self.patch_size = self.vision_config.patch_size
101
+
102
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4009ca3d9e615561897c0f4963bd01c26bccff50eda4b00fcf2c13cf3fcc86db
3
+ size 268
image_processing_minicpmv.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union, Dict, Any, List
2
+ from itertools import chain
3
+
4
+ import torch
5
+ import math
6
+ import PIL.Image
7
+ import PIL.ImageSequence
8
+ import numpy as np
9
+ import PIL
10
+ from PIL import Image
11
+
12
+ from transformers.utils import TensorType, requires_backends, is_torch_dtype, is_torch_device
13
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
14
+ from transformers import AutoImageProcessor
15
+ from transformers.image_transforms import to_channel_dimension_format
16
+ from transformers.image_utils import (
17
+ ImageInput,
18
+ make_list_of_images,
19
+ valid_images,
20
+ is_torch_tensor,
21
+ is_batched,
22
+ to_numpy_array,
23
+ infer_channel_dimension_format,
24
+ ChannelDimension
25
+ )
26
+
27
+
28
+ def recursive_converter(converter, value):
29
+ if isinstance(value, list):
30
+ new_value = []
31
+ for v in value:
32
+ new_value += [recursive_converter(converter, v)]
33
+ return new_value
34
+ else:
35
+ return converter(value)
36
+
37
+ def list_depth(lst):
38
+ if not isinstance(lst, list) and not isinstance(lst, np.ndarray):
39
+ return 0
40
+ # if not lst: # 空列表
41
+ # return 1
42
+ return 1 + max(list_depth(item) for item in lst)
43
+
44
+ class MiniCPMVBatchFeature(BatchFeature):
45
+ r"""
46
+ Extend from BatchFeature for supporting various image size
47
+ """
48
+ def __init__(self, data: Optional[Dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None):
49
+ super().__init__(data)
50
+ self.convert_to_tensors(tensor_type=tensor_type)
51
+
52
+ def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None):
53
+ if tensor_type is None:
54
+ return self
55
+
56
+ is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type)
57
+
58
+ def converter(value):
59
+ try:
60
+ if not is_tensor(value):
61
+ tensor = as_tensor(value)
62
+ return tensor
63
+ except: # noqa E722
64
+ if key == "overflowing_values":
65
+ raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
66
+ raise ValueError(
67
+ "Unable to create tensor, you should probably activate padding "
68
+ "with 'padding=True' to have batched tensors with the same length."
69
+ )
70
+
71
+
72
+ for key, value in self.items():
73
+ self[key] = recursive_converter(converter, value)
74
+ return self
75
+
76
+ def to(self, *args, **kwargs) -> "MiniCPMVBatchFeature":
77
+ requires_backends(self, ["torch"])
78
+ import torch
79
+
80
+ def cast_tensor(v):
81
+ # check if v is a floating point
82
+ if torch.is_floating_point(v):
83
+ # cast and send to device
84
+ return v.to(*args, **kwargs)
85
+ elif device is not None:
86
+ return v.to(device=device)
87
+ else:
88
+ return v
89
+
90
+ new_data = {}
91
+ device = kwargs.get("device")
92
+ # Check if the args are a device or a dtype
93
+ if device is None and len(args) > 0:
94
+ # device should be always the first argument
95
+ arg = args[0]
96
+ if is_torch_dtype(arg):
97
+ # The first argument is a dtype
98
+ pass
99
+ elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):
100
+ device = arg
101
+ else:
102
+ # it's something else
103
+ raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.")
104
+ # We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor`
105
+ for k, v in self.items():
106
+ new_data[k] = recursive_converter(cast_tensor, v)
107
+ self.data = new_data
108
+ return self
109
+
110
+
111
+ class MiniCPMVImageProcessor(BaseImageProcessor):
112
+ model_input_names = ["pixel_values"]
113
+
114
+ def __init__(
115
+ self,
116
+ max_slice_nums=9,
117
+ scale_resolution=448,
118
+ patch_size=14,
119
+ **kwargs):
120
+ super().__init__(**kwargs)
121
+ self.max_slice_nums = max_slice_nums
122
+ self.scale_resolution = scale_resolution
123
+ self.patch_size = patch_size
124
+ self.use_image_id = kwargs.pop("use_image_id", False)
125
+ self.image_feature_size = kwargs.pop("image_feature_size", 64)
126
+ self.im_start_token = kwargs.pop("im_start", "<image>")
127
+ self.im_end_token = kwargs.pop("im_end", "</image>")
128
+ self.slice_start_token = kwargs.pop("slice_start", "<slice>")
129
+ self.slice_end_token = kwargs.pop("slice_end", "</slice>")
130
+ self.unk_token = kwargs.pop("unk", "<unk>")
131
+ self.im_id_start = kwargs.pop("im_id_start", "<image_id>")
132
+ self.im_id_end = kwargs.pop("im_id_end", "</image_id>")
133
+ self.slice_mode = kwargs.pop("slice_mode", True)
134
+ self.mean = np.array(kwargs.pop("norm_mean", [0.5, 0.5, 0.5]))
135
+ self.std = np.array(kwargs.pop("norm_std", [0.5, 0.5, 0.5]))
136
+ self.version = kwargs.pop("version", 2.0)
137
+
138
+ def ensure_divide(self, length, patch_size):
139
+ return max(round(length / patch_size) * patch_size, patch_size)
140
+
141
+ def find_best_resize(self,
142
+ original_size,
143
+ scale_resolution,
144
+ patch_size,
145
+ allow_upscale=False):
146
+ width, height = original_size
147
+ if (width * height >
148
+ scale_resolution * scale_resolution) or allow_upscale:
149
+ r = width / height
150
+ height = int(scale_resolution / math.sqrt(r))
151
+ width = int(height * r)
152
+ best_width = self.ensure_divide(width, patch_size)
153
+ best_height = self.ensure_divide(height, patch_size)
154
+ return (best_width, best_height)
155
+
156
+ def get_refine_size(self,
157
+ original_size,
158
+ grid,
159
+ scale_resolution,
160
+ patch_size,
161
+ allow_upscale=False):
162
+ width, height = original_size
163
+ grid_x, grid_y = grid
164
+
165
+ refine_width = self.ensure_divide(width, grid_x)
166
+ refine_height = self.ensure_divide(height, grid_y)
167
+
168
+ grid_width = refine_width / grid_x
169
+ grid_height = refine_height / grid_y
170
+
171
+ best_grid_size = self.find_best_resize((grid_width, grid_height),
172
+ scale_resolution,
173
+ patch_size,
174
+ allow_upscale=allow_upscale)
175
+ refine_size = (best_grid_size[0] * grid_x, best_grid_size[1] * grid_y)
176
+ return refine_size
177
+
178
+ def split_to_patches(self, image, grid):
179
+ patches = []
180
+ width, height = image.size
181
+ grid_x = int(width / grid[0])
182
+ grid_y = int(height / grid[1])
183
+ for i in range(0, height, grid_y):
184
+ images = []
185
+ for j in range(0, width, grid_x):
186
+ box = (j, i, j + grid_x, i + grid_y)
187
+ patch = image.crop(box)
188
+ images.append(patch)
189
+ patches.append(images)
190
+ return patches
191
+
192
+ def slice_image(
193
+ self, image, max_slice_nums=9, scale_resolution=448, patch_size=14, never_split=False
194
+ ):
195
+ original_size = image.size
196
+ source_image = None
197
+ best_grid = self.get_sliced_grid(original_size, max_slice_nums, never_split)
198
+ patches = []
199
+
200
+ if best_grid is None:
201
+ # dont need to slice, upsample
202
+ best_size = self.find_best_resize(
203
+ original_size, scale_resolution, patch_size, allow_upscale=True
204
+ )
205
+ source_image = image.resize(best_size, resample=Image.Resampling.BICUBIC)
206
+ else:
207
+ # source image, down-sampling and ensure divided by patch_size
208
+ best_resize = self.find_best_resize(original_size, scale_resolution, patch_size)
209
+ source_image = image.copy().resize(best_resize, resample=Image.Resampling.BICUBIC)
210
+ refine_size = self.get_refine_size(
211
+ original_size, best_grid, scale_resolution, patch_size, allow_upscale=True
212
+ )
213
+ refine_image = image.resize(refine_size, resample=Image.Resampling.BICUBIC)
214
+ patches = self.split_to_patches(refine_image, best_grid)
215
+
216
+ return source_image, patches, best_grid
217
+
218
+ def get_grid_placeholder(self, grid):
219
+ if grid is None:
220
+ return ""
221
+ slice_image_placeholder = (
222
+ self.slice_start_token
223
+ + self.unk_token * self.image_feature_size
224
+ + self.slice_end_token
225
+ )
226
+
227
+ cols = grid[0]
228
+ rows = grid[1]
229
+ slices = []
230
+ for i in range(rows):
231
+ lines = []
232
+ for j in range(cols):
233
+ lines.append(slice_image_placeholder)
234
+ slices.append("".join(lines))
235
+
236
+ slice_placeholder = "\n".join(slices)
237
+ return slice_placeholder
238
+
239
+ def get_image_id_placeholder(self, idx=0):
240
+ return f"{self.im_id_start}{idx}{self.im_id_end}"
241
+
242
+ def get_sliced_images(self, image, max_slice_nums=None):
243
+ slice_images = []
244
+
245
+ if not self.slice_mode:
246
+ return [image]
247
+
248
+ max_slice_nums = self.max_slice_nums if max_slice_nums is None else int(max_slice_nums)
249
+ assert max_slice_nums > 0
250
+ source_image, patches, sliced_grid = self.slice_image(
251
+ image,
252
+ max_slice_nums, # default: 9
253
+ self.scale_resolution, # default: 448
254
+ self.patch_size # default: 14
255
+ )
256
+
257
+ slice_images.append(source_image)
258
+ if len(patches) > 0:
259
+ for i in range(len(patches)):
260
+ for j in range(len(patches[0])):
261
+ slice_images.append(patches[i][j])
262
+ return slice_images
263
+
264
+ def get_sliced_grid(self, image_size, max_slice_nums, nerver_split=False):
265
+ original_width, original_height = image_size
266
+ log_ratio = math.log(original_width / original_height)
267
+ ratio = original_width * original_height / (self.scale_resolution * self.scale_resolution)
268
+ multiple = min(math.ceil(ratio), max_slice_nums)
269
+ if multiple <= 1 or nerver_split:
270
+ return None
271
+ candidate_split_grids_nums = []
272
+ for i in [multiple - 1, multiple, multiple + 1]:
273
+ if i == 1 or i > max_slice_nums:
274
+ continue
275
+ candidate_split_grids_nums.append(i)
276
+
277
+ candidate_grids = []
278
+ for split_grids_nums in candidate_split_grids_nums:
279
+ m = 1
280
+ while m <= split_grids_nums:
281
+ if split_grids_nums % m == 0:
282
+ candidate_grids.append([m, split_grids_nums // m])
283
+ m += 1
284
+
285
+ best_grid = [1, 1]
286
+ min_error = float("inf")
287
+ for grid in candidate_grids:
288
+ error = abs(log_ratio - math.log(grid[0] / grid[1]))
289
+ if error < min_error:
290
+ best_grid = grid
291
+ min_error = error
292
+
293
+ return best_grid
294
+
295
+ def get_slice_image_placeholder(self, image_size, image_idx=0, max_slice_nums=None, use_image_id=None):
296
+ max_slice_nums = self.max_slice_nums if max_slice_nums is None else int(max_slice_nums)
297
+ assert max_slice_nums > 0
298
+ grid = self.get_sliced_grid(image_size=image_size, max_slice_nums=max_slice_nums)
299
+
300
+ image_placeholder = (
301
+ self.im_start_token
302
+ + self.unk_token * self.image_feature_size
303
+ + self.im_end_token
304
+ )
305
+ use_image_id = self.use_image_id if use_image_id is None else bool(use_image_id)
306
+ if use_image_id:
307
+ final_placeholder = self.get_image_id_placeholder(image_idx) + image_placeholder
308
+ else:
309
+ final_placeholder = image_placeholder
310
+
311
+ if self.slice_mode:
312
+ final_placeholder = final_placeholder + self.get_grid_placeholder(grid=grid)
313
+ return final_placeholder
314
+
315
+ def to_pil_image(self, image, rescale=None) -> PIL.Image.Image:
316
+ """
317
+ Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
318
+ needed.
319
+
320
+ Args:
321
+ image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):
322
+ The image to convert to the PIL Image format.
323
+ rescale (`bool`, *optional*):
324
+ Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will
325
+ default to `True` if the image type is a floating type, `False` otherwise.
326
+ """
327
+ if isinstance(image, PIL.Image.Image):
328
+ return image
329
+ if is_torch_tensor(image):
330
+ image = image.numpy()
331
+
332
+ if isinstance(image, np.ndarray):
333
+ if rescale is None:
334
+ # rescale default to the array being of floating type.
335
+ rescale = isinstance(image.flat[0], np.floating)
336
+ # If the channel as been moved to first dim, we put it back at the end.
337
+ if image.ndim == 3 and image.shape[0] in [1, 3]:
338
+ image = image.transpose(1, 2, 0)
339
+ if rescale:
340
+ image = image * 255
341
+ image = image.astype(np.uint8)
342
+ return PIL.Image.fromarray(image)
343
+ return image
344
+
345
+ def reshape_by_patch(self, image):
346
+ """
347
+ :param image: shape [3, H, W]
348
+ :param patch_size:
349
+ :return: [3, patch_size, HW/patch_size]
350
+ """
351
+ image = torch.from_numpy(image)
352
+ patch_size = self.patch_size
353
+ patches = torch.nn.functional.unfold(
354
+ image,
355
+ (patch_size, patch_size),
356
+ stride=(patch_size, patch_size)
357
+ )
358
+
359
+ patches = patches.reshape(image.size(0), patch_size, patch_size, -1)
360
+ patches = patches.permute(0, 1, 3, 2).reshape(image.size(0), patch_size, -1)
361
+ return patches.numpy()
362
+
363
+ def preprocess(
364
+ self,
365
+ images: Union[Image.Image, List[Image.Image], List[List[Image.Image]]],
366
+ do_pad: Optional[bool] = True, # TODO: add pad for MiniCPM-Llama3-V-2_5
367
+ max_slice_nums: int = None,
368
+ temporal_ids: Optional[Union[List[List[int]], List[List[List[int]]]]] = None,
369
+ return_tensors: Optional[Union[str, TensorType]] = None,
370
+ **kwargs
371
+ ) -> MiniCPMVBatchFeature:
372
+ if isinstance(images, Image.Image):
373
+ images_list = [[images]]
374
+ elif isinstance(images[0], Image.Image):
375
+ images_list = [images]
376
+ else:
377
+ images_list = images
378
+
379
+ if temporal_ids is not None:
380
+ if list_depth(temporal_ids) == 2:
381
+ temporal_ids = [temporal_ids]
382
+
383
+ new_images_list = []
384
+ image_sizes_list = []
385
+ tgt_sizes_list = []
386
+ temporal_ids_list = []
387
+ skip_image_idx_list = []
388
+
389
+ for batch_idx, _images in enumerate(images_list):
390
+ if _images is None or len(_images) == 0:
391
+ new_images_list.append([])
392
+ image_sizes_list.append([])
393
+ tgt_sizes_list.append([])
394
+ temporal_ids_list.append([])
395
+ skip_image_idx_list.append([])
396
+ continue
397
+ if not valid_images(_images):
398
+ raise ValueError(
399
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
400
+ "torch.Tensor, tf.Tensor or jax.ndarray."
401
+ )
402
+
403
+ _images = [self.to_pil_image(image).convert("RGB") for image in _images]
404
+ input_data_format = infer_channel_dimension_format(np.array(_images[0]))
405
+
406
+ new_images = []
407
+ image_sizes = [image.size for image in _images]
408
+ tgt_sizes = []
409
+ tp_ids = []
410
+ skip_image_idx = []
411
+
412
+ # for image in _images:
413
+ # image_patches = self.get_sliced_images(image, max_slice_nums)
414
+ # image_patches = [to_numpy_array(image).astype(np.float32) / 255 for image in image_patches]
415
+ # image_patches = [
416
+ # self.normalize(image=image, mean=self.mean, std=self.std, input_data_format=input_data_format)
417
+ # for image in image_patches
418
+ # ]
419
+ # image_patches = [
420
+ # to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=input_data_format)
421
+ # for image in image_patches
422
+ # ]
423
+ # for slice_image in image_patches:
424
+ # new_images.append(self.reshape_by_patch(slice_image))
425
+ # tgt_sizes.append(np.array((slice_image.shape[1] // self.patch_size, slice_image.shape[2] // self.patch_size)))
426
+
427
+ if temporal_ids is None:
428
+ # no temporal ids
429
+ for image in _images:
430
+ image_patches = self.get_sliced_images(image, max_slice_nums)
431
+ image_patches = [to_numpy_array(image).astype(np.float32) / 255 for image in image_patches]
432
+ image_patches = [
433
+ self.normalize(image=image, mean=self.mean, std=self.std, input_data_format=input_data_format)
434
+ for image in image_patches
435
+ ]
436
+ image_patches = [
437
+ to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=input_data_format)
438
+ for image in image_patches
439
+ ]
440
+ for slice_image in image_patches:
441
+ new_images.append(self.reshape_by_patch(slice_image))
442
+ tgt_sizes.append(np.array((slice_image.shape[1] // self.patch_size, slice_image.shape[2] // self.patch_size)))
443
+
444
+ tp_ids.extend([[-1]] * len(image_patches))
445
+ else:
446
+ temporal_ids_flatten = list(chain.from_iterable(temporal_ids[batch_idx]))
447
+ assert len(temporal_ids_flatten) == len(_images)
448
+ frame_groups = []
449
+ s = 0
450
+ for group in temporal_ids[batch_idx]:
451
+ frame_groups.append(_images[s:s+len(group)])
452
+ s += len(group)
453
+
454
+ skip_start = 0
455
+ for frame_group, tp_id in zip(frame_groups, temporal_ids[batch_idx]):
456
+ image_patches_group = []
457
+ for frame in frame_group:
458
+ image_patches = self.get_sliced_images(frame, max_slice_nums)
459
+ image_patches = [to_numpy_array(image).astype(np.float32) / 255 for image in image_patches]
460
+ image_patches = [
461
+ self.normalize(image=image, mean=self.mean, std=self.std, input_data_format=input_data_format)
462
+ for image in image_patches
463
+ ]
464
+ image_patches = [
465
+ to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=input_data_format)
466
+ for image in image_patches
467
+ ]
468
+ image_patches_group.append(image_patches)
469
+
470
+ group_cnt = len(image_patches_group[0])
471
+ for gidx in range(group_cnt):
472
+ group_images = [s[gidx] for s in image_patches_group]
473
+ tgt_sizes.extend([np.array((i.shape[1] // self.patch_size, i.shape[2] // self.patch_size)) for i in group_images])
474
+
475
+ group_images = [self.reshape_by_patch(i) for i in group_images]
476
+ new_images.extend(group_images)
477
+ tp_ids.append(tp_id)
478
+ skip_image_idx.extend(list(range(skip_start + 1, skip_start + len(frame_group))))
479
+ skip_start += len(frame_group)
480
+
481
+ if tgt_sizes:
482
+ tgt_sizes = np.vstack(tgt_sizes)
483
+
484
+ new_images_list.append(new_images)
485
+ image_sizes_list.append(image_sizes)
486
+ tgt_sizes_list.append(tgt_sizes)
487
+ temporal_ids_list.append(tp_ids)
488
+ skip_image_idx_list.append(skip_image_idx)
489
+
490
+ data = {
491
+ "pixel_values": new_images_list,
492
+ "image_sizes": image_sizes_list,
493
+ "tgt_sizes": tgt_sizes_list,
494
+ "temporal_ids": temporal_ids_list,
495
+ "skip_image_idx": skip_image_idx_list
496
+ }
497
+
498
+
499
+ return MiniCPMVBatchFeature(data=data, tensor_type=return_tensors)
500
+
501
+ AutoImageProcessor.register("MiniCPMVImageProcessor", MiniCPMVImageProcessor)
merges.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5
3
+ size 1671853
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68203167daf5465f04bad6a5ed44101179796ebbe290cdbd7d90fc5df17dd4fa
3
+ size 4827364414
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:41f448d2edb3d4e761394320026225a254ce72fe805a56a1c0928a863f8e137d
3
+ size 1699920944
model.safetensors.index.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d43232805e044e9646cf03b67e20daf0b6484ee379a29b5e4632b6f95998f05
3
+ size 267079
modeling_minicpmv.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import List, Optional
3
+ import json
4
+ import torch
5
+ import torchvision
6
+
7
+ from threading import Thread
8
+ from copy import deepcopy
9
+ from PIL import Image
10
+ from transformers import AutoProcessor, Qwen3PreTrainedModel, Qwen3ForCausalLM, TextIteratorStreamer
11
+
12
+ from .configuration_minicpm import MiniCPMVConfig
13
+ from .modeling_navit_siglip import SiglipVisionTransformer
14
+ from .resampler import Resampler
15
+
16
+
17
+
18
+ class MiniCPMVPreTrainedModel(Qwen3PreTrainedModel):
19
+ config_class = MiniCPMVConfig
20
+
21
+
22
+ class MiniCPMV(MiniCPMVPreTrainedModel):
23
+ def __init__(self, config):
24
+ super().__init__(config)
25
+ self.llm = Qwen3ForCausalLM(config)
26
+ self.vpm = self.init_vision_module()
27
+ self.vision_dim = self.vpm.embed_dim
28
+ self.embed_dim = self.llm.config.hidden_size
29
+ self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
30
+ self.processor = None
31
+
32
+ self.terminators = ['<|im_end|>', '<|endoftext|>']
33
+
34
+ def init_vision_module(self):
35
+ # same as HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit add tgt_sizes
36
+ if self.config._attn_implementation == 'flash_attention_2':
37
+ self.config.vision_config._attn_implementation = 'flash_attention_2'
38
+ else:
39
+ # not suport sdpa
40
+ self.config.vision_config._attn_implementation = 'eager'
41
+ model = SiglipVisionTransformer(self.config.vision_config)
42
+ if self.config.drop_vision_last_layer:
43
+ model.encoder.layers = model.encoder.layers[:-1]
44
+
45
+ setattr(model, 'embed_dim', model.embeddings.embed_dim)
46
+ setattr(model, 'patch_size', model.embeddings.patch_size)
47
+
48
+ return model
49
+
50
+ def init_resampler(self, embed_dim, vision_dim):
51
+ return Resampler(
52
+ num_queries=self.config.query_num,
53
+ embed_dim=embed_dim,
54
+ num_heads=embed_dim // 128,
55
+ kv_dim=vision_dim,
56
+ adaptive=True,
57
+ batch_infer=self.config.batch_3d_resampler
58
+ )
59
+
60
+ def get_input_embeddings(self):
61
+ return self.llm.get_input_embeddings()
62
+
63
+ def set_input_embeddings(self, value):
64
+ self.llm.embed_tokens = value
65
+
66
+ def get_output_embeddings(self):
67
+ return self.llm.lm_head
68
+
69
+ def set_output_embeddings(self, new_embeddings):
70
+ self.llm.lm_head = new_embeddings
71
+
72
+ def set_decoder(self, decoder):
73
+ self.llm = decoder
74
+
75
+ def get_decoder(self):
76
+ return self.llm
77
+
78
+ def get_vllm_embedding(self, data):
79
+ if 'vision_hidden_states' not in data:
80
+ dtype = self.llm.model.embed_tokens.weight.dtype
81
+ device = self.llm.model.embed_tokens.weight.device
82
+ tgt_sizes = data['tgt_sizes']
83
+ pixel_values_list = data['pixel_values']
84
+ temporal_ids = data.get('temporal_ids', None)
85
+ vision_hidden_states = []
86
+ all_pixel_values = []
87
+ img_cnt = []
88
+ all_temporal_ids = None
89
+
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
+ if temporal_ids is not None:
95
+ all_temporal_ids = []
96
+ for t in temporal_ids:
97
+ all_temporal_ids.extend(t)
98
+
99
+ # exist image
100
+ if all_pixel_values:
101
+ tgt_sizes = [tgt_size for tgt_size in tgt_sizes if isinstance(tgt_size, torch.Tensor)]
102
+ tgt_sizes = torch.vstack(tgt_sizes).type(torch.int32)
103
+
104
+ max_patches = torch.max(tgt_sizes[:, 0] * tgt_sizes[:, 1])
105
+
106
+ all_pixel_values = torch.nn.utils.rnn.pad_sequence(all_pixel_values, batch_first=True,
107
+ padding_value=0.0)
108
+ B, L, _ = all_pixel_values.shape
109
+ all_pixel_values = all_pixel_values.permute(0, 2, 1).reshape(B, 3, -1, L)
110
+
111
+ patch_attn_mask = torch.zeros((B, 1, max_patches), dtype=torch.bool, device=device)
112
+ for i in range(B):
113
+ patch_attn_mask[i, 0, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
114
+
115
+ vision_batch_size = self.config.vision_batch_size
116
+ all_pixel_values = all_pixel_values.type(dtype)
117
+ if B > vision_batch_size:
118
+ hs = []
119
+ for i in range(0, B, vision_batch_size):
120
+ start_idx = i
121
+ end_idx = i + vision_batch_size
122
+ tmp_hs = self.vpm(all_pixel_values[start_idx:end_idx], patch_attention_mask=patch_attn_mask[start_idx:end_idx], tgt_sizes=tgt_sizes[start_idx:end_idx]).last_hidden_state
123
+ hs.append(tmp_hs)
124
+ vision_embedding = torch.cat(hs, dim=0)
125
+ else:
126
+ vision_embedding = self.vpm(all_pixel_values, patch_attention_mask=patch_attn_mask, tgt_sizes=tgt_sizes).last_hidden_state
127
+ vision_embedding = self.resampler(vision_embedding, tgt_sizes, all_temporal_ids)
128
+
129
+ start = 0
130
+ for pixel_values in pixel_values_list:
131
+ img_cnt = len(pixel_values)
132
+ if img_cnt > 0:
133
+ vision_hidden_states.append(vision_embedding[start: start + img_cnt])
134
+ start += img_cnt
135
+ else:
136
+ vision_hidden_states.append([])
137
+ else: # no image
138
+ if self.training:
139
+ dummy_image = torch.zeros(
140
+ (1, 3, 224, 224),
141
+ device=device, dtype=dtype
142
+ )
143
+ tgt_sizes = torch.Tensor([[(224 // self.config.patch_size), math.ceil(224 / self.config.patch_size)]]).type(torch.int32)
144
+ dummy_feature = self.resampler(self.vpm(dummy_image).last_hidden_state, tgt_sizes)
145
+ else:
146
+ dummy_feature = []
147
+ for _ in range(len(pixel_values_list)):
148
+ vision_hidden_states.append(dummy_feature)
149
+
150
+ else:
151
+ vision_hidden_states = data['vision_hidden_states']
152
+
153
+ if hasattr(self.llm.config, 'scale_emb'):
154
+ vllm_embedding = self.llm.model.embed_tokens(data['input_ids']) * self.llm.config.scale_emb
155
+ else:
156
+ vllm_embedding = self.llm.model.embed_tokens(data['input_ids'])
157
+
158
+ vision_hidden_states = [i.type(vllm_embedding.dtype) if isinstance(
159
+ i, torch.Tensor) else i for i in vision_hidden_states]
160
+
161
+ bs = len(data['input_ids'])
162
+ device = vllm_embedding.device
163
+ embed_dim = vllm_embedding.shape[-1]
164
+
165
+ updated_vllm_embedding = torch.empty_like(vllm_embedding)
166
+
167
+ for i in range(bs):
168
+ cur_vs_hs = vision_hidden_states[i]
169
+ cur_vllm_emb = vllm_embedding[i]
170
+
171
+ if len(cur_vs_hs) == 0:
172
+ updated_vllm_embedding[i] = cur_vllm_emb
173
+ continue
174
+
175
+ cur_image_bound = data['image_bound'][i]
176
+
177
+ if len(cur_image_bound) > 0:
178
+ image_indices = torch.cat([
179
+ torch.arange(r[0], r[1], dtype=torch.long)
180
+ for r in cur_image_bound
181
+ ]).to(device)
182
+
183
+ indices_expanded = image_indices.view(-1, 1).expand(-1, embed_dim)
184
+ vision_features = cur_vs_hs.view(-1, embed_dim)
185
+
186
+ updated_emb = cur_vllm_emb.clone()
187
+ updated_emb.scatter_(0, indices_expanded, vision_features)
188
+ updated_vllm_embedding[i] = updated_emb
189
+ elif self.training:
190
+ if isinstance(cur_vs_hs, torch.Tensor) and cur_vs_hs.numel() > 0:
191
+ dummy_gradient_term = cur_vs_hs.sum() * 0.0
192
+ updated_vllm_embedding[i] = cur_vllm_emb + dummy_gradient_term
193
+ else:
194
+ updated_vllm_embedding[i] = cur_vllm_emb
195
+ else:
196
+ updated_vllm_embedding[i] = cur_vllm_emb
197
+
198
+ vllm_embedding = updated_vllm_embedding
199
+
200
+ return vllm_embedding, vision_hidden_states
201
+
202
+
203
+ def forward(self, data, **kwargs):
204
+ vllm_embedding, vision_hidden_states = self.get_vllm_embedding(data)
205
+
206
+ position_ids = data["position_ids"]
207
+ if position_ids.dtype != torch.int64:
208
+ position_ids = position_ids.long()
209
+
210
+ # compatible with llama factory
211
+ for key in ["input_ids", "inputs_embeds", "position_ids"]:
212
+ if key in kwargs:
213
+ del kwargs[key]
214
+
215
+ return self.llm(
216
+ input_ids=None,
217
+ position_ids=position_ids,
218
+ inputs_embeds=vllm_embedding,
219
+ **kwargs
220
+ )
221
+
222
+ def _decode(self, inputs_embeds, tokenizer, attention_mask, decode_text=False, **kwargs):
223
+ terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
224
+ output = self.llm.generate(
225
+ inputs_embeds=inputs_embeds,
226
+ pad_token_id=0,
227
+ eos_token_id=terminators,
228
+ attention_mask=attention_mask,
229
+ **kwargs
230
+ )
231
+ if decode_text:
232
+ return self._decode_text(output, tokenizer)
233
+ return output
234
+
235
+ def _decode_stream(self, inputs_embeds, tokenizer, **kwargs):
236
+ terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
237
+ streamer = TextIteratorStreamer(tokenizer=tokenizer)
238
+ generation_kwargs = {
239
+ 'inputs_embeds': inputs_embeds,
240
+ 'pad_token_id': 0,
241
+ 'eos_token_id': terminators,
242
+ 'streamer': streamer
243
+ }
244
+ generation_kwargs.update(kwargs)
245
+
246
+ thread = Thread(target=self.llm.generate, kwargs=generation_kwargs)
247
+ thread.start()
248
+
249
+ return streamer
250
+
251
+ def _decode_text(self, result_ids, tokenizer):
252
+ terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
253
+ result_text = []
254
+ for result in result_ids:
255
+ result = result[result != 0]
256
+ if result[0] == tokenizer.bos_id:
257
+ result = result[1:]
258
+ if result[-1] in terminators:
259
+ result = result[:-1]
260
+ result_text.append(tokenizer.decode(result).strip())
261
+ return result_text
262
+
263
+ def generate(
264
+ self,
265
+ input_ids=None,
266
+ pixel_values=None,
267
+ tgt_sizes=None,
268
+ image_bound=None,
269
+ temporal_ids=None,
270
+ attention_mask=None,
271
+ tokenizer=None,
272
+ vision_hidden_states=None,
273
+ return_vision_hidden_states=False,
274
+ stream=False,
275
+ decode_text=False,
276
+ **kwargs
277
+ ):
278
+ assert input_ids is not None
279
+ assert len(input_ids) == len(pixel_values)
280
+
281
+ model_inputs = {
282
+ "input_ids": input_ids,
283
+ "image_bound": image_bound,
284
+ "temporal_ids": temporal_ids,
285
+ }
286
+
287
+ if vision_hidden_states is None:
288
+ model_inputs["pixel_values"] = pixel_values
289
+ model_inputs['tgt_sizes'] = tgt_sizes
290
+ else:
291
+ model_inputs["vision_hidden_states"] = vision_hidden_states
292
+
293
+ with torch.inference_mode():
294
+ (
295
+ model_inputs["inputs_embeds"],
296
+ vision_hidden_states,
297
+ ) = self.get_vllm_embedding(model_inputs)
298
+
299
+ if stream:
300
+ result = self._decode_stream(model_inputs["inputs_embeds"], tokenizer, **kwargs)
301
+ else:
302
+ result = self._decode(model_inputs["inputs_embeds"], tokenizer, attention_mask, decode_text=decode_text, **kwargs)
303
+
304
+ if return_vision_hidden_states:
305
+ return result, vision_hidden_states
306
+
307
+ return result
308
+
309
+ def chat(
310
+ self,
311
+ image=None,
312
+ msgs=None,
313
+ tokenizer=None,
314
+ processor=None,
315
+ vision_hidden_states=None,
316
+ max_new_tokens=2048,
317
+ min_new_tokens=0,
318
+ sampling=True,
319
+ max_inp_length=16384,
320
+ system_prompt='',
321
+ stream=False,
322
+ max_slice_nums=None,
323
+ use_image_id=None,
324
+ temporal_ids=None,
325
+ enable_thinking=False,
326
+ **kwargs
327
+ ):
328
+ if isinstance(msgs[0], list):
329
+ batched = True
330
+ else:
331
+ batched = False
332
+ msgs_list = msgs
333
+ images_list = image
334
+
335
+ if batched is False:
336
+ images_list, msgs_list = [images_list], [msgs_list]
337
+ else:
338
+ assert images_list is None, "Please integrate image to msgs when using batch inference."
339
+ images_list = [None] * len(msgs_list)
340
+ assert len(images_list) == len(msgs_list), "The batch dim of images_list and msgs_list should be the same."
341
+
342
+ if processor is None:
343
+ if self.processor is None:
344
+ self.processor = AutoProcessor.from_pretrained(self.config._name_or_path, trust_remote_code=True)
345
+ processor = self.processor
346
+
347
+ assert self.config.query_num == processor.image_processor.image_feature_size, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
348
+ assert self.config.patch_size == processor.image_processor.patch_size, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
349
+ assert self.config.use_image_id == processor.image_processor.use_image_id, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
350
+ assert self.config.slice_config.max_slice_nums == processor.image_processor.max_slice_nums, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
351
+ assert self.config.slice_mode == processor.image_processor.slice_mode, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
352
+
353
+
354
+ prompts_lists = []
355
+ input_images_lists = []
356
+ for image, msgs in zip(images_list, msgs_list):
357
+ if isinstance(msgs, str):
358
+ msgs = json.loads(msgs)
359
+ copy_msgs = deepcopy(msgs)
360
+
361
+ assert len(msgs) > 0, "msgs is empty"
362
+ assert sampling or not stream, "if use stream mode, make sure sampling=True"
363
+
364
+ if image is not None and isinstance(copy_msgs[0]["content"], str):
365
+ copy_msgs[0]["content"] = [image, copy_msgs[0]["content"]]
366
+
367
+ images = []
368
+ for i, msg in enumerate(copy_msgs):
369
+ role = msg["role"]
370
+ content = msg["content"]
371
+ assert role in ["user", "assistant"]
372
+ if i == 0:
373
+ assert role == "user", "The role of first msg should be user"
374
+ if isinstance(content, str):
375
+ content = [content]
376
+ cur_msgs = []
377
+ for c in content:
378
+ if isinstance(c, Image.Image):
379
+ images.append(c)
380
+ cur_msgs.append("(<image>./</image>)")
381
+ elif isinstance(c, str):
382
+ cur_msgs.append(c)
383
+ msg["content"] = "\n".join(cur_msgs)
384
+
385
+ if system_prompt:
386
+ sys_msg = {'role': 'system', 'content': system_prompt}
387
+ copy_msgs = [sys_msg] + copy_msgs
388
+
389
+
390
+ prompts_lists.append(processor.tokenizer.apply_chat_template(copy_msgs, tokenize=False, add_generation_prompt=True, enable_thinking=enable_thinking))
391
+ input_images_lists.append(images)
392
+
393
+ if enable_thinking:
394
+ prefill_answer = '<think>\n'
395
+ else:
396
+ prefill_answer = ''
397
+
398
+ inputs = processor(
399
+ prompts_lists,
400
+ input_images_lists,
401
+ max_slice_nums=max_slice_nums,
402
+ use_image_id=use_image_id,
403
+ temporal_ids=temporal_ids,
404
+ return_tensors="pt",
405
+ max_length=max_inp_length
406
+ ).to(self.device)
407
+
408
+ if sampling:
409
+ generation_config = {
410
+ "temperature": 0.7,
411
+ "do_sample": True,
412
+ }
413
+ if not enable_thinking:
414
+ generation_config.update(
415
+ {
416
+ "top_p": 0.8,
417
+ "top_k": 100,
418
+ "repetition_penalty": 1.03
419
+ }
420
+ )
421
+ else:
422
+ generation_config = {
423
+ "num_beams": 3,
424
+ "repetition_penalty": 1.2,
425
+ }
426
+
427
+ if min_new_tokens > 0:
428
+ generation_config['min_new_tokens'] = min_new_tokens
429
+
430
+ generation_config.update(
431
+ (k, kwargs[k]) for k in generation_config.keys() & kwargs.keys()
432
+ )
433
+
434
+ inputs.pop("image_sizes")
435
+ with torch.inference_mode():
436
+ res = self.generate(
437
+ **inputs,
438
+ tokenizer=tokenizer,
439
+ max_new_tokens=max_new_tokens,
440
+ vision_hidden_states=vision_hidden_states,
441
+ stream=stream,
442
+ decode_text=True,
443
+ **generation_config
444
+ )
445
+
446
+ if stream:
447
+ def stream_gen():
448
+ for text in prefill_answer:
449
+ yield text
450
+ for text in res:
451
+ for term in self.terminators:
452
+ text = text.replace(term, '')
453
+ yield text
454
+ return stream_gen()
455
+
456
+ else:
457
+ if batched:
458
+ answer = [prefill_answer + i if prefill_answer else i for i in res]
459
+ else:
460
+ answer = prefill_answer + res[0] if prefill_answer else '' + res[0]
461
+ return answer
modeling_navit_siglip.py ADDED
@@ -0,0 +1,937 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google AI and The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch Siglip model. """
16
+ # Copied from HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit and add tgt_sizes
17
+
18
+
19
+ import os
20
+ import math
21
+ import warnings
22
+ from dataclasses import dataclass
23
+ from typing import Any, Optional, Tuple, Union
24
+
25
+ import numpy as np
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn.init import _calculate_fan_in_and_fan_out
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
34
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.configuration_utils import PretrainedConfig
37
+ from transformers.utils import (
38
+ ModelOutput,
39
+ add_start_docstrings,
40
+ add_start_docstrings_to_model_forward,
41
+ is_flash_attn_2_available,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from transformers.utils import logging
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ class SiglipVisionConfig(PretrainedConfig):
50
+ r"""
51
+ This is the configuration class to store the configuration of a [`SiglipVisionModel`]. It is used to instantiate a
52
+ Siglip vision encoder according to the specified arguments, defining the model architecture. Instantiating a
53
+ configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip
54
+ [google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
55
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
56
+ documentation from [`PretrainedConfig`] for more information.
57
+ Args:
58
+ hidden_size (`int`, *optional*, defaults to 768):
59
+ Dimensionality of the encoder layers and the pooler layer.
60
+ intermediate_size (`int`, *optional*, defaults to 3072):
61
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
62
+ num_hidden_layers (`int`, *optional*, defaults to 12):
63
+ Number of hidden layers in the Transformer encoder.
64
+ num_attention_heads (`int`, *optional*, defaults to 12):
65
+ Number of attention heads for each attention layer in the Transformer encoder.
66
+ num_channels (`int`, *optional*, defaults to 3):
67
+ Number of channels in the input images.
68
+ image_size (`int`, *optional*, defaults to 224):
69
+ The size (resolution) of each image.
70
+ patch_size (`int`, *optional*, defaults to 16):
71
+ The size (resolution) of each patch.
72
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
73
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
74
+ `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
75
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
76
+ The epsilon used by the layer normalization layers.
77
+ attention_dropout (`float`, *optional*, defaults to 0.0):
78
+ The dropout ratio for the attention probabilities.
79
+ Example:
80
+ ```python
81
+ >>> from transformers import SiglipVisionConfig, SiglipVisionModel
82
+ >>> # Initializing a SiglipVisionConfig with google/siglip-base-patch16-224 style configuration
83
+ >>> configuration = SiglipVisionConfig()
84
+ >>> # Initializing a SiglipVisionModel (with random weights) from the google/siglip-base-patch16-224 style configuration
85
+ >>> model = SiglipVisionModel(configuration)
86
+ >>> # Accessing the model configuration
87
+ >>> configuration = model.config
88
+ ```"""
89
+
90
+ model_type = "siglip_vision_model"
91
+
92
+ def __init__(
93
+ self,
94
+ hidden_size=768,
95
+ intermediate_size=3072,
96
+ num_hidden_layers=12,
97
+ num_attention_heads=12,
98
+ num_channels=3,
99
+ image_size=224,
100
+ patch_size=16,
101
+ hidden_act="gelu_pytorch_tanh",
102
+ layer_norm_eps=1e-6,
103
+ attention_dropout=0.0,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(**kwargs)
107
+
108
+ self.hidden_size = hidden_size
109
+ self.intermediate_size = intermediate_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.num_channels = num_channels
113
+ self.patch_size = patch_size
114
+ self.image_size = image_size
115
+ self.attention_dropout = attention_dropout
116
+ self.layer_norm_eps = layer_norm_eps
117
+ self.hidden_act = hidden_act
118
+
119
+ @classmethod
120
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
121
+ cls._set_token_in_kwargs(kwargs)
122
+
123
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
124
+
125
+ # get the vision config dict if we are loading from SiglipConfig
126
+ if config_dict.get("model_type") == "siglip":
127
+ config_dict = config_dict["vision_config"]
128
+
129
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
130
+ logger.warning(
131
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
132
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
133
+ )
134
+
135
+ return cls.from_dict(config_dict, **kwargs)
136
+
137
+
138
+ _CHECKPOINT_FOR_DOC = "google/siglip-base-patch16-224"
139
+
140
+ SIGLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
141
+ "google/siglip-base-patch16-224",
142
+ # See all SigLIP models at https://huggingface.co/models?filter=siglip
143
+ ]
144
+
145
+ if is_flash_attn_2_available():
146
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
147
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
148
+
149
+
150
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
151
+ def _get_unpad_data(attention_mask):
152
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
153
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
154
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
155
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
156
+ return (
157
+ indices,
158
+ cu_seqlens,
159
+ max_seqlen_in_batch,
160
+ )
161
+
162
+
163
+ def _trunc_normal_(tensor, mean, std, a, b):
164
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
165
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
166
+ def norm_cdf(x):
167
+ # Computes standard normal cumulative distribution function
168
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
169
+
170
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
171
+ warnings.warn(
172
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
173
+ "The distribution of values may be incorrect.",
174
+ stacklevel=2,
175
+ )
176
+
177
+ # Values are generated by using a truncated uniform distribution and
178
+ # then using the inverse CDF for the normal distribution.
179
+ # Get upper and lower cdf values
180
+ l = norm_cdf((a - mean) / std)
181
+ u = norm_cdf((b - mean) / std)
182
+
183
+ # Uniformly fill tensor with values from [l, u], then translate to
184
+ # [2l-1, 2u-1].
185
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
186
+
187
+ # Use inverse cdf transform for normal distribution to get truncated
188
+ # standard normal
189
+ if tensor.dtype in [torch.float16, torch.bfloat16]:
190
+ # The `erfinv_` op is not (yet?) defined in float16+cpu, bfloat16+gpu
191
+ og_dtype = tensor.dtype
192
+ tensor = tensor.to(torch.float32)
193
+ tensor.erfinv_()
194
+ tensor = tensor.to(og_dtype)
195
+ else:
196
+ tensor.erfinv_()
197
+
198
+ # Transform to proper mean, std
199
+ tensor.mul_(std * math.sqrt(2.0))
200
+ tensor.add_(mean)
201
+
202
+ # Clamp to ensure it's in the proper range
203
+ if tensor.dtype == torch.float16:
204
+ # The `clamp_` op is not (yet?) defined in float16+cpu
205
+ tensor = tensor.to(torch.float32)
206
+ tensor.clamp_(min=a, max=b)
207
+ tensor = tensor.to(torch.float16)
208
+ else:
209
+ tensor.clamp_(min=a, max=b)
210
+
211
+
212
+ def trunc_normal_tf_(
213
+ tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
214
+ ) -> torch.Tensor:
215
+ """Fills the input Tensor with values drawn from a truncated
216
+ normal distribution. The values are effectively drawn from the
217
+ normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
218
+ with values outside :math:`[a, b]` redrawn until they are within
219
+ the bounds. The method used for generating the random values works
220
+ best when :math:`a \\leq \text{mean} \\leq b`.
221
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
222
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
223
+ and the result is subsquently scaled and shifted by the mean and std args.
224
+ Args:
225
+ tensor: an n-dimensional `torch.Tensor`
226
+ mean: the mean of the normal distribution
227
+ std: the standard deviation of the normal distribution
228
+ a: the minimum cutoff value
229
+ b: the maximum cutoff value
230
+ """
231
+ with torch.no_grad():
232
+ _trunc_normal_(tensor, 0, 1.0, a, b)
233
+ tensor.mul_(std).add_(mean)
234
+
235
+
236
+ def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
237
+ fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
238
+ if mode == "fan_in":
239
+ denom = fan_in
240
+ elif mode == "fan_out":
241
+ denom = fan_out
242
+ elif mode == "fan_avg":
243
+ denom = (fan_in + fan_out) / 2
244
+
245
+ variance = scale / denom
246
+
247
+ if distribution == "truncated_normal":
248
+ # constant is stddev of standard normal truncated to (-2, 2)
249
+ trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
250
+ elif distribution == "normal":
251
+ with torch.no_grad():
252
+ tensor.normal_(std=math.sqrt(variance))
253
+ elif distribution == "uniform":
254
+ bound = math.sqrt(3 * variance)
255
+ with torch.no_grad():
256
+ tensor.uniform_(-bound, bound)
257
+ else:
258
+ raise ValueError(f"invalid distribution {distribution}")
259
+
260
+
261
+ def lecun_normal_(tensor):
262
+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
263
+
264
+
265
+ def default_flax_embed_init(tensor):
266
+ variance_scaling_(tensor, mode="fan_in", distribution="normal")
267
+
268
+
269
+ @dataclass
270
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
271
+ class SiglipVisionModelOutput(ModelOutput):
272
+ """
273
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
274
+ Args:
275
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
276
+ The image embeddings obtained by applying the projection layer to the pooler_output.
277
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
278
+ Sequence of hidden-states at the output of the last layer of the model.
279
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
280
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
281
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
282
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
283
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
284
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
285
+ sequence_length)`.
286
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
287
+ heads.
288
+ """
289
+
290
+ image_embeds: Optional[torch.FloatTensor] = None
291
+ last_hidden_state: torch.FloatTensor = None
292
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
293
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
294
+
295
+
296
+ class SiglipVisionEmbeddings(nn.Module):
297
+ def __init__(self, config: SiglipVisionConfig):
298
+ super().__init__()
299
+ self.config = config
300
+ self.embed_dim = config.hidden_size
301
+ self.image_size = config.image_size
302
+ self.patch_size = config.patch_size
303
+
304
+ self.patch_embedding = nn.Conv2d(
305
+ in_channels=config.num_channels,
306
+ out_channels=self.embed_dim,
307
+ kernel_size=self.patch_size,
308
+ stride=self.patch_size,
309
+ padding="valid",
310
+ )
311
+
312
+ self.num_patches_per_side = self.image_size // self.patch_size
313
+ self.num_patches = self.num_patches_per_side**2
314
+ self.num_positions = self.num_patches
315
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
316
+
317
+ def forward(self, pixel_values: torch.FloatTensor, patch_attention_mask: torch.BoolTensor, tgt_sizes: Optional[torch.IntTensor]=None) -> torch.Tensor:
318
+ batch_size = pixel_values.size(0)
319
+
320
+ patch_embeds = self.patch_embedding(pixel_values)
321
+ embeddings = patch_embeds.flatten(2).transpose(1, 2)
322
+
323
+ max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3)
324
+ max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size
325
+ boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side)
326
+ position_ids = torch.full(
327
+ size=(
328
+ batch_size,
329
+ max_nb_patches_h * max_nb_patches_w,
330
+ ),
331
+ fill_value=0,
332
+ )
333
+
334
+ for batch_idx, p_attn_mask in enumerate(patch_attention_mask):
335
+ if tgt_sizes is not None:
336
+ nb_patches_h = tgt_sizes[batch_idx][0]
337
+ nb_patches_w = tgt_sizes[batch_idx][1]
338
+ else:
339
+ nb_patches_h = p_attn_mask[:, 0].sum()
340
+ nb_patches_w = p_attn_mask[0].sum()
341
+
342
+ fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h)
343
+ fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
344
+
345
+ bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
346
+ bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
347
+
348
+ pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
349
+ position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids
350
+
351
+ position_ids = position_ids.to(self.position_embedding.weight.device)
352
+
353
+ embeddings = embeddings + self.position_embedding(position_ids)
354
+ return embeddings
355
+
356
+
357
+ class SiglipAttention(nn.Module):
358
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
359
+
360
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
361
+ def __init__(self, config):
362
+ super().__init__()
363
+ self.config = config
364
+ self.embed_dim = config.hidden_size
365
+ self.num_heads = config.num_attention_heads
366
+ self.head_dim = self.embed_dim // self.num_heads
367
+ if self.head_dim * self.num_heads != self.embed_dim:
368
+ raise ValueError(
369
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
370
+ f" {self.num_heads})."
371
+ )
372
+ self.scale = self.head_dim**-0.5
373
+ self.dropout = config.attention_dropout
374
+
375
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
376
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
377
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
378
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
379
+
380
+ def forward(
381
+ self,
382
+ hidden_states: torch.Tensor,
383
+ attention_mask: Optional[torch.Tensor] = None,
384
+ output_attentions: Optional[bool] = False,
385
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
386
+ """Input shape: Batch x Time x Channel"""
387
+
388
+ batch_size, q_len, _ = hidden_states.size()
389
+
390
+ query_states = self.q_proj(hidden_states)
391
+ key_states = self.k_proj(hidden_states)
392
+ value_states = self.v_proj(hidden_states)
393
+
394
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
395
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
396
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
397
+
398
+ k_v_seq_len = key_states.shape[-2]
399
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
400
+
401
+ if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
402
+ raise ValueError(
403
+ f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
404
+ f" {attn_weights.size()}"
405
+ )
406
+
407
+ if attention_mask is not None:
408
+ if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
409
+ raise ValueError(
410
+ f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
411
+ )
412
+ attn_weights = attn_weights + attention_mask
413
+
414
+ # upcast attention to fp32
415
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
416
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
417
+ attn_output = torch.matmul(attn_weights, value_states)
418
+
419
+ if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
420
+ raise ValueError(
421
+ f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
422
+ f" {attn_output.size()}"
423
+ )
424
+
425
+ attn_output = attn_output.transpose(1, 2).contiguous()
426
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
427
+
428
+ attn_output = self.out_proj(attn_output)
429
+
430
+ return attn_output, attn_weights
431
+
432
+
433
+ class SiglipFlashAttention2(SiglipAttention):
434
+ """
435
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
436
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
437
+ flash attention and deal with padding tokens in case the input contains any of them.
438
+ """
439
+
440
+ def __init__(self, *args, **kwargs):
441
+ super().__init__(*args, **kwargs)
442
+ self.is_causal = False # Hack to make sure we don't use a causal mask
443
+
444
+ def forward(
445
+ self,
446
+ hidden_states: torch.Tensor,
447
+ attention_mask: Optional[torch.LongTensor] = None,
448
+ position_ids: Optional[torch.LongTensor] = None,
449
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
450
+ output_attentions: bool = False,
451
+ use_cache: bool = False,
452
+ **kwargs,
453
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
454
+ output_attentions = False
455
+
456
+ bsz, q_len, _ = hidden_states.size()
457
+
458
+ query_states = self.q_proj(hidden_states)
459
+ key_states = self.k_proj(hidden_states)
460
+ value_states = self.v_proj(hidden_states)
461
+
462
+ # Flash attention requires the input to have the shape
463
+ # batch_size x seq_length x head_dim x hidden_dim
464
+ # therefore we just need to keep the original shape
465
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
466
+ key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
467
+ value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
468
+
469
+ kv_seq_len = key_states.shape[-2]
470
+ if past_key_value is not None:
471
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
472
+ # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
473
+ # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
474
+
475
+ # if past_key_value is not None:
476
+ # cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
477
+ # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
478
+
479
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
480
+ # to be able to avoid many of these transpose/reshape/view.
481
+ query_states = query_states.transpose(1, 2)
482
+ key_states = key_states.transpose(1, 2)
483
+ value_states = value_states.transpose(1, 2)
484
+
485
+ dropout_rate = self.dropout if self.training else 0.0
486
+
487
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
488
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
489
+ # cast them back in the correct dtype just to be sure everything works as expected.
490
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
491
+ # in fp32. (LlamaRMSNorm handles it correctly)
492
+
493
+ input_dtype = query_states.dtype
494
+ if input_dtype == torch.float32:
495
+ if torch.is_autocast_enabled():
496
+ target_dtype = torch.get_autocast_gpu_dtype()
497
+ # Handle the case where the model is quantized
498
+ elif hasattr(self.config, "_pre_quantization_dtype"):
499
+ target_dtype = self.config._pre_quantization_dtype
500
+ else:
501
+ target_dtype = self.q_proj.weight.dtype
502
+
503
+ logger.warning_once(
504
+ "The input hidden states seems to be silently casted in float32, this might be related to the fact"
505
+ " you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
506
+ f" {target_dtype}."
507
+ )
508
+
509
+ query_states = query_states.to(target_dtype)
510
+ key_states = key_states.to(target_dtype)
511
+ value_states = value_states.to(target_dtype)
512
+
513
+ attn_output = self._flash_attention_forward(
514
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
515
+ )
516
+
517
+ attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
518
+ attn_output = self.out_proj(attn_output)
519
+
520
+ if not output_attentions:
521
+ attn_weights = None
522
+
523
+ return attn_output, attn_weights
524
+
525
+ def _flash_attention_forward(
526
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
527
+ ):
528
+ """
529
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
530
+ first unpad the input, then computes the attention scores and pad the final attention scores.
531
+ Args:
532
+ query_states (`torch.Tensor`):
533
+ Input query states to be passed to Flash Attention API
534
+ key_states (`torch.Tensor`):
535
+ Input key states to be passed to Flash Attention API
536
+ value_states (`torch.Tensor`):
537
+ Input value states to be passed to Flash Attention API
538
+ attention_mask (`torch.Tensor`):
539
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
540
+ position of padding tokens and 1 for the position of non-padding tokens.
541
+ dropout (`int`, *optional*):
542
+ Attention dropout
543
+ softmax_scale (`float`, *optional*):
544
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
545
+ """
546
+
547
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
548
+ causal = self.is_causal and query_length != 1
549
+
550
+ # Contains at least one padding token in the sequence
551
+ if attention_mask is not None:
552
+ batch_size = query_states.shape[0]
553
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
554
+ query_states, key_states, value_states, attention_mask, query_length
555
+ )
556
+
557
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
558
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
559
+
560
+ attn_output_unpad = flash_attn_varlen_func(
561
+ query_states,
562
+ key_states,
563
+ value_states,
564
+ cu_seqlens_q=cu_seqlens_q,
565
+ cu_seqlens_k=cu_seqlens_k,
566
+ max_seqlen_q=max_seqlen_in_batch_q,
567
+ max_seqlen_k=max_seqlen_in_batch_k,
568
+ dropout_p=dropout,
569
+ softmax_scale=softmax_scale,
570
+ causal=causal,
571
+ )
572
+
573
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
574
+ else:
575
+ attn_output = flash_attn_func(
576
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
577
+ )
578
+
579
+ return attn_output
580
+
581
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
582
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
583
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
584
+
585
+ key_layer = index_first_axis(
586
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
587
+ )
588
+ value_layer = index_first_axis(
589
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
590
+ )
591
+ if query_length == kv_seq_len:
592
+ query_layer = index_first_axis(
593
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
594
+ )
595
+ cu_seqlens_q = cu_seqlens_k
596
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
597
+ indices_q = indices_k
598
+ elif query_length == 1:
599
+ max_seqlen_in_batch_q = 1
600
+ cu_seqlens_q = torch.arange(
601
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
602
+ ) # There is a memcpy here, that is very bad.
603
+ indices_q = cu_seqlens_q[:-1]
604
+ query_layer = query_layer.squeeze(1)
605
+ else:
606
+ # The -q_len: slice assumes left padding.
607
+ attention_mask = attention_mask[:, -query_length:]
608
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
609
+
610
+ return (
611
+ query_layer,
612
+ key_layer,
613
+ value_layer,
614
+ indices_q,
615
+ (cu_seqlens_q, cu_seqlens_k),
616
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
617
+ )
618
+
619
+
620
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
621
+ class SiglipMLP(nn.Module):
622
+ def __init__(self, config):
623
+ super().__init__()
624
+ self.config = config
625
+ self.activation_fn = ACT2FN[config.hidden_act]
626
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
627
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
628
+
629
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
630
+ hidden_states = self.fc1(hidden_states)
631
+ hidden_states = self.activation_fn(hidden_states)
632
+ hidden_states = self.fc2(hidden_states)
633
+ return hidden_states
634
+
635
+
636
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglip
637
+ class SiglipEncoderLayer(nn.Module):
638
+ def __init__(self, config: SiglipVisionConfig):
639
+ super().__init__()
640
+ self.embed_dim = config.hidden_size
641
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
642
+ self.self_attn = (
643
+ SiglipAttention(config)
644
+ if not self._use_flash_attention_2
645
+ else SiglipFlashAttention2(config)
646
+ )
647
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
648
+ self.mlp = SiglipMLP(config)
649
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
650
+
651
+ def forward(
652
+ self,
653
+ hidden_states: torch.Tensor,
654
+ attention_mask: torch.Tensor,
655
+ output_attentions: Optional[bool] = False,
656
+ ) -> Tuple[torch.FloatTensor]:
657
+ """
658
+ Args:
659
+ hidden_states (`torch.FloatTensor`):
660
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
661
+ attention_mask (`torch.FloatTensor`):
662
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
663
+ output_attentions (`bool`, *optional*, defaults to `False`):
664
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
665
+ returned tensors for more detail.
666
+ """
667
+ residual = hidden_states
668
+
669
+ hidden_states = self.layer_norm1(hidden_states)
670
+ hidden_states, attn_weights = self.self_attn(
671
+ hidden_states=hidden_states,
672
+ attention_mask=attention_mask,
673
+ output_attentions=output_attentions,
674
+ )
675
+ hidden_states = residual + hidden_states
676
+
677
+ residual = hidden_states
678
+ hidden_states = self.layer_norm2(hidden_states)
679
+ hidden_states = self.mlp(hidden_states)
680
+ hidden_states = residual + hidden_states
681
+
682
+ outputs = (hidden_states,)
683
+
684
+ if output_attentions:
685
+ outputs += (attn_weights,)
686
+
687
+ return outputs
688
+
689
+
690
+ class SiglipPreTrainedModel(PreTrainedModel):
691
+ """
692
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
693
+ models.
694
+ """
695
+
696
+ config_class = SiglipVisionConfig
697
+ base_model_prefix = "siglip"
698
+ supports_gradient_checkpointing = True
699
+
700
+ def _init_weights(self, module):
701
+ """Initialize the weights"""
702
+
703
+ if isinstance(module, SiglipVisionEmbeddings):
704
+ width = self.config.hidden_size
705
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
706
+ elif isinstance(module, nn.Embedding):
707
+ default_flax_embed_init(module.weight)
708
+ elif isinstance(module, SiglipAttention):
709
+ nn.init.normal_(module.q_proj.weight)
710
+ nn.init.normal_(module.k_proj.weight)
711
+ nn.init.normal_(module.v_proj.weight)
712
+ nn.init.normal_(module.out_proj.weight)
713
+ nn.init.zeros_(module.q_proj.bias)
714
+ nn.init.zeros_(module.k_proj.bias)
715
+ nn.init.zeros_(module.v_proj.bias)
716
+ nn.init.zeros_(module.out_proj.bias)
717
+ elif isinstance(module, SiglipMLP):
718
+ nn.init.normal_(module.fc1.weight)
719
+ nn.init.normal_(module.fc2.weight)
720
+ nn.init.normal_(module.fc1.bias, std=1e-6)
721
+ nn.init.normal_(module.fc2.bias, std=1e-6)
722
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
723
+ lecun_normal_(module.weight)
724
+ if module.bias is not None:
725
+ nn.init.zeros_(module.bias)
726
+ elif isinstance(module, nn.LayerNorm):
727
+ module.bias.data.zero_()
728
+ module.weight.data.fill_(1.0)
729
+
730
+
731
+ SIGLIP_START_DOCSTRING = r"""
732
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
733
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
734
+ etc.)
735
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
736
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
737
+ and behavior.
738
+ Parameters:
739
+ config ([`SiglipVisionConfig`]): Model configuration class with all the parameters of the model.
740
+ Initializing with a config file does not load the weights associated with the model, only the
741
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
742
+ """
743
+
744
+
745
+ SIGLIP_VISION_INPUTS_DOCSTRING = r"""
746
+ Args:
747
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
748
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
749
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
750
+ output_attentions (`bool`, *optional*):
751
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
752
+ tensors for more detail.
753
+ output_hidden_states (`bool`, *optional*):
754
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
755
+ more detail.
756
+ return_dict (`bool`, *optional*):
757
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
758
+ """
759
+
760
+
761
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglip
762
+ class SiglipEncoder(nn.Module):
763
+ """
764
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
765
+ [`SiglipEncoderLayer`].
766
+ Args:
767
+ config: SiglipConfig
768
+ """
769
+
770
+ def __init__(self, config: SiglipVisionConfig):
771
+ super().__init__()
772
+ self.config = config
773
+ self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
774
+ self.gradient_checkpointing = False
775
+
776
+ # Ignore copy
777
+ def forward(
778
+ self,
779
+ inputs_embeds,
780
+ attention_mask: Optional[torch.Tensor] = None,
781
+ output_attentions: Optional[bool] = None,
782
+ output_hidden_states: Optional[bool] = None,
783
+ return_dict: Optional[bool] = None,
784
+ ) -> Union[Tuple, BaseModelOutput]:
785
+ r"""
786
+ Args:
787
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
788
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
789
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
790
+ than the model's internal embedding lookup matrix.
791
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
792
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
793
+ - 1 for tokens that are **not masked**,
794
+ - 0 for tokens that are **masked**.
795
+ [What are attention masks?](../glossary#attention-mask)
796
+ output_attentions (`bool`, *optional*):
797
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
798
+ returned tensors for more detail.
799
+ output_hidden_states (`bool`, *optional*):
800
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
801
+ for more detail.
802
+ return_dict (`bool`, *optional*):
803
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
804
+ """
805
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
806
+ output_hidden_states = (
807
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
808
+ )
809
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
810
+
811
+ encoder_states = () if output_hidden_states else None
812
+ all_attentions = () if output_attentions else None
813
+
814
+ hidden_states = inputs_embeds
815
+ for encoder_layer in self.layers:
816
+ if output_hidden_states:
817
+ encoder_states = encoder_states + (hidden_states,)
818
+ if self.gradient_checkpointing and self.training:
819
+ layer_outputs = self._gradient_checkpointing_func(
820
+ encoder_layer.__call__,
821
+ hidden_states,
822
+ attention_mask,
823
+ output_attentions,
824
+ )
825
+ else:
826
+ layer_outputs = encoder_layer(
827
+ hidden_states,
828
+ attention_mask,
829
+ output_attentions=output_attentions,
830
+ )
831
+
832
+ hidden_states = layer_outputs[0]
833
+
834
+ if output_attentions:
835
+ all_attentions = all_attentions + (layer_outputs[1],)
836
+
837
+ if output_hidden_states:
838
+ encoder_states = encoder_states + (hidden_states,)
839
+
840
+ if not return_dict:
841
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
842
+ return BaseModelOutput(
843
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
844
+ )
845
+
846
+ @add_start_docstrings(
847
+ """The vision model from SigLIP without any head or projection on top.""",
848
+ SIGLIP_START_DOCSTRING
849
+ )
850
+ class SiglipVisionTransformer(SiglipPreTrainedModel):
851
+ config_class = SiglipVisionConfig
852
+ main_input_name = "pixel_values"
853
+ _supports_flash_attn_2 = True
854
+
855
+ def __init__(self, config: SiglipVisionConfig):
856
+ super().__init__(config)
857
+ self.config = config
858
+ embed_dim = config.hidden_size
859
+
860
+ self.embeddings = SiglipVisionEmbeddings(config)
861
+ self.encoder = SiglipEncoder(config)
862
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
863
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
864
+
865
+ # Initialize weights and apply final processing
866
+ self.post_init()
867
+
868
+ def get_input_embeddings(self) -> nn.Module:
869
+ return self.embeddings.patch_embedding
870
+
871
+ @add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
872
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig)
873
+ def forward(
874
+ self,
875
+ pixel_values,
876
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
877
+ tgt_sizes: Optional[torch.IntTensor] = None,
878
+ output_attentions: Optional[bool] = None,
879
+ output_hidden_states: Optional[bool] = None,
880
+ return_dict: Optional[bool] = None,
881
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
882
+ r"""
883
+ Returns:
884
+ """
885
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
886
+ output_hidden_states = (
887
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
888
+ )
889
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
890
+
891
+ batch_size = pixel_values.size(0)
892
+ if patch_attention_mask is None:
893
+ patch_attention_mask = torch.ones(
894
+ size=(
895
+ batch_size,
896
+ pixel_values.size(2) // self.config.patch_size,
897
+ pixel_values.size(3) // self.config.patch_size,
898
+ ),
899
+ dtype=torch.bool,
900
+ device=pixel_values.device,
901
+ )
902
+
903
+ hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask, tgt_sizes=tgt_sizes)
904
+
905
+ patch_attention_mask = patch_attention_mask.view(batch_size, -1)
906
+ # The call to `_upad_input` in `_flash_attention_forward` is expensive
907
+ # So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
908
+ # avoiding passing the attention_mask, which is equivalent to attending to the full sequence
909
+ if not torch.any(~patch_attention_mask):
910
+ attention_mask=None
911
+ else:
912
+ attention_mask = (
913
+ _prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
914
+ if not self._use_flash_attention_2
915
+ else patch_attention_mask
916
+ )
917
+
918
+ encoder_outputs = self.encoder(
919
+ inputs_embeds=hidden_states,
920
+ attention_mask=attention_mask,
921
+ output_attentions=output_attentions,
922
+ output_hidden_states=output_hidden_states,
923
+ return_dict=return_dict,
924
+ )
925
+
926
+ last_hidden_state = encoder_outputs[0]
927
+ last_hidden_state = self.post_layernorm(last_hidden_state)
928
+
929
+ if not return_dict:
930
+ return (last_hidden_state, None) + encoder_outputs[1:]
931
+
932
+ return BaseModelOutputWithPooling(
933
+ last_hidden_state=last_hidden_state,
934
+ pooler_output=None,
935
+ hidden_states=encoder_outputs.hidden_states,
936
+ attentions=encoder_outputs.attentions,
937
+ )
preprocessor_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c0dbc92920ded2304e2ed6ad4251da56029aa1f3f69427117ac6df9bc68496e
3
+ size 714
processing_minicpmv.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ max_length: Optional[int] = None,
58
+ do_pad: Optional[bool] = True,
59
+ max_slice_nums: int = None,
60
+ use_image_id: bool = None,
61
+ temporal_ids: Optional[Union[List[List[int]], List[List[List[int]]]]] = None,
62
+ return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
63
+ **kwargs
64
+ ) -> MiniCPMVBatchFeature:
65
+
66
+ if images is not None:
67
+ # image_inputs = self.image_processor(images, do_pad=do_pad, max_slice_nums=max_slice_nums, return_tensors=return_tensors)
68
+ image_inputs = self.image_processor(images, do_pad=do_pad, max_slice_nums=max_slice_nums, temporal_ids=temporal_ids, return_tensors=return_tensors)
69
+ # return self._convert_images_texts_to_inputs(image_inputs, text, max_slice_nums=max_slice_nums, use_image_id=use_image_id, max_length=max_length, **kwargs)
70
+ return self._convert_images_texts_to_inputs(image_inputs, text, max_slice_nums=max_slice_nums, use_image_id=use_image_id, max_length=max_length, temporal_ids=temporal_ids, **kwargs)
71
+
72
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
73
+ def batch_decode(self, *args, **kwargs):
74
+ """
75
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
76
+ refer to the docstring of this method for more information.
77
+ """
78
+ output_ids = args[0]
79
+ result_text = []
80
+ for result in output_ids:
81
+ result = result[result != 0]
82
+ if result[0] == self.tokenizer.bos_id:
83
+ result = result[1:]
84
+ if result[-1] == self.tokenizer.eos_id:
85
+ result = result[:-1]
86
+ result_text.append(self.tokenizer.decode(result, *args[1:], **kwargs).strip())
87
+ return result_text
88
+ # return self.tokenizer.batch_decode(*args, **kwargs)
89
+
90
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
91
+ def decode(self, *args, **kwargs):
92
+ """
93
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
94
+ the docstring of this method for more information.
95
+ """
96
+ result = args[0]
97
+ result = result[result != 0]
98
+ if result[0] == self.tokenizer.bos_id:
99
+ result = result[1:]
100
+ if result[-1] == self.tokenizer.eos_id or (hasattr(self.tokenizer, "eot_id") and result[-1] == self.tokenizer.eot_id):
101
+ result = result[:-1]
102
+ return self.tokenizer.decode(result, *args[1:], **kwargs).strip()
103
+
104
+ def _convert(
105
+ self, input_str, max_inp_length: Optional[int] = None
106
+ ):
107
+ if self.version > 2.5 or not getattr(self.tokenizer, "add_bos_token", False):
108
+ input_ids = self.tokenizer.encode(input_str)
109
+ else:
110
+ input_ids = [self.tokenizer.bos_id] + self.tokenizer.encode(input_str)
111
+ if max_inp_length is not None:
112
+ input_ids = input_ids[:max_inp_length]
113
+ input_ids = torch.tensor(input_ids, dtype=torch.int32)
114
+
115
+ start_cond = (input_ids == self.tokenizer.im_start_id) | (input_ids == self.tokenizer.slice_start_id)
116
+ end_cond = (input_ids == self.tokenizer.im_end_id) | (input_ids == self.tokenizer.slice_end_id)
117
+
118
+ image_start_tokens = torch.where(start_cond)[0]
119
+ image_start_tokens += 1
120
+ image_end_tokens = torch.where(end_cond)[0]
121
+
122
+ valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
123
+
124
+ image_bounds = torch.hstack(
125
+ [
126
+ image_start_tokens[:valid_image_nums].unsqueeze(-1),
127
+ image_end_tokens[:valid_image_nums].unsqueeze(-1),
128
+ ]
129
+ )
130
+ return input_ids, image_bounds
131
+
132
+ def _convert_images_texts_to_inputs(
133
+ self,
134
+ images,
135
+ texts: Union[str, List[str]],
136
+ truncation=None,
137
+ max_length=None,
138
+ max_slice_nums=None,
139
+ use_image_id=None,
140
+ return_tensors=None,
141
+ **kwargs
142
+ ):
143
+ if images is None or not len(images):
144
+ model_inputs = self.tokenizer(texts, return_tensors=return_tensors, truncation=truncation, max_length=max_length, **kwargs)
145
+ return MiniCPMVBatchFeature(data={**model_inputs})
146
+
147
+ pattern = "(<image>./</image>)"
148
+ # images, image_sizes, tgt_sizes = images["pixel_values"], images["image_sizes"], images["tgt_sizes"]
149
+ images, image_sizes, tgt_sizes, temporal_ids, skip_image_idx = images["pixel_values"], images["image_sizes"], images["tgt_sizes"], images["temporal_ids"], images["skip_image_idx"]
150
+
151
+ if isinstance(texts, str):
152
+ texts = [texts]
153
+ input_ids_list = []
154
+ image_bounds_list = []
155
+ for index, (text, skip_idx) in enumerate(zip(texts, skip_image_idx)):
156
+ image_tags = re.findall(pattern, text)
157
+ assert len(image_tags) == len(image_sizes[index])
158
+ text_chunks = text.split(pattern)
159
+ final_text = ""
160
+
161
+ for i in range(len(image_tags)):
162
+ if i in skip_idx:
163
+ image_placeholder = ''
164
+ text_chunk = text_chunks[i].strip()
165
+
166
+ else:
167
+ image_placeholder = self.image_processor.get_slice_image_placeholder(
168
+ image_sizes[index][i],
169
+ i,
170
+ max_slice_nums,
171
+ use_image_id
172
+ )
173
+ text_chunk = text_chunks[i]
174
+
175
+ final_text = final_text + text_chunk + image_placeholder
176
+
177
+ final_text += text_chunks[-1]
178
+
179
+ input_ids, image_bounds = self._convert(final_text, max_length)
180
+ input_ids_list.append(input_ids)
181
+ image_bounds_list.append(image_bounds)
182
+ padded_input_ids, padding_lengths = self.pad(
183
+ input_ids_list,
184
+ padding_side="left"
185
+ )
186
+ for i, length in enumerate(padding_lengths):
187
+ image_bounds_list[i] = image_bounds_list[i] + length
188
+ attention_mask = padded_input_ids.ne(0)
189
+
190
+ return MiniCPMVBatchFeature(data={
191
+ "input_ids": padded_input_ids,
192
+ "attention_mask": attention_mask,
193
+ "pixel_values": images,
194
+ "image_sizes": image_sizes,
195
+ "image_bound": image_bounds_list,
196
+ "tgt_sizes": tgt_sizes,
197
+ "temporal_ids": temporal_ids
198
+ })
199
+
200
+ @property
201
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
202
+ def model_input_names(self):
203
+ tokenizer_input_names = self.tokenizer.model_input_names
204
+ image_processor_input_names = self.image_processor.model_input_names
205
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
206
+
207
+
208
+ def pad(self, inputs, max_length=None, padding_value=0, padding_side="left"):
209
+ items = []
210
+ if isinstance(inputs[0], list):
211
+ assert isinstance(inputs[0][0], torch.Tensor)
212
+ for it in inputs:
213
+ for tr in it:
214
+ items.append(tr)
215
+ else:
216
+ assert isinstance(inputs[0], torch.Tensor)
217
+ items = inputs
218
+
219
+ batch_size = len(items)
220
+ shape = items[0].shape
221
+ dim = len(shape)
222
+ assert dim <= 2
223
+ if max_length is None:
224
+ max_length = 0
225
+ max_length = max(max_length, max(item.shape[-1] for item in items))
226
+ min_length = min(item.shape[-1] for item in items)
227
+ dtype = items[0].dtype
228
+
229
+ if dim == 0:
230
+ return torch.stack([item for item in items], dim=0), [0]
231
+ elif dim == 1:
232
+ if max_length == min_length:
233
+ return torch.stack([item for item in items], dim=0), [0] * batch_size
234
+ tensor = torch.zeros((batch_size, max_length), dtype=dtype) + padding_value
235
+ else:
236
+ tensor = (
237
+ torch.zeros((batch_size, max_length, shape[-1]), dtype=dtype)
238
+ + padding_value
239
+ )
240
+
241
+ padding_length = []
242
+ for i, item in enumerate(items):
243
+ if dim == 1:
244
+ if padding_side == "left":
245
+ tensor[i, -len(item) :] = item.clone()
246
+ else:
247
+ tensor[i, : len(item)] = item.clone()
248
+ elif dim == 2:
249
+ if padding_side == "left":
250
+ tensor[i, -len(item) :, :] = item.clone()
251
+ else:
252
+ tensor[i, : len(item), :] = item.clone()
253
+ padding_length.append(tensor.shape[-1] - len(item))
254
+
255
+ return tensor, padding_length
resampler.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ from itertools import chain
3
+ from typing import Optional, Tuple, List
4
+ import numpy as np
5
+
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn.init import trunc_normal_
9
+
10
+ from transformers.integrations import is_deepspeed_zero3_enabled
11
+
12
+ def get_2d_sincos_pos_embed(embed_dim, image_size):
13
+ """
14
+ image_size: image_size or (image_height, image_width)
15
+ return:
16
+ pos_embed: [image_height, image_width, embed_dim]
17
+ """
18
+ if isinstance(image_size, int):
19
+ grid_h_size, grid_w_size = image_size, image_size
20
+ else:
21
+ grid_h_size, grid_w_size = image_size[0], image_size[1]
22
+
23
+ grid_h = np.arange(grid_h_size, dtype=np.float32)
24
+ grid_w = np.arange(grid_w_size, dtype=np.float32)
25
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
26
+ grid = np.stack(grid, axis=0)
27
+
28
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
29
+ return pos_embed
30
+
31
+
32
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
33
+ assert embed_dim % 2 == 0
34
+
35
+ # use half of dimensions to encode grid_h
36
+ emb_h = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[0]) # (H, W, D/2)
37
+ emb_w = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[1]) # (H, W, D/2)
38
+
39
+ emb = np.concatenate([emb_h, emb_w], axis=-1) # (H, W, D)
40
+ return emb
41
+
42
+
43
+ def get_1d_sincos_pos_embed_from_grid_new(embed_dim, pos):
44
+ """
45
+ embed_dim: output dimension for each position
46
+ pos: a list of positions to be encoded: size (H, W)
47
+ out: (H, W, D)
48
+ """
49
+ assert embed_dim % 2 == 0
50
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
51
+ omega /= embed_dim / 2.
52
+ omega = 1. / 10000 ** omega # (D/2,)
53
+
54
+ out = np.einsum('hw,d->hwd', pos, omega) # (H, W, D/2), outer product
55
+
56
+ emb_sin = np.sin(out) # (H, W, D/2)
57
+ emb_cos = np.cos(out) # (H, W, D/2)
58
+
59
+ emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (H, W, D)
60
+ return emb
61
+
62
+ def get_1d_sincos_pos_embed_from_temporal_size(embed_dim, pos):
63
+ """
64
+ embed_dim: output dimension for each position
65
+ pos: a list of positions to be encoded: size (M,)
66
+ out: (M, D)
67
+ """
68
+ assert embed_dim % 2 == 0
69
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
70
+ omega /= embed_dim / 2.
71
+ omega = 1. / 10000**omega # (D/2,)
72
+
73
+ pos = pos.reshape(-1) # (M,)
74
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
75
+
76
+ emb_sin = np.sin(out) # (M, D/2)
77
+ emb_cos = np.cos(out) # (M, D/2)
78
+
79
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
80
+ return emb
81
+
82
+
83
+ class Resampler(nn.Module):
84
+ """
85
+ A 2D perceiver-resampler network with one cross attention layers by
86
+ given learnable queries and 2d sincos pos_emb
87
+ Outputs:
88
+ A tensor with the shape of (batch_size, num_queries, embed_dim)
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ num_queries,
94
+ embed_dim,
95
+ num_heads,
96
+ kv_dim=None,
97
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
98
+ adaptive=False,
99
+ max_size=(70, 70),
100
+ max_temporal_size=72000,
101
+ batch_infer=False
102
+ ):
103
+ super().__init__()
104
+ self.num_queries = num_queries
105
+ self.embed_dim = embed_dim
106
+ self.num_heads = num_heads
107
+ self.adaptive = adaptive
108
+ self.max_size = max_size
109
+ self.max_temporal_size = max_temporal_size
110
+ self.batch_infer = batch_infer
111
+
112
+ self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
113
+ trunc_normal_(self.query, std=.02)
114
+
115
+ if kv_dim is not None and kv_dim != embed_dim:
116
+ self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
117
+ else:
118
+ self.kv_proj = nn.Identity()
119
+
120
+ self.attn = nn.MultiheadAttention(embed_dim, num_heads)
121
+ self.ln_q = norm_layer(embed_dim)
122
+ self.ln_kv = norm_layer(embed_dim)
123
+
124
+ self.ln_post = norm_layer(embed_dim)
125
+ self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
126
+
127
+ self._set_2d_pos_cache(self.max_size)
128
+ self._set_temporal_pos_cache(self.max_temporal_size)
129
+ self.apply(self._init_weights)
130
+
131
+ def _set_2d_pos_cache(self, max_size, device='cpu'):
132
+ if is_deepspeed_zero3_enabled():
133
+ device='cuda'
134
+ pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.embed_dim, max_size)).float().to(device)
135
+ self.register_buffer("pos_embed", pos_embed, persistent=False)
136
+
137
+ def _adjust_pos_cache(self, tgt_sizes, device):
138
+ max_h = torch.max(tgt_sizes[:, 0])
139
+ max_w = torch.max(tgt_sizes[:, 1])
140
+ if max_h > self.max_size[0] or max_w > self.max_size[1]:
141
+ self.max_size = [max(max_h, self.max_size[0]), max(max_w, self.max_size[1])]
142
+ self._set_2d_pos_cache(self.max_size, device)
143
+
144
+ def _set_temporal_pos_cache(self, max_temporal_size, device='cpu'):
145
+ temporal_size = np.arange(max_temporal_size, dtype=np.float32)
146
+ pos_embed = torch.from_numpy(get_1d_sincos_pos_embed_from_temporal_size(self.embed_dim, temporal_size)).float().to(device)
147
+ self.register_buffer("temporal_pos_embed", pos_embed, persistent=False)
148
+
149
+ def _adjust_temporal_pos_cache(self, max_temporal_size, device):
150
+ if max_temporal_size > self.max_temporal_size:
151
+ self.max_temporal_size = max_temporal_size
152
+ self._set_temporal_pos_cache(self.max_temporal_size, device)
153
+
154
+ def _init_weights(self, m):
155
+ if isinstance(m, nn.Linear):
156
+ trunc_normal_(m.weight, std=.02)
157
+ if isinstance(m, nn.Linear) and m.bias is not None:
158
+ nn.init.constant_(m.bias, 0)
159
+ elif isinstance(m, nn.LayerNorm):
160
+ nn.init.constant_(m.bias, 0)
161
+ nn.init.constant_(m.weight, 1.0)
162
+
163
+ def forward(self, x, tgt_sizes=None, temporal_ids=None):
164
+ assert x.shape[0] == tgt_sizes.shape[0]
165
+ bs = x.shape[0]
166
+
167
+ device = x.device
168
+ dtype = x.dtype
169
+
170
+ patch_len = tgt_sizes[:, 0] * tgt_sizes[:, 1]
171
+
172
+ self._adjust_pos_cache(tgt_sizes, device=device)
173
+
174
+ temporal_pos_emb = False
175
+ temporal_ids_flatten = None
176
+ if temporal_ids is not None:
177
+ # example: [[-1], [-1], [2, 6, 9]]
178
+ temporal_ids_flatten = list(chain.from_iterable(temporal_ids))
179
+ max_temporal_size = max(temporal_ids_flatten) + 1
180
+ if max_temporal_size > -1:
181
+ temporal_pos_emb = True
182
+ if max_temporal_size > self.max_temporal_size:
183
+ self._adjust_temporal_pos_cache(max_temporal_size, device)
184
+
185
+
186
+ max_patch_len = torch.max(patch_len)
187
+ key_padding_mask = torch.zeros((bs, max_patch_len), dtype=torch.bool, device=device)
188
+
189
+ pos_embed = []
190
+ for i in range(bs):
191
+ tgt_h, tgt_w = tgt_sizes[i]
192
+ pos_embed.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape((tgt_h * tgt_w, -1)).to(dtype)) # patches * D
193
+ key_padding_mask[i, patch_len[i]:] = True
194
+
195
+ pos_embed = torch.nn.utils.rnn.pad_sequence(
196
+ pos_embed, batch_first=True, padding_value=0.0).permute(1, 0, 2) # BLD => L * B * D
197
+
198
+ x = self.kv_proj(x) # B * L * D
199
+ x = self.ln_kv(x).permute(1, 0, 2) # L * B * D
200
+
201
+ q = self.ln_q(self.query) # Q * D
202
+
203
+ pos_embed_2d = []
204
+ pos_embed_temporal = []
205
+ for i in range(bs):
206
+ tgt_h, tgt_w = tgt_sizes[i]
207
+ if temporal_pos_emb:
208
+ if temporal_ids_flatten[i] == -1:
209
+ pos_embed_temporal.append(torch.zeros(self.embed_dim, dtype=dtype, device=device))
210
+ else:
211
+ pos_embed_temporal.append(self.temporal_pos_embed[temporal_ids_flatten[i]].to(dtype)) # D
212
+
213
+ pos_embed_2d.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape((tgt_h * tgt_w, -1)).to(dtype)) # patches * D
214
+ key_padding_mask[i, patch_len[i]:] = True
215
+
216
+ pos_embed_2d = torch.nn.utils.rnn.pad_sequence(
217
+ pos_embed_2d, batch_first=True, padding_value=0.0).permute(1, 0, 2) # BLD => L * B * D
218
+
219
+ v = x
220
+ k = x + pos_embed_2d
221
+
222
+ if self.batch_infer:
223
+ out = self.batch_attn_forward(q, k, v, pos_embed_temporal, temporal_ids, key_padding_mask)
224
+ else: # save gpu memory
225
+ out = self.foreach_attn_forward(q, k, v, pos_embed_temporal, temporal_ids, key_padding_mask)
226
+
227
+ # out: Q * B * D
228
+ x = out.permute(1, 0, 2) # B * Q * D
229
+
230
+ x = self.ln_post(x)
231
+ x = x @ self.proj
232
+ return x
233
+
234
+
235
+ def _repeat(self, query, N: int):
236
+ return query.unsqueeze(1).repeat(1, N, 1)
237
+
238
+
239
+ def batch_attn_forward(self, q, k, v, pos_embed_temporal, temporal_ids, key_padding_mask):
240
+ bs = k.shape[0]
241
+
242
+ if pos_embed_temporal:
243
+ # temporal 维度折叠
244
+ # 时序 embedding
245
+ k += torch.stack(pos_embed_temporal, dim=0)
246
+ bs = len(temporal_ids)
247
+ merge_k = []
248
+ merge_v = []
249
+ merge_key_padding_mask = []
250
+
251
+ start = 0
252
+ for tp in temporal_ids:
253
+ end = start + len(tp)
254
+ # # L * (end-start) * D -> (end-start) * L * D -> 1 * L*(end-start) * D
255
+ merge_k.append(k[:, start: end, :].permute(1, 0, 2).reshape(-1, self.embed_dim))
256
+ merge_v.append(v[:, start: end, :].permute(1, 0, 2).reshape(-1, self.embed_dim))
257
+ merge_key_padding_mask.append(key_padding_mask[start: end, :].reshape(-1, 1))
258
+
259
+ start = end
260
+
261
+ k = torch.nn.utils.rnn.pad_sequence(merge_k, batch_first=True, padding_value=0.0).permute(1, 0, 2) # L*(end-start)
262
+ v = torch.nn.utils.rnn.pad_sequence(merge_v, batch_first=True, padding_value=0.0).permute(1, 0, 2) # L*(end-start)
263
+ key_padding_mask = torch.nn.utils.rnn.pad_sequence(merge_key_padding_mask, batch_first=True, padding_value=True).squeeze(-1)
264
+
265
+ out = self.attn(
266
+ self._repeat(q, bs), # Q * B * D
267
+ k, # L * B * D + L * B * D
268
+ v,
269
+ key_padding_mask=key_padding_mask)[0]
270
+
271
+ return out
272
+
273
+
274
+ def foreach_attn_forward(self, q, k, v, pos_embed_temporal, temporal_ids, key_padding_mask):
275
+ bs = k.shape[0]
276
+
277
+ if pos_embed_temporal:
278
+ k += torch.stack(pos_embed_temporal, dim=0)
279
+ # bs = len(temporal_ids)
280
+ out_list = []
281
+
282
+ start = 0
283
+ for tp in temporal_ids:
284
+ end = start + len(tp)
285
+ # 处理每个序列而不padding
286
+ curr_k = k[:, start:end, :].reshape(-1, self.embed_dim)
287
+ curr_v = v[:, start:end, :].reshape(-1, self.embed_dim)
288
+ curr_key_padding_mask = key_padding_mask[start: end, :].reshape(-1)
289
+ curr_out = self.attn(
290
+ q,
291
+ curr_k,
292
+ curr_v,
293
+ key_padding_mask=curr_key_padding_mask,
294
+ )[0]
295
+
296
+ out_list.append(curr_out)
297
+ start = end
298
+
299
+ # 合并所有序列的结果
300
+ out = torch.stack(out_list, dim=1)
301
+
302
+ else:
303
+ out = self.attn(
304
+ self._repeat(q, bs), # Q * B * D
305
+ k, # L * B * D + L * B * D
306
+ v,
307
+ key_padding_mask=key_padding_mask)[0]
308
+
309
+ return out
special_tokens_map.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:742d22f66cc33f367b17d45d8dcb5ffde7d777fe94a9b05ee858dc43018c2016
3
+ size 12103
tokenization_minicpmv_fast.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import Qwen2TokenizerFast
2
+
3
+
4
+ class MiniCPMVTokenizerFast(Qwen2TokenizerFast):
5
+ def __init__(self, **kwargs):
6
+ super().__init__(**kwargs)
7
+ self.im_start = "<image>"
8
+ self.im_end = "</image>"
9
+ self.ref_start = "<ref>"
10
+ self.ref_end = "</ref>"
11
+ self.box_start = "<box>"
12
+ self.box_end = "</box>"
13
+ self.quad_start = "<quad>"
14
+ self.quad_end = "</quad>"
15
+ self.slice_start = "<slice>"
16
+ self.slice_end = "</slice>"
17
+ self.im_id_start = "<image_id>"
18
+ self.im_id_end = "</image_id>"
19
+
20
+ @property
21
+ def eos_id(self):
22
+ return self.eos_token_id
23
+
24
+ @property
25
+ def bos_id(self):
26
+ return self.bos_token_id
27
+
28
+ @property
29
+ def unk_id(self):
30
+ return self.unk_token_id
31
+
32
+ @property
33
+ def im_start_id(self):
34
+ return self.convert_tokens_to_ids(self.im_start)
35
+
36
+ @property
37
+ def im_end_id(self):
38
+ return self.convert_tokens_to_ids(self.im_end)
39
+
40
+ @property
41
+ def slice_start_id(self):
42
+ return self.convert_tokens_to_ids(self.slice_start)
43
+
44
+ @property
45
+ def slice_end_id(self):
46
+ return self.convert_tokens_to_ids(self.slice_end)
47
+
48
+ @property
49
+ def im_id_start_id(self):
50
+ return self.convert_tokens_to_ids(self.im_id_start)
51
+
52
+ @property
53
+ def im_id_end_id(self):
54
+ return self.convert_tokens_to_ids(self.im_id_end)
55
+
56
+ @property
57
+ def newline_id(self):
58
+ return self.convert_tokens_to_ids('\n')
59
+
60
+ @staticmethod
61
+ def escape(text: str) -> str:
62
+ return text
63
+
64
+ @staticmethod
65
+ def unescape(text: str) -> str:
66
+ return text
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c5a94a2c3913b8aa2175fffb5fd6cf4301958f323d06475bfd91037c13bdd74b
3
+ size 11437868
tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8cbacbea273108831f02441518bbbc73627c15e34ddaa3fec6369e7bd07b720c
3
+ size 25786
vocab.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910
3
+ size 2776833