Wovchena commited on
Commit
fb5f6dc
·
verified ·
1 Parent(s): a3803cf

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ Copied from katuni4ka/tiny-random-minicpmv-2_6
added_tokens.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 151651,
3
+ "</image>": 151647,
4
+ "</image_id>": 151659,
5
+ "</point>": 151655,
6
+ "</quad>": 151653,
7
+ "</ref>": 151649,
8
+ "</slice>": 151657,
9
+ "<box>": 151650,
10
+ "<image>": 151646,
11
+ "<image_id>": 151658,
12
+ "<point>": 151654,
13
+ "<quad>": 151652,
14
+ "<ref>": 151648,
15
+ "<slice>": 151656,
16
+ "<|endoftext|>": 151643,
17
+ "<|im_end|>": 151645,
18
+ "<|im_start|>": 151644,
19
+ "<|reserved_special_token_0|>": 151660,
20
+ "<|reserved_special_token_1|>": 151661,
21
+ "<|reserved_special_token_2|>": 151662,
22
+ "<|reserved_special_token_3|>": 151663,
23
+ "<|reserved_special_token_4|>": 151664,
24
+ "<|reserved_special_token_5|>": 151665
25
+ }
config.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "tiny-random-minicpmv-2_6",
3
+ "architectures": [
4
+ "MiniCPMV"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_minicpm.MiniCPMVConfig",
9
+ "AutoModel": "modeling_minicpmv.MiniCPMV",
10
+ "AutoModelForCausalLM": "modeling_minicpmv.MiniCPMV"
11
+ },
12
+ "batch_vision_input": true,
13
+ "bos_token_id": 151643,
14
+ "drop_vision_last_layer": false,
15
+ "eos_token_id": 151645,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 256,
18
+ "image_size": 28,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 128,
21
+ "max_position_embeddings": 32768,
22
+ "max_window_layers": 2,
23
+ "model_type": "minicpmv",
24
+ "num_attention_heads": 2,
25
+ "num_hidden_layers": 2,
26
+ "num_key_value_heads": 2,
27
+ "patch_size": 2,
28
+ "query_num": 4,
29
+ "rms_norm_eps": 1e-06,
30
+ "rope_scaling": null,
31
+ "rope_theta": 1000000.0,
32
+ "slice_config": {
33
+ "max_slice_nums": 4,
34
+ "model_type": "minicpmv"
35
+ },
36
+ "slice_mode": true,
37
+ "sliding_window": null,
38
+ "tie_word_embeddings": false,
39
+ "torch_dtype": "float32",
40
+ "transformers_version": "4.46.1",
41
+ "use_cache": true,
42
+ "use_image_id": true,
43
+ "use_sliding_window": false,
44
+ "version": 2.6,
45
+ "vision_batch_size": 16,
46
+ "vision_config": {
47
+ "_attn_implementation_autoset": true,
48
+ "hidden_size": 64,
49
+ "image_size": 28,
50
+ "intermediate_size": 128,
51
+ "model_type": "siglip_vision_model",
52
+ "num_attention_heads": 2,
53
+ "num_hidden_layers": 4,
54
+ "patch_size": 2
55
+ },
56
+ "vocab_size": 151666
57
+ }
configuration_minicpm.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ """ MiniCPMV model configuration"""
3
+
4
+ import os
5
+ from typing import Union
6
+
7
+ from transformers import PretrainedConfig, Qwen2Config
8
+ from transformers.utils import logging
9
+
10
+ from .modeling_navit_siglip import SiglipVisionConfig
11
+
12
+
13
+ logger = logging.get_logger(__name__)
14
+
15
+
16
+ class MiniCPMVSliceConfig(PretrainedConfig):
17
+ model_type = "minicpmv"
18
+
19
+ def __init__(
20
+ self,
21
+ patch_size=14,
22
+ max_slice_nums=9,
23
+ scale_resolution=448,
24
+ **kwargs,
25
+ ):
26
+ super().__init__(**kwargs)
27
+ self.patch_size = patch_size
28
+ self.max_slice_nums = max_slice_nums
29
+ self.scale_resolution = scale_resolution
30
+
31
+ @classmethod
32
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
33
+ cls._set_token_in_kwargs(kwargs)
34
+
35
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
36
+
37
+ if config_dict.get("model_type") == "minicpmv":
38
+ config_dict = config_dict["slice_config"]
39
+
40
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
41
+ logger.warning(
42
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
43
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
44
+ )
45
+
46
+ return cls.from_dict(config_dict, **kwargs)
47
+
48
+
49
+ class MiniCPMVConfig(Qwen2Config):
50
+ model_type = "minicpmv"
51
+ keys_to_ignore_at_inference = ["past_key_values"]
52
+
53
+ default_vision_config = {
54
+ "hidden_size": 1152,
55
+ "image_size": 980,
56
+ "intermediate_size": 4304,
57
+ "model_type": "siglip",
58
+ "num_attention_heads": 16,
59
+ "num_hidden_layers": 27,
60
+ "patch_size": 14,
61
+ }
62
+
63
+ def __init__(
64
+ self,
65
+ use_cache=True,
66
+ query_num=64,
67
+ image_size=448,
68
+ drop_vision_last_layer=True,
69
+ batch_vision_input=True,
70
+ slice_config=None,
71
+ vision_config=None,
72
+ use_image_id=True,
73
+ vision_batch_size=16,
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
+
84
+ if slice_config is None:
85
+ self.slice_config = MiniCPMVSliceConfig(max_slice_nums=1)
86
+ else:
87
+ self.slice_config = MiniCPMVSliceConfig(**slice_config)
88
+ self.slice_mode = True
89
+
90
+ # same as HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit add tgt_sizes
91
+ if vision_config is None:
92
+ self.vision_config = SiglipVisionConfig(**self.default_vision_config)
93
+ logger.info("vision_config is None, using default vision config")
94
+ elif isinstance(vision_config, dict):
95
+ self.vision_config = SiglipVisionConfig(**vision_config)
96
+ elif isinstance(vision_config, SiglipVisionConfig):
97
+ self.vision_config = vision_config
98
+
99
+ self.patch_size = self.vision_config.patch_size
100
+
101
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "transformers_version": "4.46.1"
6
+ }
image_processing_minicpmv.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Any, Dict, List, Optional, Union
3
+
4
+ import numpy as np
5
+ import PIL
6
+ import PIL.Image
7
+ import PIL.ImageSequence
8
+ import torch
9
+ from PIL import Image
10
+ from transformers import AutoImageProcessor
11
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
12
+ from transformers.image_transforms import to_channel_dimension_format
13
+ from transformers.image_utils import (
14
+ ChannelDimension,
15
+ infer_channel_dimension_format,
16
+ is_torch_tensor,
17
+ to_numpy_array,
18
+ valid_images,
19
+ )
20
+ from transformers.utils import TensorType, is_torch_device, is_torch_dtype, requires_backends
21
+
22
+
23
+ def recursive_converter(converter, value):
24
+ if isinstance(value, list):
25
+ new_value = []
26
+ for v in value:
27
+ new_value += [recursive_converter(converter, v)]
28
+ return new_value
29
+ else:
30
+ return converter(value)
31
+
32
+
33
+ class MiniCPMVBatchFeature(BatchFeature):
34
+ r"""
35
+ Extend from BatchFeature for supporting various image size
36
+ """
37
+
38
+ def __init__(self, data: Optional[Dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None):
39
+ super().__init__(data)
40
+ self.convert_to_tensors(tensor_type=tensor_type)
41
+
42
+ def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None):
43
+ if tensor_type is None:
44
+ return self
45
+
46
+ is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type)
47
+
48
+ def converter(value):
49
+ try:
50
+ if not is_tensor(value):
51
+ tensor = as_tensor(value)
52
+ return tensor
53
+ except: # noqa E722
54
+ if key == "overflowing_values":
55
+ raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
56
+ raise ValueError(
57
+ "Unable to create tensor, you should probably activate padding "
58
+ "with 'padding=True' to have batched tensors with the same length."
59
+ )
60
+
61
+ for key, value in self.items():
62
+ self[key] = recursive_converter(converter, value)
63
+ return self
64
+
65
+ def to(self, *args, **kwargs) -> "MiniCPMVBatchFeature":
66
+ requires_backends(self, ["torch"])
67
+ import torch
68
+
69
+ def cast_tensor(v):
70
+ # check if v is a floating point
71
+ if torch.is_floating_point(v):
72
+ # cast and send to device
73
+ return v.to(*args, **kwargs)
74
+ elif device is not None:
75
+ return v.to(device=device)
76
+ else:
77
+ return v
78
+
79
+ new_data = {}
80
+ device = kwargs.get("device")
81
+ # Check if the args are a device or a dtype
82
+ if device is None and len(args) > 0:
83
+ # device should be always the first argument
84
+ arg = args[0]
85
+ if is_torch_dtype(arg):
86
+ # The first argument is a dtype
87
+ pass
88
+ elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):
89
+ device = arg
90
+ else:
91
+ # it's something else
92
+ raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.")
93
+ # We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor`
94
+ for k, v in self.items():
95
+ new_data[k] = recursive_converter(cast_tensor, v)
96
+ self.data = new_data
97
+ return self
98
+
99
+
100
+ class MiniCPMVImageProcessor(BaseImageProcessor):
101
+ model_input_names = ["pixel_values"]
102
+
103
+ def __init__(self, max_slice_nums=9, scale_resolution=448, patch_size=14, **kwargs):
104
+ super().__init__(**kwargs)
105
+ self.max_slice_nums = max_slice_nums
106
+ self.scale_resolution = scale_resolution
107
+ self.patch_size = patch_size
108
+ self.use_image_id = kwargs.pop("use_image_id", False)
109
+ self.image_feature_size = kwargs.pop("image_feature_size", 64)
110
+ self.im_start_token = kwargs.pop("im_start", "<image>")
111
+ self.im_end_token = kwargs.pop("im_end", "</image>")
112
+ self.slice_start_token = kwargs.pop("slice_start", "<slice>")
113
+ self.slice_end_token = kwargs.pop("slice_end", "</slice>")
114
+ self.unk_token = kwargs.pop("unk", "<unk>")
115
+ self.im_id_start = kwargs.pop("im_id_start", "<image_id>")
116
+ self.im_id_end = kwargs.pop("im_id_end", "</image_id>")
117
+ self.slice_mode = kwargs.pop("slice_mode", True)
118
+ self.mean = kwargs.pop("norm_mean", 0.5)
119
+ self.std = kwargs.pop("norm_std", 0.5)
120
+ self.version = kwargs.pop("version", 2.0)
121
+
122
+ def ensure_divide(self, length, patch_size):
123
+ return max(round(length / patch_size) * patch_size, patch_size)
124
+
125
+ def find_best_resize(self, original_size, scale_resolution, patch_size, allow_upscale=False):
126
+ width, height = original_size
127
+ if (width * height > scale_resolution * scale_resolution) or allow_upscale:
128
+ r = width / height
129
+ height = int(scale_resolution / math.sqrt(r))
130
+ width = int(height * r)
131
+ best_width = self.ensure_divide(width, patch_size)
132
+ best_height = self.ensure_divide(height, patch_size)
133
+ return (best_width, best_height)
134
+
135
+ def get_refine_size(self, original_size, grid, scale_resolution, patch_size, allow_upscale=False):
136
+ width, height = original_size
137
+ grid_x, grid_y = grid
138
+
139
+ refine_width = self.ensure_divide(width, grid_x)
140
+ refine_height = self.ensure_divide(height, grid_y)
141
+
142
+ grid_width = refine_width / grid_x
143
+ grid_height = refine_height / grid_y
144
+
145
+ best_grid_size = self.find_best_resize(
146
+ (grid_width, grid_height), scale_resolution, patch_size, allow_upscale=allow_upscale
147
+ )
148
+ refine_size = (best_grid_size[0] * grid_x, best_grid_size[1] * grid_y)
149
+ return refine_size
150
+
151
+ def split_to_patches(self, image, grid):
152
+ patches = []
153
+ width, height = image.size
154
+ grid_x = int(width / grid[0])
155
+ grid_y = int(height / grid[1])
156
+ for i in range(0, height, grid_y):
157
+ images = []
158
+ for j in range(0, width, grid_x):
159
+ box = (j, i, j + grid_x, i + grid_y)
160
+ patch = image.crop(box)
161
+ images.append(patch)
162
+ patches.append(images)
163
+ return patches
164
+
165
+ def slice_image(self, image, max_slice_nums=9, scale_resolution=448, patch_size=14, never_split=False):
166
+ original_size = image.size
167
+ source_image = None
168
+ best_grid = self.get_sliced_grid(original_size, max_slice_nums, never_split)
169
+ patches = []
170
+
171
+ if best_grid is None:
172
+ # dont need to slice, upsample
173
+ best_size = self.find_best_resize(original_size, scale_resolution, patch_size, allow_upscale=True)
174
+ source_image = image.resize(best_size, resample=Image.Resampling.BICUBIC)
175
+ else:
176
+ # source image, down-sampling and ensure divided by patch_size
177
+ best_resize = self.find_best_resize(original_size, scale_resolution, patch_size)
178
+ source_image = image.copy().resize(best_resize, resample=Image.Resampling.BICUBIC)
179
+ refine_size = self.get_refine_size(
180
+ original_size, best_grid, scale_resolution, patch_size, allow_upscale=True
181
+ )
182
+ refine_image = image.resize(refine_size, resample=Image.Resampling.BICUBIC)
183
+ patches = self.split_to_patches(refine_image, best_grid)
184
+
185
+ return source_image, patches, best_grid
186
+
187
+ def get_grid_placeholder(self, grid):
188
+ if grid is None:
189
+ return ""
190
+ slice_image_placeholder = (
191
+ self.slice_start_token + self.unk_token * self.image_feature_size + self.slice_end_token
192
+ )
193
+
194
+ cols = grid[0]
195
+ rows = grid[1]
196
+ slices = []
197
+ for i in range(rows):
198
+ lines = []
199
+ for j in range(cols):
200
+ lines.append(slice_image_placeholder)
201
+ slices.append("".join(lines))
202
+
203
+ slice_placeholder = "\n".join(slices)
204
+ return slice_placeholder
205
+
206
+ def get_image_id_placeholder(self, idx=0):
207
+ return f"{self.im_id_start}{idx}{self.im_id_end}"
208
+
209
+ def get_sliced_images(self, image, max_slice_nums=None):
210
+ slice_images = []
211
+
212
+ if not self.slice_mode:
213
+ return [image]
214
+
215
+ max_slice_nums = self.max_slice_nums if max_slice_nums is None else int(max_slice_nums)
216
+ assert max_slice_nums > 0
217
+ source_image, patches, sliced_grid = self.slice_image(
218
+ image, max_slice_nums, self.scale_resolution, self.patch_size # default: 9 # default: 448 # default: 14
219
+ )
220
+
221
+ slice_images.append(source_image)
222
+ if len(patches) > 0:
223
+ for i in range(len(patches)):
224
+ for j in range(len(patches[0])):
225
+ slice_images.append(patches[i][j])
226
+ return slice_images
227
+
228
+ def get_sliced_grid(self, image_size, max_slice_nums, nerver_split=False):
229
+ original_width, original_height = image_size
230
+ log_ratio = math.log(original_width / original_height)
231
+ ratio = original_width * original_height / (self.scale_resolution * self.scale_resolution)
232
+ multiple = min(math.ceil(ratio), max_slice_nums)
233
+ if multiple <= 1 or nerver_split:
234
+ return None
235
+ candidate_split_grids_nums = []
236
+ for i in [multiple - 1, multiple, multiple + 1]:
237
+ if i == 1 or i > max_slice_nums:
238
+ continue
239
+ candidate_split_grids_nums.append(i)
240
+
241
+ candidate_grids = []
242
+ for split_grids_nums in candidate_split_grids_nums:
243
+ m = 1
244
+ while m <= split_grids_nums:
245
+ if split_grids_nums % m == 0:
246
+ candidate_grids.append([m, split_grids_nums // m])
247
+ m += 1
248
+
249
+ best_grid = [1, 1]
250
+ min_error = float("inf")
251
+ for grid in candidate_grids:
252
+ error = abs(log_ratio - math.log(grid[0] / grid[1]))
253
+ if error < min_error:
254
+ best_grid = grid
255
+ min_error = error
256
+
257
+ return best_grid
258
+
259
+ def get_slice_image_placeholder(self, image_size, image_idx=0, max_slice_nums=None, use_image_id=None):
260
+ max_slice_nums = self.max_slice_nums if max_slice_nums is None else int(max_slice_nums)
261
+ assert max_slice_nums > 0
262
+ grid = self.get_sliced_grid(image_size=image_size, max_slice_nums=max_slice_nums)
263
+
264
+ image_placeholder = self.im_start_token + self.unk_token * self.image_feature_size + self.im_end_token
265
+ use_image_id = self.use_image_id if use_image_id is None else bool(use_image_id)
266
+ if use_image_id:
267
+ final_placeholder = self.get_image_id_placeholder(image_idx) + image_placeholder
268
+ else:
269
+ final_placeholder = image_placeholder
270
+
271
+ if self.slice_mode:
272
+ final_placeholder = final_placeholder + self.get_grid_placeholder(grid=grid)
273
+ return final_placeholder
274
+
275
+ def to_pil_image(self, image, rescale=None) -> PIL.Image.Image:
276
+ """
277
+ Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
278
+ needed.
279
+
280
+ Args:
281
+ image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):
282
+ The image to convert to the PIL Image format.
283
+ rescale (`bool`, *optional*):
284
+ Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will
285
+ default to `True` if the image type is a floating type, `False` otherwise.
286
+ """
287
+ if isinstance(image, PIL.Image.Image):
288
+ return image
289
+ if is_torch_tensor(image):
290
+ image = image.numpy()
291
+
292
+ if isinstance(image, np.ndarray):
293
+ if rescale is None:
294
+ # rescale default to the array being of floating type.
295
+ rescale = isinstance(image.flat[0], np.floating)
296
+ # If the channel as been moved to first dim, we put it back at the end.
297
+ if image.ndim == 3 and image.shape[0] in [1, 3]:
298
+ image = image.transpose(1, 2, 0)
299
+ if rescale:
300
+ image = image * 255
301
+ image = image.astype(np.uint8)
302
+ return PIL.Image.fromarray(image)
303
+ return image
304
+
305
+ def reshape_by_patch(self, image):
306
+ """
307
+ :param image: shape [3, H, W]
308
+ :param patch_size:
309
+ :return: [3, patch_size, HW/patch_size]
310
+ """
311
+ image = torch.from_numpy(image)
312
+ patch_size = self.patch_size
313
+ patches = torch.nn.functional.unfold(image, (patch_size, patch_size), stride=(patch_size, patch_size))
314
+
315
+ patches = patches.reshape(image.size(0), patch_size, patch_size, -1)
316
+ patches = patches.permute(0, 1, 3, 2).reshape(image.size(0), patch_size, -1)
317
+ return patches.numpy()
318
+
319
+ def preprocess(
320
+ self,
321
+ images: Union[Image.Image, List[Image.Image], List[List[Image.Image]]],
322
+ do_pad: Optional[bool] = True, # TODO: add pad for MiniCPM-Llama3-V-2_5
323
+ max_slice_nums: int = None,
324
+ return_tensors: Optional[Union[str, TensorType]] = None,
325
+ **kwargs,
326
+ ) -> MiniCPMVBatchFeature:
327
+ if isinstance(images, Image.Image):
328
+ images_list = [[images]]
329
+ elif isinstance(images[0], Image.Image):
330
+ images_list = [images]
331
+ else:
332
+ images_list = images
333
+
334
+ new_images_list = []
335
+ image_sizes_list = []
336
+ tgt_sizes_list = []
337
+
338
+ for _images in images_list:
339
+ if _images is None or len(_images) == 0:
340
+ new_images_list.append([])
341
+ image_sizes_list.append([])
342
+ tgt_sizes_list.append([])
343
+ continue
344
+ if not valid_images(_images):
345
+ raise ValueError(
346
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
347
+ "torch.Tensor, tf.Tensor or jax.ndarray."
348
+ )
349
+
350
+ _images = [self.to_pil_image(image).convert("RGB") for image in _images]
351
+ input_data_format = infer_channel_dimension_format(np.array(_images[0]))
352
+
353
+ new_images = []
354
+ image_sizes = [image.size for image in _images]
355
+ tgt_sizes = []
356
+ for image in _images:
357
+ image_patches = self.get_sliced_images(image, max_slice_nums)
358
+ image_patches = [to_numpy_array(image).astype(np.float32) / 255 for image in image_patches]
359
+ image_patches = [
360
+ self.normalize(image=image, mean=self.mean, std=self.std, input_data_format=input_data_format)
361
+ for image in image_patches
362
+ ]
363
+ image_patches = [
364
+ to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=input_data_format)
365
+ for image in image_patches
366
+ ]
367
+ for slice_image in image_patches:
368
+ new_images.append(self.reshape_by_patch(slice_image))
369
+ tgt_sizes.append(
370
+ np.array((slice_image.shape[1] // self.patch_size, slice_image.shape[2] // self.patch_size))
371
+ )
372
+
373
+ if tgt_sizes:
374
+ tgt_sizes = np.vstack(tgt_sizes)
375
+
376
+ new_images_list.append(new_images)
377
+ image_sizes_list.append(image_sizes)
378
+ tgt_sizes_list.append(tgt_sizes)
379
+ return MiniCPMVBatchFeature(
380
+ data={"pixel_values": new_images_list, "image_sizes": image_sizes_list, "tgt_sizes": tgt_sizes_list},
381
+ tensor_type=return_tensors,
382
+ )
383
+
384
+
385
+ AutoImageProcessor.register("MiniCPMVImageProcessor", MiniCPMVImageProcessor)
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a13c2a624f4445809755648b73465369b127bf9f4c7a6a87ccf0c7498039149
3
+ size 315498808
modeling_minicpmv.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+ from copy import deepcopy
4
+ from threading import Thread
5
+
6
+ import torch
7
+ from PIL import Image
8
+ from transformers import AutoProcessor, Qwen2ForCausalLM, Qwen2PreTrainedModel
9
+
10
+ from .configuration_minicpm import MiniCPMVConfig
11
+ from .modeling_navit_siglip import SiglipVisionTransformer
12
+ from .resampler import Resampler
13
+
14
+
15
+ class MiniCPMVPreTrainedModel(Qwen2PreTrainedModel):
16
+ config_class = MiniCPMVConfig
17
+
18
+
19
+ class MiniCPMV(MiniCPMVPreTrainedModel):
20
+ def __init__(self, config):
21
+ super().__init__(config)
22
+ self.llm = Qwen2ForCausalLM(config)
23
+ self.vpm = self.init_vision_module()
24
+ self.vision_dim = self.vpm.embed_dim
25
+ self.embed_dim = self.llm.config.hidden_size
26
+ self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
27
+ self.processor = None
28
+
29
+ self.terminators = ["<|im_end|>", "<|endoftext|>"]
30
+
31
+ def init_vision_module(self):
32
+ # same as HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit add tgt_sizes
33
+ if self.config._attn_implementation == "flash_attention_2":
34
+ self.config.vision_config._attn_implementation = "flash_attention_2"
35
+ else:
36
+ # not suport sdpa
37
+ self.config.vision_config._attn_implementation = "eager"
38
+ model = SiglipVisionTransformer(self.config.vision_config)
39
+ if self.config.drop_vision_last_layer:
40
+ model.encoder.layers = model.encoder.layers[:-1]
41
+
42
+ setattr(model, "embed_dim", model.embeddings.embed_dim)
43
+ setattr(model, "patch_size", model.embeddings.patch_size)
44
+
45
+ return model
46
+
47
+ def init_resampler(self, embed_dim, vision_dim):
48
+ return Resampler(
49
+ num_queries=self.config.query_num,
50
+ embed_dim=embed_dim,
51
+ num_heads=embed_dim // 128,
52
+ kv_dim=vision_dim,
53
+ adaptive=True,
54
+ )
55
+
56
+ def get_input_embeddings(self):
57
+ return self.llm.get_input_embeddings()
58
+
59
+ def set_input_embeddings(self, value):
60
+ self.llm.embed_tokens = value
61
+
62
+ def get_output_embeddings(self):
63
+ return self.llm.lm_head
64
+
65
+ def set_output_embeddings(self, new_embeddings):
66
+ self.llm.lm_head = new_embeddings
67
+
68
+ def set_decoder(self, decoder):
69
+ self.llm = decoder
70
+
71
+ def get_decoder(self):
72
+ return self.llm
73
+
74
+ def get_vllm_embedding(self, data):
75
+ if "vision_hidden_states" not in data:
76
+ dtype = self.llm.model.embed_tokens.weight.dtype
77
+ device = self.llm.model.embed_tokens.weight.device
78
+ tgt_sizes = data["tgt_sizes"]
79
+ pixel_values_list = data["pixel_values"]
80
+ vision_hidden_states = []
81
+ all_pixel_values = []
82
+ img_cnt = []
83
+ for pixel_values in pixel_values_list:
84
+ img_cnt.append(len(pixel_values))
85
+ all_pixel_values.extend([i.flatten(end_dim=1).permute(1, 0) for i in pixel_values])
86
+
87
+ # exist image
88
+ if all_pixel_values:
89
+ tgt_sizes = [tgt_size for tgt_size in tgt_sizes if isinstance(tgt_size, torch.Tensor)]
90
+ tgt_sizes = torch.vstack(tgt_sizes).type(torch.int32)
91
+
92
+ max_patches = torch.max(tgt_sizes[:, 0] * tgt_sizes[:, 1])
93
+
94
+ all_pixel_values = torch.nn.utils.rnn.pad_sequence(
95
+ all_pixel_values, batch_first=True, padding_value=0.0
96
+ )
97
+ B, L, _ = all_pixel_values.shape
98
+ all_pixel_values = all_pixel_values.permute(0, 2, 1).reshape(B, 3, -1, L)
99
+
100
+ patch_attn_mask = torch.zeros((B, 1, max_patches), dtype=torch.bool, device=device)
101
+ for i in range(B):
102
+ patch_attn_mask[i, 0, : tgt_sizes[i][0] * tgt_sizes[i][1]] = True
103
+
104
+ vision_batch_size = self.config.vision_batch_size
105
+ all_pixel_values = all_pixel_values.type(dtype)
106
+ if B > vision_batch_size:
107
+ hs = []
108
+ for i in range(0, B, vision_batch_size):
109
+ start_idx = i
110
+ end_idx = i + vision_batch_size
111
+ tmp_hs = self.vpm(
112
+ all_pixel_values[start_idx:end_idx],
113
+ patch_attention_mask=patch_attn_mask[start_idx:end_idx],
114
+ tgt_sizes=tgt_sizes[start_idx:end_idx],
115
+ ).last_hidden_state
116
+ hs.append(tmp_hs)
117
+ vision_embedding = torch.cat(hs, dim=0)
118
+ else:
119
+ vision_embedding = self.vpm(
120
+ all_pixel_values, patch_attention_mask=patch_attn_mask, tgt_sizes=tgt_sizes
121
+ ).last_hidden_state
122
+ vision_embedding = self.resampler(vision_embedding, tgt_sizes)
123
+
124
+ start = 0
125
+ for pixel_values in pixel_values_list:
126
+ img_cnt = len(pixel_values)
127
+ if img_cnt > 0:
128
+ vision_hidden_states.append(vision_embedding[start : start + img_cnt])
129
+ start += img_cnt
130
+ else:
131
+ vision_hidden_states.append([])
132
+ else: # no image
133
+ if self.training:
134
+ dummy_image = torch.zeros((1, 3, 224, 224), device=device, dtype=dtype)
135
+ tgt_sizes = torch.Tensor(
136
+ [[(224 // self.config.patch_size), math.ceil(224 / self.config.patch_size)]]
137
+ ).type(torch.int32)
138
+ dummy_feature = self.resampler(self.vpm(dummy_image).last_hidden_state, tgt_sizes)
139
+ else:
140
+ dummy_feature = []
141
+ for _ in range(len(pixel_values_list)):
142
+ vision_hidden_states.append(dummy_feature)
143
+
144
+ else:
145
+ vision_hidden_states = data["vision_hidden_states"]
146
+
147
+ if hasattr(self.llm.config, "scale_emb"):
148
+ vllm_embedding = self.llm.model.embed_tokens(data["input_ids"]) * self.llm.config.scale_emb
149
+ else:
150
+ vllm_embedding = self.llm.model.embed_tokens(data["input_ids"])
151
+
152
+ vision_hidden_states = [
153
+ i.type(vllm_embedding.dtype) if isinstance(i, torch.Tensor) else i for i in vision_hidden_states
154
+ ]
155
+
156
+ bs = len(data["input_ids"])
157
+ for i in range(bs):
158
+ cur_vs_hs = vision_hidden_states[i]
159
+ if len(cur_vs_hs) > 0:
160
+ cur_vllm_emb = vllm_embedding[i]
161
+ cur_image_bound = data["image_bound"][i]
162
+ if len(cur_image_bound) > 0:
163
+ image_indices = torch.stack(
164
+ [torch.arange(r[0], r[1], dtype=torch.long) for r in cur_image_bound]
165
+ ).to(vllm_embedding.device)
166
+
167
+ cur_vllm_emb.scatter_(
168
+ 0,
169
+ image_indices.view(-1, 1).repeat(1, cur_vllm_emb.shape[-1]),
170
+ cur_vs_hs.view(-1, cur_vs_hs.shape[-1]),
171
+ )
172
+ elif self.training:
173
+ cur_vllm_emb += cur_vs_hs[0].mean() * 0
174
+
175
+ return vllm_embedding, vision_hidden_states
176
+
177
+ def forward(self, data, **kwargs):
178
+ vllm_embedding, vision_hidden_states = self.get_vllm_embedding(data)
179
+ position_ids = data["position_ids"]
180
+ if position_ids.dtype != torch.int64:
181
+ position_ids = position_ids.long()
182
+
183
+ return self.llm(input_ids=None, position_ids=position_ids, inputs_embeds=vllm_embedding, **kwargs)
184
+
185
+ def _decode(self, inputs_embeds, tokenizer, attention_mask, decode_text=False, **kwargs):
186
+ terminators = None
187
+ if tokenizer is not None:
188
+ terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
189
+ kwargs.pop("image_sizes", None)
190
+ output = self.llm.generate(
191
+ inputs_embeds=inputs_embeds,
192
+ # pad_token_id=0,
193
+ eos_token_id=terminators,
194
+ attention_mask=attention_mask,
195
+ **kwargs,
196
+ )
197
+ if decode_text:
198
+ return self._decode_text(output, tokenizer)
199
+ return output
200
+
201
+ def _decode_stream(self, inputs_embeds, tokenizer, **kwargs):
202
+ from transformers import TextIteratorStreamer
203
+ terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
204
+ streamer = TextIteratorStreamer(tokenizer=tokenizer)
205
+ generation_kwargs = {
206
+ "inputs_embeds": inputs_embeds,
207
+ "pad_token_id": 0,
208
+ "eos_token_id": terminators,
209
+ "streamer": streamer,
210
+ }
211
+ generation_kwargs.update(kwargs)
212
+
213
+ thread = Thread(target=self.llm.generate, kwargs=generation_kwargs)
214
+ thread.start()
215
+
216
+ return streamer
217
+
218
+ def _decode_text(self, result_ids, tokenizer):
219
+ terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
220
+ result_text = []
221
+ for result in result_ids:
222
+ result = result[result != 0]
223
+ if result[0] == tokenizer.bos_id:
224
+ result = result[1:]
225
+ if result[-1] in terminators:
226
+ result = result[:-1]
227
+ result_text.append(tokenizer.decode(result).strip())
228
+ return result_text
229
+
230
+ def generate(
231
+ self,
232
+ input_ids=None,
233
+ pixel_values=None,
234
+ tgt_sizes=None,
235
+ image_bound=None,
236
+ attention_mask=None,
237
+ tokenizer=None,
238
+ vision_hidden_states=None,
239
+ return_vision_hidden_states=False,
240
+ stream=False,
241
+ decode_text=False,
242
+ **kwargs,
243
+ ):
244
+ assert input_ids is not None
245
+ assert len(input_ids) == len(pixel_values)
246
+
247
+ model_inputs = {
248
+ "input_ids": input_ids,
249
+ "image_bound": image_bound,
250
+ }
251
+
252
+ if vision_hidden_states is None:
253
+ model_inputs["pixel_values"] = pixel_values
254
+ model_inputs["tgt_sizes"] = tgt_sizes
255
+ else:
256
+ model_inputs["vision_hidden_states"] = vision_hidden_states
257
+
258
+ with torch.inference_mode():
259
+ (
260
+ model_inputs["inputs_embeds"],
261
+ vision_hidden_states,
262
+ ) = self.get_vllm_embedding(model_inputs)
263
+
264
+ if stream:
265
+ result = self._decode_stream(model_inputs["inputs_embeds"], tokenizer, **kwargs)
266
+ else:
267
+ result = self._decode(
268
+ model_inputs["inputs_embeds"], tokenizer, attention_mask, decode_text=decode_text, **kwargs
269
+ )
270
+
271
+ if return_vision_hidden_states:
272
+ return result, vision_hidden_states
273
+
274
+ return result
275
+
276
+ def chat(
277
+ self,
278
+ image,
279
+ msgs,
280
+ tokenizer,
281
+ processor=None,
282
+ vision_hidden_states=None,
283
+ max_new_tokens=2048,
284
+ min_new_tokens=0,
285
+ sampling=True,
286
+ max_inp_length=8192,
287
+ system_prompt="",
288
+ stream=False,
289
+ max_slice_nums=None,
290
+ use_image_id=None,
291
+ **kwargs,
292
+ ):
293
+ if isinstance(msgs[0], list):
294
+ batched = True
295
+ else:
296
+ batched = False
297
+ msgs_list = msgs
298
+ images_list = image
299
+
300
+ if batched is False:
301
+ images_list, msgs_list = [images_list], [msgs_list]
302
+ else:
303
+ assert images_list is None, "Please integrate image to msgs when using batch inference."
304
+ images_list = [None] * len(msgs_list)
305
+ assert len(images_list) == len(msgs_list), "The batch dim of images_list and msgs_list should be the same."
306
+
307
+ if processor is None:
308
+ if self.processor is None:
309
+ self.processor = AutoProcessor.from_pretrained(self.config._name_or_path, trust_remote_code=True)
310
+ processor = self.processor
311
+
312
+ assert (
313
+ self.config.query_num == processor.image_processor.image_feature_size
314
+ ), "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
315
+ assert (
316
+ self.config.patch_size == processor.image_processor.patch_size
317
+ ), "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
318
+ assert (
319
+ self.config.use_image_id == processor.image_processor.use_image_id
320
+ ), "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
321
+ assert (
322
+ self.config.slice_config.max_slice_nums == processor.image_processor.max_slice_nums
323
+ ), "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
324
+ assert (
325
+ self.config.slice_mode == processor.image_processor.slice_mode
326
+ ), "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
327
+
328
+ prompts_lists = []
329
+ input_images_lists = []
330
+ for image, msgs in zip(images_list, msgs_list):
331
+ if isinstance(msgs, str):
332
+ msgs = json.loads(msgs)
333
+ copy_msgs = deepcopy(msgs)
334
+
335
+ assert len(msgs) > 0, "msgs is empty"
336
+ assert sampling or not stream, "if use stream mode, make sure sampling=True"
337
+
338
+ if image is not None and isinstance(copy_msgs[0]["content"], str):
339
+ copy_msgs[0]["content"] = [image, copy_msgs[0]["content"]]
340
+
341
+ images = []
342
+ for i, msg in enumerate(copy_msgs):
343
+ role = msg["role"]
344
+ content = msg["content"]
345
+ assert role in ["user", "assistant"]
346
+ if i == 0:
347
+ assert role == "user", "The role of first msg should be user"
348
+ if isinstance(content, str):
349
+ content = [content]
350
+ cur_msgs = []
351
+ for c in content:
352
+ if isinstance(c, Image.Image):
353
+ images.append(c)
354
+ cur_msgs.append("(<image>./</image>)")
355
+ elif isinstance(c, str):
356
+ cur_msgs.append(c)
357
+ msg["content"] = "\n".join(cur_msgs)
358
+
359
+ if system_prompt:
360
+ sys_msg = {"role": "system", "content": system_prompt}
361
+ copy_msgs = [sys_msg] + copy_msgs
362
+
363
+ prompts_lists.append(
364
+ processor.tokenizer.apply_chat_template(copy_msgs, tokenize=False, add_generation_prompt=True)
365
+ )
366
+ input_images_lists.append(images)
367
+
368
+ inputs = processor(
369
+ prompts_lists,
370
+ input_images_lists,
371
+ max_slice_nums=max_slice_nums,
372
+ use_image_id=use_image_id,
373
+ return_tensors="pt",
374
+ max_length=max_inp_length,
375
+ ).to(self.device)
376
+
377
+ if sampling:
378
+ generation_config = {
379
+ "top_p": 0.8,
380
+ "top_k": 100,
381
+ "temperature": 0.7,
382
+ "do_sample": True,
383
+ "repetition_penalty": 1.05,
384
+ }
385
+ else:
386
+ generation_config = {
387
+ "num_beams": 3,
388
+ "repetition_penalty": 1.2,
389
+ }
390
+
391
+ if min_new_tokens > 0:
392
+ generation_config["min_new_tokens"] = min_new_tokens
393
+
394
+ generation_config.update((k, kwargs[k]) for k in generation_config.keys() & kwargs.keys())
395
+
396
+ inputs.pop("image_sizes", None)
397
+ with torch.inference_mode():
398
+ res = self.generate(
399
+ **inputs,
400
+ tokenizer=tokenizer,
401
+ max_new_tokens=max_new_tokens,
402
+ vision_hidden_states=vision_hidden_states,
403
+ stream=stream,
404
+ decode_text=True,
405
+ **generation_config,
406
+ )
407
+
408
+ if stream:
409
+
410
+ def stream_gen():
411
+ for text in res:
412
+ for term in self.terminators:
413
+ text = text.replace(term, "")
414
+ yield text
415
+
416
+ return stream_gen()
417
+
418
+ else:
419
+ if batched:
420
+ answer = res
421
+ else:
422
+ answer = res[0]
423
+ return answer
modeling_navit_siglip.py ADDED
@@ -0,0 +1,943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
20
+ import os
21
+ import warnings
22
+ from dataclasses import dataclass
23
+ from typing import 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
+ from transformers.activations import ACT2FN
32
+ from transformers.configuration_utils import PretrainedConfig
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.utils import (
37
+ ModelOutput,
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ is_flash_attn_2_available,
41
+ logging,
42
+ replace_return_docstrings,
43
+ )
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
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
+ try:
146
+ if is_flash_attn_2_available():
147
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
148
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
149
+ except:
150
+ pass
151
+
152
+
153
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
154
+ def _get_unpad_data(attention_mask):
155
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
156
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
157
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
158
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
159
+ return (
160
+ indices,
161
+ cu_seqlens,
162
+ max_seqlen_in_batch,
163
+ )
164
+
165
+
166
+ def _trunc_normal_(tensor, mean, std, a, b):
167
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
168
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
169
+ def norm_cdf(x):
170
+ # Computes standard normal cumulative distribution function
171
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
172
+
173
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
174
+ warnings.warn(
175
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
176
+ "The distribution of values may be incorrect.",
177
+ stacklevel=2,
178
+ )
179
+
180
+ # Values are generated by using a truncated uniform distribution and
181
+ # then using the inverse CDF for the normal distribution.
182
+ # Get upper and lower cdf values
183
+ l = norm_cdf((a - mean) / std)
184
+ u = norm_cdf((b - mean) / std)
185
+
186
+ # Uniformly fill tensor with values from [l, u], then translate to
187
+ # [2l-1, 2u-1].
188
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
189
+
190
+ # Use inverse cdf transform for normal distribution to get truncated
191
+ # standard normal
192
+ if tensor.dtype in [torch.float16, torch.bfloat16]:
193
+ # The `erfinv_` op is not (yet?) defined in float16+cpu, bfloat16+gpu
194
+ og_dtype = tensor.dtype
195
+ tensor = tensor.to(torch.float32)
196
+ tensor.erfinv_()
197
+ tensor = tensor.to(og_dtype)
198
+ else:
199
+ tensor.erfinv_()
200
+
201
+ # Transform to proper mean, std
202
+ tensor.mul_(std * math.sqrt(2.0))
203
+ tensor.add_(mean)
204
+
205
+ # Clamp to ensure it's in the proper range
206
+ if tensor.dtype == torch.float16:
207
+ # The `clamp_` op is not (yet?) defined in float16+cpu
208
+ tensor = tensor.to(torch.float32)
209
+ tensor.clamp_(min=a, max=b)
210
+ tensor = tensor.to(torch.float16)
211
+ else:
212
+ tensor.clamp_(min=a, max=b)
213
+
214
+
215
+ def trunc_normal_tf_(
216
+ tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
217
+ ) -> torch.Tensor:
218
+ """Fills the input Tensor with values drawn from a truncated
219
+ normal distribution. The values are effectively drawn from the
220
+ normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
221
+ with values outside :math:`[a, b]` redrawn until they are within
222
+ the bounds. The method used for generating the random values works
223
+ best when :math:`a \\leq \text{mean} \\leq b`.
224
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
225
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
226
+ and the result is subsquently scaled and shifted by the mean and std args.
227
+ Args:
228
+ tensor: an n-dimensional `torch.Tensor`
229
+ mean: the mean of the normal distribution
230
+ std: the standard deviation of the normal distribution
231
+ a: the minimum cutoff value
232
+ b: the maximum cutoff value
233
+ """
234
+ with torch.no_grad():
235
+ _trunc_normal_(tensor, 0, 1.0, a, b)
236
+ tensor.mul_(std).add_(mean)
237
+
238
+
239
+ def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
240
+ fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
241
+ if mode == "fan_in":
242
+ denom = fan_in
243
+ elif mode == "fan_out":
244
+ denom = fan_out
245
+ elif mode == "fan_avg":
246
+ denom = (fan_in + fan_out) / 2
247
+
248
+ variance = scale / denom
249
+
250
+ if distribution == "truncated_normal":
251
+ # constant is stddev of standard normal truncated to (-2, 2)
252
+ trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
253
+ elif distribution == "normal":
254
+ with torch.no_grad():
255
+ tensor.normal_(std=math.sqrt(variance))
256
+ elif distribution == "uniform":
257
+ bound = math.sqrt(3 * variance)
258
+ with torch.no_grad():
259
+ tensor.uniform_(-bound, bound)
260
+ else:
261
+ raise ValueError(f"invalid distribution {distribution}")
262
+
263
+
264
+ def lecun_normal_(tensor):
265
+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
266
+
267
+
268
+ def default_flax_embed_init(tensor):
269
+ variance_scaling_(tensor, mode="fan_in", distribution="normal")
270
+
271
+
272
+ @dataclass
273
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
274
+ class SiglipVisionModelOutput(ModelOutput):
275
+ """
276
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
277
+ Args:
278
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
279
+ The image embeddings obtained by applying the projection layer to the pooler_output.
280
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
281
+ Sequence of hidden-states at the output of the last layer of the model.
282
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
283
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
284
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
285
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
286
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
287
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
288
+ sequence_length)`.
289
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
290
+ heads.
291
+ """
292
+
293
+ image_embeds: Optional[torch.FloatTensor] = None
294
+ last_hidden_state: torch.FloatTensor = None
295
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
296
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
297
+
298
+
299
+ class SiglipVisionEmbeddings(nn.Module):
300
+ def __init__(self, config: SiglipVisionConfig):
301
+ super().__init__()
302
+ self.config = config
303
+ self.embed_dim = config.hidden_size
304
+ self.image_size = config.image_size
305
+ self.patch_size = config.patch_size
306
+
307
+ self.patch_embedding = nn.Conv2d(
308
+ in_channels=config.num_channels,
309
+ out_channels=self.embed_dim,
310
+ kernel_size=self.patch_size,
311
+ stride=self.patch_size,
312
+ padding="valid",
313
+ )
314
+
315
+ self.num_patches_per_side = self.image_size // self.patch_size
316
+ self.num_patches = self.num_patches_per_side**2
317
+ self.num_positions = self.num_patches
318
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
319
+
320
+ def forward(
321
+ self,
322
+ pixel_values: torch.FloatTensor,
323
+ patch_attention_mask: torch.BoolTensor,
324
+ tgt_sizes: Optional[torch.IntTensor] = None,
325
+ ) -> torch.Tensor:
326
+ batch_size = pixel_values.size(0)
327
+
328
+ patch_embeds = self.patch_embedding(pixel_values)
329
+ embeddings = patch_embeds.flatten(2).transpose(1, 2)
330
+
331
+ max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3)
332
+ max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size
333
+ boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side)
334
+ position_ids = torch.full(
335
+ size=(
336
+ batch_size,
337
+ max_nb_patches_h * max_nb_patches_w,
338
+ ),
339
+ fill_value=0,
340
+ )
341
+
342
+ for batch_idx, p_attn_mask in enumerate(patch_attention_mask):
343
+ if tgt_sizes is not None:
344
+ nb_patches_h = tgt_sizes[batch_idx][0]
345
+ nb_patches_w = tgt_sizes[batch_idx][1]
346
+ else:
347
+ nb_patches_h = p_attn_mask[:, 0].sum()
348
+ nb_patches_w = p_attn_mask[0].sum()
349
+
350
+ fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h)
351
+ fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
352
+
353
+ bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
354
+ bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
355
+
356
+ pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
357
+ position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids
358
+
359
+ position_ids = position_ids.to(self.position_embedding.weight.device)
360
+
361
+ embeddings = embeddings + self.position_embedding(position_ids)
362
+ return embeddings
363
+
364
+
365
+ class SiglipAttention(nn.Module):
366
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
367
+
368
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
369
+ def __init__(self, config):
370
+ super().__init__()
371
+ self.config = config
372
+ self.embed_dim = config.hidden_size
373
+ self.num_heads = config.num_attention_heads
374
+ self.head_dim = self.embed_dim // self.num_heads
375
+ if self.head_dim * self.num_heads != self.embed_dim:
376
+ raise ValueError(
377
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
378
+ f" {self.num_heads})."
379
+ )
380
+ self.scale = self.head_dim**-0.5
381
+ self.dropout = config.attention_dropout
382
+
383
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
384
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
385
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
386
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ attention_mask: Optional[torch.Tensor] = None,
392
+ output_attentions: Optional[bool] = False,
393
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
394
+ """Input shape: Batch x Time x Channel"""
395
+
396
+ batch_size, q_len, _ = hidden_states.size()
397
+
398
+ query_states = self.q_proj(hidden_states)
399
+ key_states = self.k_proj(hidden_states)
400
+ value_states = self.v_proj(hidden_states)
401
+
402
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
403
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
404
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
405
+
406
+ k_v_seq_len = key_states.shape[-2]
407
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
408
+
409
+ if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
410
+ raise ValueError(
411
+ f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
412
+ f" {attn_weights.size()}"
413
+ )
414
+
415
+ if attention_mask is not None:
416
+ if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
417
+ raise ValueError(
418
+ f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
419
+ )
420
+ attn_weights = attn_weights + attention_mask
421
+
422
+ # upcast attention to fp32
423
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
424
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
425
+ attn_output = torch.matmul(attn_weights, value_states)
426
+
427
+ if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
428
+ raise ValueError(
429
+ f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
430
+ f" {attn_output.size()}"
431
+ )
432
+
433
+ attn_output = attn_output.transpose(1, 2).contiguous()
434
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
435
+
436
+ attn_output = self.out_proj(attn_output)
437
+
438
+ return attn_output, attn_weights
439
+
440
+
441
+ class SiglipFlashAttention2(SiglipAttention):
442
+ """
443
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
444
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
445
+ flash attention and deal with padding tokens in case the input contains any of them.
446
+ """
447
+
448
+ def __init__(self, *args, **kwargs):
449
+ super().__init__(*args, **kwargs)
450
+ self.is_causal = False # Hack to make sure we don't use a causal mask
451
+
452
+ def forward(
453
+ self,
454
+ hidden_states: torch.Tensor,
455
+ attention_mask: Optional[torch.LongTensor] = None,
456
+ position_ids: Optional[torch.LongTensor] = None,
457
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
458
+ output_attentions: bool = False,
459
+ use_cache: bool = False,
460
+ **kwargs,
461
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
462
+ output_attentions = False
463
+
464
+ bsz, q_len, _ = hidden_states.size()
465
+
466
+ query_states = self.q_proj(hidden_states)
467
+ key_states = self.k_proj(hidden_states)
468
+ value_states = self.v_proj(hidden_states)
469
+
470
+ # Flash attention requires the input to have the shape
471
+ # batch_size x seq_length x head_dim x hidden_dim
472
+ # therefore we just need to keep the original shape
473
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
474
+ key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
475
+ value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
476
+
477
+ kv_seq_len = key_states.shape[-2]
478
+ if past_key_value is not None:
479
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
480
+ # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
481
+ # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
482
+
483
+ # if past_key_value is not None:
484
+ # cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
485
+ # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
486
+
487
+ # 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
488
+ # to be able to avoid many of these transpose/reshape/view.
489
+ query_states = query_states.transpose(1, 2)
490
+ key_states = key_states.transpose(1, 2)
491
+ value_states = value_states.transpose(1, 2)
492
+
493
+ dropout_rate = self.dropout if self.training else 0.0
494
+
495
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
496
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
497
+ # cast them back in the correct dtype just to be sure everything works as expected.
498
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
499
+ # in fp32. (LlamaRMSNorm handles it correctly)
500
+
501
+ input_dtype = query_states.dtype
502
+ if input_dtype == torch.float32:
503
+ if torch.is_autocast_enabled():
504
+ target_dtype = torch.get_autocast_gpu_dtype()
505
+ # Handle the case where the model is quantized
506
+ elif hasattr(self.config, "_pre_quantization_dtype"):
507
+ target_dtype = self.config._pre_quantization_dtype
508
+ else:
509
+ target_dtype = self.q_proj.weight.dtype
510
+
511
+ logger.warning_once(
512
+ "The input hidden states seems to be silently casted in float32, this might be related to the fact"
513
+ " you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
514
+ f" {target_dtype}."
515
+ )
516
+
517
+ query_states = query_states.to(target_dtype)
518
+ key_states = key_states.to(target_dtype)
519
+ value_states = value_states.to(target_dtype)
520
+
521
+ attn_output = self._flash_attention_forward(
522
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
523
+ )
524
+
525
+ attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
526
+ attn_output = self.out_proj(attn_output)
527
+
528
+ if not output_attentions:
529
+ attn_weights = None
530
+
531
+ return attn_output, attn_weights
532
+
533
+ def _flash_attention_forward(
534
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
535
+ ):
536
+ """
537
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
538
+ first unpad the input, then computes the attention scores and pad the final attention scores.
539
+ Args:
540
+ query_states (`torch.Tensor`):
541
+ Input query states to be passed to Flash Attention API
542
+ key_states (`torch.Tensor`):
543
+ Input key states to be passed to Flash Attention API
544
+ value_states (`torch.Tensor`):
545
+ Input value states to be passed to Flash Attention API
546
+ attention_mask (`torch.Tensor`):
547
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
548
+ position of padding tokens and 1 for the position of non-padding tokens.
549
+ dropout (`int`, *optional*):
550
+ Attention dropout
551
+ softmax_scale (`float`, *optional*):
552
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
553
+ """
554
+
555
+ # 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__.
556
+ causal = self.is_causal and query_length != 1
557
+
558
+ # Contains at least one padding token in the sequence
559
+ if attention_mask is not None:
560
+ batch_size = query_states.shape[0]
561
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
562
+ query_states, key_states, value_states, attention_mask, query_length
563
+ )
564
+
565
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
566
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
567
+
568
+ attn_output_unpad = flash_attn_varlen_func(
569
+ query_states,
570
+ key_states,
571
+ value_states,
572
+ cu_seqlens_q=cu_seqlens_q,
573
+ cu_seqlens_k=cu_seqlens_k,
574
+ max_seqlen_q=max_seqlen_in_batch_q,
575
+ max_seqlen_k=max_seqlen_in_batch_k,
576
+ dropout_p=dropout,
577
+ softmax_scale=softmax_scale,
578
+ causal=causal,
579
+ )
580
+
581
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
582
+ else:
583
+ attn_output = flash_attn_func(
584
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
585
+ )
586
+
587
+ return attn_output
588
+
589
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
590
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
591
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
592
+
593
+ key_layer = index_first_axis(
594
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
595
+ )
596
+ value_layer = index_first_axis(
597
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
598
+ )
599
+ if query_length == kv_seq_len:
600
+ query_layer = index_first_axis(
601
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
602
+ )
603
+ cu_seqlens_q = cu_seqlens_k
604
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
605
+ indices_q = indices_k
606
+ elif query_length == 1:
607
+ max_seqlen_in_batch_q = 1
608
+ cu_seqlens_q = torch.arange(
609
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
610
+ ) # There is a memcpy here, that is very bad.
611
+ indices_q = cu_seqlens_q[:-1]
612
+ query_layer = query_layer.squeeze(1)
613
+ else:
614
+ # The -q_len: slice assumes left padding.
615
+ attention_mask = attention_mask[:, -query_length:]
616
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
617
+
618
+ return (
619
+ query_layer,
620
+ key_layer,
621
+ value_layer,
622
+ indices_q,
623
+ (cu_seqlens_q, cu_seqlens_k),
624
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
625
+ )
626
+
627
+
628
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
629
+ class SiglipMLP(nn.Module):
630
+ def __init__(self, config):
631
+ super().__init__()
632
+ self.config = config
633
+ self.activation_fn = ACT2FN[config.hidden_act]
634
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
635
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
636
+
637
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
638
+ hidden_states = self.fc1(hidden_states)
639
+ hidden_states = self.activation_fn(hidden_states)
640
+ hidden_states = self.fc2(hidden_states)
641
+ return hidden_states
642
+
643
+
644
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglip
645
+ class SiglipEncoderLayer(nn.Module):
646
+ def __init__(self, config: SiglipVisionConfig):
647
+ super().__init__()
648
+ self.embed_dim = config.hidden_size
649
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
650
+ self.self_attn = SiglipAttention(config) if not self._use_flash_attention_2 else SiglipFlashAttention2(config)
651
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
652
+ self.mlp = SiglipMLP(config)
653
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
654
+
655
+ def forward(
656
+ self,
657
+ hidden_states: torch.Tensor,
658
+ attention_mask: torch.Tensor,
659
+ output_attentions: Optional[bool] = False,
660
+ ) -> Tuple[torch.FloatTensor]:
661
+ """
662
+ Args:
663
+ hidden_states (`torch.FloatTensor`):
664
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
665
+ attention_mask (`torch.FloatTensor`):
666
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
667
+ output_attentions (`bool`, *optional*, defaults to `False`):
668
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
669
+ returned tensors for more detail.
670
+ """
671
+ residual = hidden_states
672
+
673
+ hidden_states = self.layer_norm1(hidden_states)
674
+ hidden_states, attn_weights = self.self_attn(
675
+ hidden_states=hidden_states,
676
+ attention_mask=attention_mask,
677
+ output_attentions=output_attentions,
678
+ )
679
+ hidden_states = residual + hidden_states
680
+
681
+ residual = hidden_states
682
+ hidden_states = self.layer_norm2(hidden_states)
683
+ hidden_states = self.mlp(hidden_states)
684
+ hidden_states = residual + hidden_states
685
+
686
+ outputs = (hidden_states,)
687
+
688
+ if output_attentions:
689
+ outputs += (attn_weights,)
690
+
691
+ return outputs
692
+
693
+
694
+ class SiglipPreTrainedModel(PreTrainedModel):
695
+ """
696
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
697
+ models.
698
+ """
699
+
700
+ config_class = SiglipVisionConfig
701
+ base_model_prefix = "siglip"
702
+ supports_gradient_checkpointing = True
703
+
704
+ def _init_weights(self, module):
705
+ """Initialize the weights"""
706
+
707
+ if isinstance(module, SiglipVisionEmbeddings):
708
+ width = self.config.hidden_size
709
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
710
+ elif isinstance(module, nn.Embedding):
711
+ default_flax_embed_init(module.weight)
712
+ elif isinstance(module, SiglipAttention):
713
+ nn.init.normal_(module.q_proj.weight)
714
+ nn.init.normal_(module.k_proj.weight)
715
+ nn.init.normal_(module.v_proj.weight)
716
+ nn.init.normal_(module.out_proj.weight)
717
+ nn.init.zeros_(module.q_proj.bias)
718
+ nn.init.zeros_(module.k_proj.bias)
719
+ nn.init.zeros_(module.v_proj.bias)
720
+ nn.init.zeros_(module.out_proj.bias)
721
+ elif isinstance(module, SiglipMLP):
722
+ nn.init.normal_(module.fc1.weight)
723
+ nn.init.normal_(module.fc2.weight)
724
+ nn.init.normal_(module.fc1.bias, std=1e-6)
725
+ nn.init.normal_(module.fc2.bias, std=1e-6)
726
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
727
+ lecun_normal_(module.weight)
728
+ if module.bias is not None:
729
+ nn.init.zeros_(module.bias)
730
+ elif isinstance(module, nn.LayerNorm):
731
+ module.bias.data.zero_()
732
+ module.weight.data.fill_(1.0)
733
+
734
+
735
+ SIGLIP_START_DOCSTRING = r"""
736
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
737
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
738
+ etc.)
739
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
740
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
741
+ and behavior.
742
+ Parameters:
743
+ config ([`SiglipVisionConfig`]): Model configuration class with all the parameters of the model.
744
+ Initializing with a config file does not load the weights associated with the model, only the
745
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
746
+ """
747
+
748
+
749
+ SIGLIP_VISION_INPUTS_DOCSTRING = r"""
750
+ Args:
751
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
752
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
753
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
754
+ output_attentions (`bool`, *optional*):
755
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
756
+ tensors for more detail.
757
+ output_hidden_states (`bool`, *optional*):
758
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
759
+ more detail.
760
+ return_dict (`bool`, *optional*):
761
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
762
+ """
763
+
764
+
765
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglip
766
+ class SiglipEncoder(nn.Module):
767
+ """
768
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
769
+ [`SiglipEncoderLayer`].
770
+ Args:
771
+ config: SiglipConfig
772
+ """
773
+
774
+ def __init__(self, config: SiglipVisionConfig):
775
+ super().__init__()
776
+ self.config = config
777
+ self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
778
+ self.gradient_checkpointing = False
779
+
780
+ # Ignore copy
781
+ def forward(
782
+ self,
783
+ inputs_embeds,
784
+ attention_mask: Optional[torch.Tensor] = None,
785
+ output_attentions: Optional[bool] = None,
786
+ output_hidden_states: Optional[bool] = None,
787
+ return_dict: Optional[bool] = None,
788
+ ) -> Union[Tuple, BaseModelOutput]:
789
+ r"""
790
+ Args:
791
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
792
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
793
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
794
+ than the model's internal embedding lookup matrix.
795
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
796
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
797
+ - 1 for tokens that are **not masked**,
798
+ - 0 for tokens that are **masked**.
799
+ [What are attention masks?](../glossary#attention-mask)
800
+ output_attentions (`bool`, *optional*):
801
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
802
+ returned tensors for more detail.
803
+ output_hidden_states (`bool`, *optional*):
804
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
805
+ for more detail.
806
+ return_dict (`bool`, *optional*):
807
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
808
+ """
809
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
810
+ output_hidden_states = (
811
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
812
+ )
813
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
814
+
815
+ encoder_states = () if output_hidden_states else None
816
+ all_attentions = () if output_attentions else None
817
+
818
+ hidden_states = inputs_embeds
819
+ for encoder_layer in self.layers:
820
+ if output_hidden_states:
821
+ encoder_states = encoder_states + (hidden_states,)
822
+ if self.gradient_checkpointing and self.training:
823
+ layer_outputs = self._gradient_checkpointing_func(
824
+ encoder_layer.__call__,
825
+ hidden_states,
826
+ attention_mask,
827
+ output_attentions,
828
+ )
829
+ else:
830
+ layer_outputs = encoder_layer(
831
+ hidden_states,
832
+ attention_mask,
833
+ output_attentions=output_attentions,
834
+ )
835
+
836
+ hidden_states = layer_outputs[0]
837
+
838
+ if output_attentions:
839
+ all_attentions = all_attentions + (layer_outputs[1],)
840
+
841
+ if output_hidden_states:
842
+ encoder_states = encoder_states + (hidden_states,)
843
+
844
+ if not return_dict:
845
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
846
+ return BaseModelOutput(
847
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
848
+ )
849
+
850
+
851
+ @add_start_docstrings(
852
+ """The vision model from SigLIP without any head or projection on top.""", SIGLIP_START_DOCSTRING
853
+ )
854
+ class SiglipVisionTransformer(SiglipPreTrainedModel):
855
+ config_class = SiglipVisionConfig
856
+ main_input_name = "pixel_values"
857
+ _supports_flash_attn_2 = True
858
+
859
+ def __init__(self, config: SiglipVisionConfig):
860
+ super().__init__(config)
861
+ self.config = config
862
+ embed_dim = config.hidden_size
863
+
864
+ self.embeddings = SiglipVisionEmbeddings(config)
865
+ self.encoder = SiglipEncoder(config)
866
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
867
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
868
+
869
+ # Initialize weights and apply final processing
870
+ self.post_init()
871
+
872
+ def get_input_embeddings(self) -> nn.Module:
873
+ return self.embeddings.patch_embedding
874
+
875
+ @add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
876
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig)
877
+ def forward(
878
+ self,
879
+ pixel_values,
880
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
881
+ tgt_sizes: Optional[torch.IntTensor] = None,
882
+ output_attentions: Optional[bool] = None,
883
+ output_hidden_states: Optional[bool] = None,
884
+ return_dict: Optional[bool] = None,
885
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
886
+ r"""
887
+ Returns:
888
+ """
889
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
890
+ output_hidden_states = (
891
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
892
+ )
893
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
894
+
895
+ batch_size = pixel_values.size(0)
896
+ if patch_attention_mask is None:
897
+ patch_attention_mask = torch.ones(
898
+ size=(
899
+ batch_size,
900
+ pixel_values.size(2) // self.config.patch_size,
901
+ pixel_values.size(3) // self.config.patch_size,
902
+ ),
903
+ dtype=torch.bool,
904
+ device=pixel_values.device,
905
+ )
906
+
907
+ hidden_states = self.embeddings(
908
+ pixel_values=pixel_values, patch_attention_mask=patch_attention_mask, tgt_sizes=tgt_sizes
909
+ )
910
+
911
+ patch_attention_mask = patch_attention_mask.view(batch_size, -1)
912
+ # The call to `_upad_input` in `_flash_attention_forward` is expensive
913
+ # So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
914
+ # avoiding passing the attention_mask, which is equivalent to attending to the full sequence
915
+ if not torch.any(~patch_attention_mask):
916
+ attention_mask = None
917
+ else:
918
+ attention_mask = (
919
+ _prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
920
+ if not self._use_flash_attention_2
921
+ else patch_attention_mask
922
+ )
923
+
924
+ encoder_outputs = self.encoder(
925
+ inputs_embeds=hidden_states,
926
+ attention_mask=attention_mask,
927
+ output_attentions=output_attentions,
928
+ output_hidden_states=output_hidden_states,
929
+ return_dict=return_dict,
930
+ )
931
+
932
+ last_hidden_state = encoder_outputs[0]
933
+ last_hidden_state = self.post_layernorm(last_hidden_state)
934
+
935
+ if not return_dict:
936
+ return (last_hidden_state, None) + encoder_outputs[1:]
937
+
938
+ return BaseModelOutputWithPooling(
939
+ last_hidden_state=last_hidden_state,
940
+ pooler_output=None,
941
+ hidden_states=encoder_outputs.hidden_states,
942
+ attentions=encoder_outputs.attentions,
943
+ )
preprocessor_config.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoImageProcessor": "image_processing_minicpmv.MiniCPMVImageProcessor",
4
+ "AutoProcessor": "processing_minicpmv.MiniCPMVProcessor"
5
+ },
6
+ "im_end": "</image>",
7
+ "im_end_token": "</image>",
8
+ "im_id_end": "</image_id>",
9
+ "im_id_start": "<image_id>",
10
+ "im_start": "<image>",
11
+ "im_start_token": "<image>",
12
+ "image_feature_size": 4,
13
+ "image_processor_type": "MiniCPMVImageProcessor",
14
+ "max_slice_nums": 4,
15
+ "mean": [
16
+ 0.5,
17
+ 0.5,
18
+ 0.5
19
+ ],
20
+ "norm_mean": [
21
+ 0.5,
22
+ 0.5,
23
+ 0.5
24
+ ],
25
+ "norm_std": [
26
+ 0.5,
27
+ 0.5,
28
+ 0.5
29
+ ],
30
+ "patch_size": 2,
31
+ "processor_class": "MiniCPMVProcessor",
32
+ "scale_resolution": 28,
33
+ "slice_end": "</slice>",
34
+ "slice_end_token": "</slice>",
35
+ "slice_mode": true,
36
+ "slice_start": "<slice>",
37
+ "slice_start_token": "<slice>",
38
+ "std": [
39
+ 0.5,
40
+ 0.5,
41
+ 0.5
42
+ ],
43
+ "unk": "<unk>",
44
+ "unk_token": "<unk>",
45
+ "use_image_id": true,
46
+ "version": 2.6
47
+ }
processing_minicpmv.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import re
20
+ from typing import List, Optional, Union
21
+
22
+ import torch
23
+ from transformers.image_utils import ImageInput
24
+ from transformers.processing_utils import ProcessorMixin
25
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
26
+ from transformers.utils import TensorType
27
+
28
+ from .image_processing_minicpmv import MiniCPMVBatchFeature
29
+
30
+
31
+ class MiniCPMVProcessor(ProcessorMixin):
32
+ r"""
33
+ Constructs a MiniCPMV processor which wraps a MiniCPMV image processor and a MiniCPMV tokenizer into a single processor.
34
+
35
+ [`MiniCPMVProcessor`] offers all the functionalities of [`MiniCPMVImageProcessor`] and [`LlamaTokenizerWrapper`]. See the
36
+ [`~MiniCPMVProcessor.__call__`] and [`~MiniCPMVProcessor.decode`] for more information.
37
+
38
+ Args:
39
+ image_processor ([`MiniCPMVImageProcessor`], *optional*):
40
+ The image processor is a required input.
41
+ tokenizer ([`LlamaTokenizerWrapper`], *optional*):
42
+ The tokenizer is a required input.
43
+ """
44
+ attributes = ["image_processor", "tokenizer"]
45
+ image_processor_class = "AutoImageProcessor"
46
+ tokenizer_class = "AutoTokenizer"
47
+
48
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
49
+ super().__init__(image_processor, tokenizer)
50
+ self.version = image_processor.version
51
+
52
+ def __call__(
53
+ self,
54
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
55
+ images: ImageInput = None,
56
+ max_length: Optional[int] = None,
57
+ do_pad: Optional[bool] = True,
58
+ max_slice_nums: int = None,
59
+ use_image_id: bool = None,
60
+ return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
61
+ **kwargs,
62
+ ) -> MiniCPMVBatchFeature:
63
+ image_inputs = None
64
+ if images is not None:
65
+ image_inputs = self.image_processor(
66
+ images, do_pad=do_pad, max_slice_nums=max_slice_nums, return_tensors=return_tensors
67
+ )
68
+ return self._convert_images_texts_to_inputs(
69
+ image_inputs,
70
+ text,
71
+ max_slice_nums=max_slice_nums,
72
+ use_image_id=use_image_id,
73
+ max_length=max_length,
74
+ **kwargs,
75
+ return_tensors=return_tensors,
76
+ )
77
+
78
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
79
+ def batch_decode(self, *args, **kwargs):
80
+ """
81
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
82
+ refer to the docstring of this method for more information.
83
+ """
84
+ output_ids = args[0]
85
+ result_text = []
86
+ for result in output_ids:
87
+ result = result[result != 0]
88
+ if result[0] == self.tokenizer.bos_id:
89
+ result = result[1:]
90
+ if result[-1] == self.tokenizer.eos_id:
91
+ result = result[:-1]
92
+ result_text.append(self.tokenizer.decode(result, *args[1:], **kwargs).strip())
93
+ return result_text
94
+ # return self.tokenizer.batch_decode(*args, **kwargs)
95
+
96
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
97
+ def decode(self, *args, **kwargs):
98
+ """
99
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
100
+ the docstring of this method for more information.
101
+ """
102
+ result = args[0]
103
+ result = result[result != 0]
104
+ if result[0] == self.tokenizer.bos_id:
105
+ result = result[1:]
106
+ if result[-1] == self.tokenizer.eos_id or (
107
+ hasattr(self.tokenizer, "eot_id") and result[-1] == self.tokenizer.eot_id
108
+ ):
109
+ result = result[:-1]
110
+ return self.tokenizer.decode(result, *args[1:], **kwargs).strip()
111
+
112
+ def _convert(self, input_str, max_inp_length: Optional[int] = None):
113
+ if self.version > 2.5 or not getattr(self.tokenizer, "add_bos_token", False):
114
+ input_ids = self.tokenizer.encode(input_str)
115
+ else:
116
+ input_ids = [self.tokenizer.bos_id] + self.tokenizer.encode(input_str)
117
+ if max_inp_length is not None:
118
+ input_ids = input_ids[:max_inp_length]
119
+ input_ids = torch.tensor(input_ids, dtype=torch.int32)
120
+
121
+ start_cond = (input_ids == self.tokenizer.im_start_id) | (input_ids == self.tokenizer.slice_start_id)
122
+ end_cond = (input_ids == self.tokenizer.im_end_id) | (input_ids == self.tokenizer.slice_end_id)
123
+
124
+ image_start_tokens = torch.where(start_cond)[0]
125
+ image_start_tokens += 1
126
+ image_end_tokens = torch.where(end_cond)[0]
127
+
128
+ valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
129
+
130
+ image_bounds = torch.hstack(
131
+ [
132
+ image_start_tokens[:valid_image_nums].unsqueeze(-1),
133
+ image_end_tokens[:valid_image_nums].unsqueeze(-1),
134
+ ]
135
+ )
136
+ return input_ids, image_bounds
137
+
138
+ def _convert_images_texts_to_inputs(
139
+ self,
140
+ images,
141
+ texts: Union[str, List[str]],
142
+ truncation=None,
143
+ max_length=None,
144
+ max_slice_nums=None,
145
+ use_image_id=None,
146
+ return_tensors=None,
147
+ **kwargs,
148
+ ):
149
+ if images is None or not len(images):
150
+ model_inputs = self.tokenizer(
151
+ texts, return_tensors=return_tensors, truncation=truncation, max_length=max_length, **kwargs
152
+ )
153
+ return MiniCPMVBatchFeature(data={**model_inputs})
154
+
155
+ pattern = "(<image>./</image>)"
156
+ images, image_sizes, tgt_sizes = images["pixel_values"], images["image_sizes"], images["tgt_sizes"]
157
+
158
+ if isinstance(texts, str):
159
+ texts = [texts]
160
+ input_ids_list = []
161
+ image_bounds_list = []
162
+ for index, text in enumerate(texts):
163
+ image_tags = re.findall(pattern, text)
164
+ assert len(image_tags) == len(image_sizes[index])
165
+ text_chunks = text.split(pattern)
166
+ final_text = ""
167
+ for i in range(len(image_tags)):
168
+ final_text = (
169
+ final_text
170
+ + text_chunks[i]
171
+ + self.image_processor.get_slice_image_placeholder(
172
+ image_sizes[index][i], i, max_slice_nums, use_image_id
173
+ )
174
+ )
175
+ final_text += text_chunks[-1]
176
+ input_ids, image_bounds = self._convert(final_text, max_length)
177
+ input_ids_list.append(input_ids)
178
+ image_bounds_list.append(image_bounds)
179
+ padded_input_ids, padding_lengths = self.pad(input_ids_list, padding_side="left")
180
+ for i, length in enumerate(padding_lengths):
181
+ image_bounds_list[i] = image_bounds_list[i] + length
182
+ attention_mask = padded_input_ids.ne(0)
183
+
184
+ return MiniCPMVBatchFeature(
185
+ data={
186
+ "input_ids": padded_input_ids,
187
+ "attention_mask": attention_mask,
188
+ "pixel_values": images,
189
+ "image_sizes": image_sizes,
190
+ "image_bound": image_bounds_list,
191
+ "tgt_sizes": tgt_sizes,
192
+ }
193
+ )
194
+
195
+ @property
196
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
197
+ def model_input_names(self):
198
+ tokenizer_input_names = self.tokenizer.model_input_names
199
+ image_processor_input_names = self.image_processor.model_input_names
200
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
201
+
202
+ def pad(self, inputs, max_length=None, padding_value=0, padding_side="left"):
203
+ items = []
204
+ if isinstance(inputs[0], list):
205
+ assert isinstance(inputs[0][0], torch.Tensor)
206
+ for it in inputs:
207
+ for tr in it:
208
+ items.append(tr)
209
+ else:
210
+ assert isinstance(inputs[0], torch.Tensor)
211
+ items = inputs
212
+
213
+ batch_size = len(items)
214
+ shape = items[0].shape
215
+ dim = len(shape)
216
+ assert dim <= 2
217
+ if max_length is None:
218
+ max_length = 0
219
+ max_length = max(max_length, max(item.shape[-1] for item in items))
220
+ min_length = min(item.shape[-1] for item in items)
221
+ dtype = items[0].dtype
222
+
223
+ if dim == 0:
224
+ return torch.stack([item for item in items], dim=0), [0]
225
+ elif dim == 1:
226
+ if max_length == min_length:
227
+ return torch.stack([item for item in items], dim=0), [0] * batch_size
228
+ tensor = torch.zeros((batch_size, max_length), dtype=dtype) + padding_value
229
+ else:
230
+ tensor = torch.zeros((batch_size, max_length, shape[-1]), dtype=dtype) + padding_value
231
+
232
+ padding_length = []
233
+ for i, item in enumerate(items):
234
+ if dim == 1:
235
+ if padding_side == "left":
236
+ tensor[i, -len(item) :] = item.clone()
237
+ else:
238
+ tensor[i, : len(item)] = item.clone()
239
+ elif dim == 2:
240
+ if padding_side == "left":
241
+ tensor[i, -len(item) :, :] = item.clone()
242
+ else:
243
+ tensor[i, : len(item), :] = item.clone()
244
+ padding_length.append(tensor.shape[-1] - len(item))
245
+
246
+ return tensor, padding_length
resampler.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from functools import partial
3
+ from typing import Optional, Tuple, List
4
+
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from torch import Tensor, nn
9
+ from torch.nn.functional import *
10
+ from torch.nn.init import trunc_normal_
11
+ from torch.nn.modules.activation import *
12
+ from transformers.integrations import is_deepspeed_zero3_enabled
13
+
14
+
15
+ def get_2d_sincos_pos_embed(embed_dim, image_size):
16
+ """
17
+ image_size: image_size or (image_height, image_width)
18
+ return:
19
+ pos_embed: [image_height, image_width, embed_dim]
20
+ """
21
+ if isinstance(image_size, int):
22
+ grid_h_size, grid_w_size = image_size, image_size
23
+ else:
24
+ grid_h_size, grid_w_size = image_size[0], image_size[1]
25
+
26
+ grid_h = np.arange(grid_h_size, dtype=np.float32)
27
+ grid_w = np.arange(grid_w_size, dtype=np.float32)
28
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
29
+ grid = np.stack(grid, axis=0)
30
+
31
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
32
+ return pos_embed
33
+
34
+
35
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
36
+ assert embed_dim % 2 == 0
37
+
38
+ # use half of dimensions to encode grid_h
39
+ emb_h = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[0]) # (H, W, D/2)
40
+ emb_w = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[1]) # (H, W, D/2)
41
+
42
+ emb = np.concatenate([emb_h, emb_w], axis=-1) # (H, W, D)
43
+ return emb
44
+
45
+
46
+ def get_1d_sincos_pos_embed_from_grid_new(embed_dim, pos):
47
+ """
48
+ embed_dim: output dimension for each position
49
+ pos: a list of positions to be encoded: size (H, W)
50
+ out: (H, W, D)
51
+ """
52
+ assert embed_dim % 2 == 0
53
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
54
+ omega /= embed_dim / 2.0
55
+ omega = 1.0 / 10000**omega # (D/2,)
56
+
57
+ out = np.einsum("hw,d->hwd", pos, omega) # (H, W, D/2), outer product
58
+
59
+ emb_sin = np.sin(out) # (H, W, D/2)
60
+ emb_cos = np.cos(out) # (H, W, D/2)
61
+
62
+ emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (H, W, D)
63
+ return emb
64
+
65
+
66
+ class Resampler(nn.Module):
67
+ """
68
+ A 2D perceiver-resampler network with one cross attention layers by
69
+ given learnable queries and 2d sincos pos_emb
70
+ Outputs:
71
+ A tensor with the shape of (batch_size, num_queries, embed_dim)
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ num_queries,
77
+ embed_dim,
78
+ num_heads,
79
+ kv_dim=None,
80
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
81
+ adaptive=False,
82
+ max_size=(70, 70),
83
+ ):
84
+ super().__init__()
85
+ self.num_queries = num_queries
86
+ self.embed_dim = embed_dim
87
+ self.num_heads = num_heads
88
+ self.adaptive = adaptive
89
+ self.max_size = max_size
90
+
91
+ self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
92
+
93
+ if kv_dim is not None and kv_dim != embed_dim:
94
+ self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
95
+ else:
96
+ self.kv_proj = nn.Identity()
97
+
98
+ self.attn = MultiheadAttention(embed_dim, num_heads)
99
+ self.ln_q = norm_layer(embed_dim)
100
+ self.ln_kv = norm_layer(embed_dim)
101
+
102
+ self.ln_post = norm_layer(embed_dim)
103
+ self.proj = nn.Parameter((embed_dim**-0.5) * torch.randn(embed_dim, embed_dim))
104
+
105
+ self._set_2d_pos_cache(self.max_size)
106
+
107
+ def _set_2d_pos_cache(self, max_size, device="cpu"):
108
+ if is_deepspeed_zero3_enabled():
109
+ device = "cuda"
110
+ pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.embed_dim, max_size)).float().to(device)
111
+ self.register_buffer("pos_embed", pos_embed, persistent=False)
112
+
113
+ def _adjust_pos_cache(self, tgt_sizes, device):
114
+ max_h = torch.max(tgt_sizes[:, 0])
115
+ max_w = torch.max(tgt_sizes[:, 1])
116
+ if max_h > self.max_size[0] or max_w > self.max_size[1]:
117
+ self.max_size = [max(max_h, self.max_size[0]), max(max_w, self.max_size[1])]
118
+ self._set_2d_pos_cache(self.max_size, device)
119
+
120
+ def _initialize_weights(self, module):
121
+ """
122
+ Initialize the weights if they are not already initialized.
123
+ """
124
+ if getattr(module, "_is_hf_initialized", False):
125
+ return
126
+ self._init_weights(module)
127
+ module._is_hf_initialized = True
128
+
129
+ def _init_weights(self, m):
130
+ if isinstance(m, nn.Linear):
131
+ trunc_normal_(m.weight, std=0.02)
132
+ if isinstance(m, nn.Linear) and m.bias is not None:
133
+ nn.init.constant_(m.bias, 0)
134
+ elif isinstance(m, nn.LayerNorm):
135
+ nn.init.constant_(m.bias, 0)
136
+ nn.init.constant_(m.weight, 1.0)
137
+
138
+ def forward(self, x, tgt_sizes=None):
139
+ assert x.shape[0] == tgt_sizes.shape[0]
140
+ bs = x.shape[0]
141
+
142
+ device = x.device
143
+ dtype = x.dtype
144
+
145
+ patch_len = tgt_sizes[:, 0] * tgt_sizes[:, 1]
146
+
147
+ self._adjust_pos_cache(tgt_sizes, device=device)
148
+
149
+ max_patch_len = torch.max(patch_len)
150
+ key_padding_mask = torch.zeros((bs, max_patch_len), dtype=torch.bool, device=device)
151
+
152
+ pos_embed = []
153
+ for i in range(bs):
154
+ tgt_h, tgt_w = tgt_sizes[i]
155
+ pos_embed.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape((tgt_h * tgt_w, -1)).to(dtype)) # patches * D
156
+ key_padding_mask[i, patch_len[i] :] = True
157
+
158
+ pos_embed = torch.nn.utils.rnn.pad_sequence(pos_embed, batch_first=True, padding_value=0.0).permute(
159
+ 1, 0, 2
160
+ ) # BLD => L * B * D
161
+
162
+ x = self.kv_proj(x) # B * L * D
163
+ x = self.ln_kv(x).permute(1, 0, 2) # L * B * D
164
+
165
+ q = self.ln_q(self.query) # Q * D
166
+
167
+ out = self.attn(
168
+ self._repeat(q, bs), # Q * B * D
169
+ x + pos_embed, # L * B * D + L * B * D
170
+ x,
171
+ key_padding_mask=key_padding_mask,
172
+ )[0]
173
+ # out: Q * B * D
174
+ x = out.permute(1, 0, 2) # B * Q * D
175
+
176
+ x = self.ln_post(x)
177
+ x = x @ self.proj
178
+ return x
179
+
180
+ def _repeat(self, query, N: int):
181
+ return query.unsqueeze(1).repeat(1, N, 1)
182
+
183
+
184
+ class MultiheadAttention(nn.MultiheadAttention):
185
+ def __init__(
186
+ self,
187
+ embed_dim,
188
+ num_heads,
189
+ dropout=0.0,
190
+ bias=True,
191
+ add_bias_kv=False,
192
+ add_zero_attn=False,
193
+ kdim=None,
194
+ vdim=None,
195
+ batch_first=False,
196
+ device=None,
197
+ dtype=None,
198
+ ):
199
+ super().__init__(
200
+ embed_dim, num_heads, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first, device, dtype
201
+ )
202
+
203
+ # rewrite out_proj layer,with nn.Linear
204
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias, device=device, dtype=dtype)
205
+
206
+ def forward(
207
+ self,
208
+ query: Tensor,
209
+ key: Tensor,
210
+ value: Tensor,
211
+ key_padding_mask: Optional[Tensor] = None,
212
+ need_weights: bool = True,
213
+ attn_mask: Optional[Tensor] = None,
214
+ average_attn_weights: bool = True,
215
+ is_causal: bool = False,
216
+ ) -> Tuple[Tensor, Optional[Tensor]]:
217
+ why_not_fast_path = ""
218
+ if (
219
+ (attn_mask is not None and torch.is_floating_point(attn_mask))
220
+ or (key_padding_mask is not None)
221
+ and torch.is_floating_point(key_padding_mask)
222
+ ):
223
+ why_not_fast_path = "floating-point masks are not supported for fast path."
224
+
225
+ is_batched = query.dim() == 3
226
+
227
+ key_padding_mask = _canonical_mask(
228
+ mask=key_padding_mask,
229
+ mask_name="key_padding_mask",
230
+ other_type=F._none_or_dtype(attn_mask),
231
+ other_name="attn_mask",
232
+ target_type=query.dtype,
233
+ )
234
+
235
+ attn_mask = _canonical_mask(
236
+ mask=attn_mask,
237
+ mask_name="attn_mask",
238
+ other_type=None,
239
+ other_name="",
240
+ target_type=query.dtype,
241
+ check_other=False,
242
+ )
243
+
244
+ if not is_batched:
245
+ why_not_fast_path = f"input not batched; expected query.dim() of 3 but got {query.dim()}"
246
+ elif query is not key or key is not value:
247
+ # When lifting this restriction, don't forget to either
248
+ # enforce that the dtypes all match or test cases where
249
+ # they don't!
250
+ why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
251
+ elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
252
+ why_not_fast_path = (
253
+ f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
254
+ )
255
+ elif self.in_proj_weight is None:
256
+ why_not_fast_path = "in_proj_weight was None"
257
+ elif query.dtype != self.in_proj_weight.dtype:
258
+ # this case will fail anyway, but at least they'll get a useful error message.
259
+ why_not_fast_path = (
260
+ f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
261
+ )
262
+ elif self.training:
263
+ why_not_fast_path = "training is enabled"
264
+ elif (self.num_heads % 2) != 0:
265
+ why_not_fast_path = "self.num_heads is not even"
266
+ elif not self.batch_first:
267
+ why_not_fast_path = "batch_first was not True"
268
+ elif self.bias_k is not None:
269
+ why_not_fast_path = "self.bias_k was not None"
270
+ elif self.bias_v is not None:
271
+ why_not_fast_path = "self.bias_v was not None"
272
+ elif self.add_zero_attn:
273
+ why_not_fast_path = "add_zero_attn was enabled"
274
+ elif not self._qkv_same_embed_dim:
275
+ why_not_fast_path = "_qkv_same_embed_dim was not True"
276
+ elif query.is_nested and (key_padding_mask is not None or attn_mask is not None):
277
+ why_not_fast_path = "supplying both src_key_padding_mask and src_mask at the same time \
278
+ is not supported with NestedTensor input"
279
+ elif torch.is_autocast_enabled():
280
+ why_not_fast_path = "autocast is enabled"
281
+
282
+ if not why_not_fast_path:
283
+ tensor_args = (
284
+ query,
285
+ key,
286
+ value,
287
+ self.in_proj_weight,
288
+ self.in_proj_bias,
289
+ self.out_proj.weight,
290
+ self.out_proj.bias,
291
+ )
292
+ # We have to use list comprehensions below because TorchScript does not support
293
+ # generator expressions.
294
+ if torch.overrides.has_torch_function(tensor_args):
295
+ why_not_fast_path = "some Tensor argument has_torch_function"
296
+ elif _is_make_fx_tracing():
297
+ why_not_fast_path = "we are running make_fx tracing"
298
+ elif not all(_check_arg_device(x) for x in tensor_args):
299
+ why_not_fast_path = (
300
+ "some Tensor argument's device is neither one of "
301
+ f"cpu, cuda or {torch.utils.backend_registration._privateuse1_backend_name}"
302
+ )
303
+ elif torch.is_grad_enabled() and any(_arg_requires_grad(x) for x in tensor_args):
304
+ why_not_fast_path = (
305
+ "grad is enabled and at least one of query or the "
306
+ "input/output projection weights or biases requires_grad"
307
+ )
308
+ if not why_not_fast_path:
309
+ merged_mask, mask_type = self.merge_masks(attn_mask, key_padding_mask, query)
310
+
311
+ if self.in_proj_bias is not None and self.in_proj_weight is not None:
312
+ return torch._native_multi_head_attention(
313
+ query,
314
+ key,
315
+ value,
316
+ self.embed_dim,
317
+ self.num_heads,
318
+ self.in_proj_weight,
319
+ self.in_proj_bias,
320
+ self.out_proj.weight,
321
+ self.out_proj.bias,
322
+ merged_mask,
323
+ need_weights,
324
+ average_attn_weights,
325
+ mask_type,
326
+ )
327
+
328
+ any_nested = query.is_nested or key.is_nested or value.is_nested
329
+ assert not any_nested, (
330
+ "MultiheadAttention does not support NestedTensor outside of its fast path. "
331
+ + f"The fast path was not hit because {why_not_fast_path}"
332
+ )
333
+
334
+ if self.batch_first and is_batched:
335
+ # make sure that the transpose op does not affect the "is" property
336
+ if key is value:
337
+ if query is key:
338
+ query = key = value = query.transpose(1, 0)
339
+ else:
340
+ query, key = (x.transpose(1, 0) for x in (query, key))
341
+ value = key
342
+ else:
343
+ query, key, value = (x.transpose(1, 0) for x in (query, key, value))
344
+
345
+ if not self._qkv_same_embed_dim:
346
+ attn_output, attn_output_weights = self.multi_head_attention_forward(
347
+ query,
348
+ key,
349
+ value,
350
+ self.embed_dim,
351
+ self.num_heads,
352
+ self.in_proj_weight,
353
+ self.in_proj_bias,
354
+ self.bias_k,
355
+ self.bias_v,
356
+ self.add_zero_attn,
357
+ self.dropout,
358
+ self.out_proj.weight,
359
+ self.out_proj.bias,
360
+ training=self.training,
361
+ key_padding_mask=key_padding_mask,
362
+ need_weights=need_weights,
363
+ attn_mask=attn_mask,
364
+ use_separate_proj_weight=True,
365
+ q_proj_weight=self.q_proj_weight,
366
+ k_proj_weight=self.k_proj_weight,
367
+ v_proj_weight=self.v_proj_weight,
368
+ average_attn_weights=average_attn_weights,
369
+ is_causal=is_causal,
370
+ )
371
+ else:
372
+ attn_output, attn_output_weights = self.multi_head_attention_forward(
373
+ query,
374
+ key,
375
+ value,
376
+ self.embed_dim,
377
+ self.num_heads,
378
+ self.in_proj_weight,
379
+ self.in_proj_bias,
380
+ self.bias_k,
381
+ self.bias_v,
382
+ self.add_zero_attn,
383
+ self.dropout,
384
+ self.out_proj.weight,
385
+ self.out_proj.bias,
386
+ training=self.training,
387
+ key_padding_mask=key_padding_mask,
388
+ need_weights=need_weights,
389
+ attn_mask=attn_mask,
390
+ average_attn_weights=average_attn_weights,
391
+ is_causal=is_causal,
392
+ )
393
+ if self.batch_first and is_batched:
394
+ return attn_output.transpose(1, 0), attn_output_weights
395
+ else:
396
+ return attn_output, attn_output_weights
397
+
398
+ def multi_head_attention_forward(
399
+ self,
400
+ query: Tensor,
401
+ key: Tensor,
402
+ value: Tensor,
403
+ embed_dim_to_check: int,
404
+ num_heads: int,
405
+ in_proj_weight: Optional[Tensor],
406
+ in_proj_bias: Optional[Tensor],
407
+ bias_k: Optional[Tensor],
408
+ bias_v: Optional[Tensor],
409
+ add_zero_attn: bool,
410
+ dropout_p: float,
411
+ out_proj_weight: Tensor,
412
+ out_proj_bias: Optional[Tensor],
413
+ training: bool = True,
414
+ key_padding_mask: Optional[Tensor] = None,
415
+ need_weights: bool = True,
416
+ attn_mask: Optional[Tensor] = None,
417
+ use_separate_proj_weight: bool = False,
418
+ q_proj_weight: Optional[Tensor] = None,
419
+ k_proj_weight: Optional[Tensor] = None,
420
+ v_proj_weight: Optional[Tensor] = None,
421
+ static_k: Optional[Tensor] = None,
422
+ static_v: Optional[Tensor] = None,
423
+ average_attn_weights: bool = True,
424
+ is_causal: bool = False,
425
+ ) -> Tuple[Tensor, Optional[Tensor]]:
426
+ tens_ops = (query, key, value, in_proj_weight, in_proj_bias, bias_k, bias_v, out_proj_weight, out_proj_bias)
427
+
428
+ is_batched = _mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
429
+
430
+ # For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
431
+ # is batched, run the computation and before returning squeeze the
432
+ # batch dimension so that the output doesn't carry this temporary batch dimension.
433
+ if not is_batched:
434
+ # unsqueeze if the input is unbatched
435
+ query = query.unsqueeze(1)
436
+ key = key.unsqueeze(1)
437
+ value = value.unsqueeze(1)
438
+ if key_padding_mask is not None:
439
+ key_padding_mask = key_padding_mask.unsqueeze(0)
440
+
441
+ # set up shape vars
442
+ tgt_len, bsz, embed_dim = query.shape
443
+ src_len, _, _ = key.shape
444
+
445
+ key_padding_mask = _canonical_mask(
446
+ mask=key_padding_mask,
447
+ mask_name="key_padding_mask",
448
+ other_type=_none_or_dtype(attn_mask),
449
+ other_name="attn_mask",
450
+ target_type=query.dtype,
451
+ )
452
+
453
+ if is_causal and attn_mask is None:
454
+ raise RuntimeError(
455
+ "Need attn_mask if specifying the is_causal hint. "
456
+ "You may use the Transformer module method "
457
+ "`generate_square_subsequent_mask` to create this mask."
458
+ )
459
+
460
+ if is_causal and key_padding_mask is None and not need_weights:
461
+ # when we have a kpm or need weights, we need attn_mask
462
+ # Otherwise, we use the is_causal hint go as is_causal
463
+ # indicator to SDPA.
464
+ attn_mask = None
465
+ else:
466
+ attn_mask = _canonical_mask(
467
+ mask=attn_mask,
468
+ mask_name="attn_mask",
469
+ other_type=None,
470
+ other_name="",
471
+ target_type=query.dtype,
472
+ check_other=False,
473
+ )
474
+
475
+ if key_padding_mask is not None:
476
+ # We have the attn_mask, and use that to merge kpm into it.
477
+ # Turn off use of is_causal hint, as the merged mask is no
478
+ # longer causal.
479
+ is_causal = False
480
+
481
+ assert (
482
+ embed_dim == embed_dim_to_check
483
+ ), f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
484
+ if isinstance(embed_dim, torch.Tensor):
485
+ # embed_dim can be a tensor when JIT tracing
486
+ head_dim = embed_dim.div(num_heads, rounding_mode="trunc")
487
+ else:
488
+ head_dim = embed_dim // num_heads
489
+ assert head_dim * num_heads == embed_dim, f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
490
+ if use_separate_proj_weight:
491
+ # allow MHA to have different embedding dimensions when separate projection weights are used
492
+ assert (
493
+ key.shape[:2] == value.shape[:2]
494
+ ), f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
495
+ else:
496
+ assert key.shape == value.shape, f"key shape {key.shape} does not match value shape {value.shape}"
497
+
498
+ #
499
+ # compute in-projection
500
+ #
501
+ if not use_separate_proj_weight:
502
+ assert in_proj_weight is not None, "use_separate_proj_weight is False but in_proj_weight is None"
503
+ q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
504
+ else:
505
+ assert q_proj_weight is not None, "use_separate_proj_weight is True but q_proj_weight is None"
506
+ assert k_proj_weight is not None, "use_separate_proj_weight is True but k_proj_weight is None"
507
+ assert v_proj_weight is not None, "use_separate_proj_weight is True but v_proj_weight is None"
508
+ if in_proj_bias is None:
509
+ b_q = b_k = b_v = None
510
+ else:
511
+ b_q, b_k, b_v = in_proj_bias.chunk(3)
512
+ q, k, v = _in_projection(query, key, value, q_proj_weight, k_proj_weight, v_proj_weight, b_q, b_k, b_v)
513
+
514
+ # prep attention mask
515
+
516
+ if attn_mask is not None:
517
+ # ensure attn_mask's dim is 3
518
+ if attn_mask.dim() == 2:
519
+ correct_2d_size = (tgt_len, src_len)
520
+ if attn_mask.shape != correct_2d_size:
521
+ raise RuntimeError(
522
+ f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}."
523
+ )
524
+ attn_mask = attn_mask.unsqueeze(0)
525
+ elif attn_mask.dim() == 3:
526
+ correct_3d_size = (bsz * num_heads, tgt_len, src_len)
527
+ if attn_mask.shape != correct_3d_size:
528
+ raise RuntimeError(
529
+ f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}."
530
+ )
531
+ else:
532
+ raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
533
+
534
+ # add bias along batch dimension (currently second)
535
+ if bias_k is not None and bias_v is not None:
536
+ assert static_k is None, "bias cannot be added to static key."
537
+ assert static_v is None, "bias cannot be added to static value."
538
+ k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
539
+ v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
540
+ if attn_mask is not None:
541
+ attn_mask = pad(attn_mask, (0, 1))
542
+ if key_padding_mask is not None:
543
+ key_padding_mask = pad(key_padding_mask, (0, 1))
544
+ else:
545
+ assert bias_k is None
546
+ assert bias_v is None
547
+
548
+ #
549
+ # reshape q, k, v for multihead attention and make em batch first
550
+ #
551
+ q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
552
+ if static_k is None:
553
+ k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
554
+ else:
555
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
556
+ assert (
557
+ static_k.size(0) == bsz * num_heads
558
+ ), f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
559
+ assert (
560
+ static_k.size(2) == head_dim
561
+ ), f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
562
+ k = static_k
563
+ if static_v is None:
564
+ v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
565
+ else:
566
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
567
+ assert (
568
+ static_v.size(0) == bsz * num_heads
569
+ ), f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
570
+ assert (
571
+ static_v.size(2) == head_dim
572
+ ), f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
573
+ v = static_v
574
+
575
+ # add zero attention along batch dimension (now first)
576
+ if add_zero_attn:
577
+ zero_attn_shape = (bsz * num_heads, 1, head_dim)
578
+ k = torch.cat([k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1)
579
+ v = torch.cat([v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1)
580
+ if attn_mask is not None:
581
+ attn_mask = pad(attn_mask, (0, 1))
582
+ if key_padding_mask is not None:
583
+ key_padding_mask = pad(key_padding_mask, (0, 1))
584
+
585
+ # update source sequence length after adjustments
586
+ src_len = k.size(1)
587
+
588
+ # merge key padding and attention masks
589
+ if key_padding_mask is not None:
590
+ assert key_padding_mask.shape == (
591
+ bsz,
592
+ src_len,
593
+ ), f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
594
+ key_padding_mask = (
595
+ key_padding_mask.view(bsz, 1, 1, src_len)
596
+ .expand(-1, num_heads, -1, -1)
597
+ .reshape(bsz * num_heads, 1, src_len)
598
+ )
599
+ if attn_mask is None:
600
+ attn_mask = key_padding_mask
601
+ else:
602
+ attn_mask = attn_mask + key_padding_mask
603
+
604
+ # adjust dropout probability
605
+ if not training:
606
+ dropout_p = 0.0
607
+
608
+ #
609
+ # (deep breath) calculate attention and out projection
610
+ #
611
+
612
+ if need_weights:
613
+ B, Nt, E = q.shape
614
+ q_scaled = q / math.sqrt(E)
615
+
616
+ assert not (is_causal and attn_mask is None), "FIXME: is_causal not implemented for need_weights"
617
+
618
+ if attn_mask is not None:
619
+ attn_output_weights = torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1))
620
+ else:
621
+ attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
622
+ attn_output_weights = softmax(attn_output_weights, dim=-1)
623
+ if dropout_p > 0.0:
624
+ attn_output_weights = dropout(attn_output_weights, p=dropout_p)
625
+
626
+ attn_output = torch.bmm(attn_output_weights, v)
627
+
628
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
629
+ attn_output = self.out_proj(attn_output)
630
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
631
+
632
+ # optionally average attention weights over heads
633
+ attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
634
+ if average_attn_weights:
635
+ attn_output_weights = attn_output_weights.mean(dim=1)
636
+
637
+ if not is_batched:
638
+ # squeeze the output if input was unbatched
639
+ attn_output = attn_output.squeeze(1)
640
+ attn_output_weights = attn_output_weights.squeeze(0)
641
+ return attn_output, attn_output_weights
642
+ else:
643
+ # attn_mask can be either (L,S) or (N*num_heads, L, S)
644
+ # if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
645
+ # in order to match the input for SDPA of (N, num_heads, L, S)
646
+ if attn_mask is not None:
647
+ if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
648
+ attn_mask = attn_mask.unsqueeze(0)
649
+ else:
650
+ attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
651
+
652
+ q = q.view(bsz, num_heads, tgt_len, head_dim)
653
+ k = k.view(bsz, num_heads, src_len, head_dim)
654
+ v = v.view(bsz, num_heads, src_len, head_dim)
655
+
656
+ attn_output = F.scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
657
+ attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
658
+
659
+ attn_output = self.out_proj(attn_output)
660
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
661
+ if not is_batched:
662
+ # squeeze the output if input was unbatched
663
+ attn_output = attn_output.squeeze(1)
664
+ return attn_output, None
665
+
666
+
667
+ def _mha_shape_check(
668
+ query: Tensor,
669
+ key: Tensor,
670
+ value: Tensor,
671
+ key_padding_mask: Optional[Tensor],
672
+ attn_mask: Optional[Tensor],
673
+ num_heads: int,
674
+ ):
675
+ # Verifies the expected shape for `query, `key`, `value`, `key_padding_mask` and `attn_mask`
676
+ # and returns if the input is batched or not.
677
+ # Raises an error if `query` is not 2-D (unbatched) or 3-D (batched) tensor.
678
+
679
+ # Shape check.
680
+ if query.dim() == 3:
681
+ # Batched Inputs
682
+ is_batched = True
683
+ assert key.dim() == 3 and value.dim() == 3, (
684
+ "For batched (3-D) `query`, expected `key` and `value` to be 3-D"
685
+ f" but found {key.dim()}-D and {value.dim()}-D tensors respectively"
686
+ )
687
+ if key_padding_mask is not None:
688
+ assert key_padding_mask.dim() == 2, (
689
+ "For batched (3-D) `query`, expected `key_padding_mask` to be `None` or 2-D"
690
+ f" but found {key_padding_mask.dim()}-D tensor instead"
691
+ )
692
+ if attn_mask is not None:
693
+ assert attn_mask.dim() in (2, 3), (
694
+ "For batched (3-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
695
+ f" but found {attn_mask.dim()}-D tensor instead"
696
+ )
697
+ elif query.dim() == 2:
698
+ # Unbatched Inputs
699
+ is_batched = False
700
+ assert key.dim() == 2 and value.dim() == 2, (
701
+ "For unbatched (2-D) `query`, expected `key` and `value` to be 2-D"
702
+ f" but found {key.dim()}-D and {value.dim()}-D tensors respectively"
703
+ )
704
+
705
+ if key_padding_mask is not None:
706
+ assert key_padding_mask.dim() == 1, (
707
+ "For unbatched (2-D) `query`, expected `key_padding_mask` to be `None` or 1-D"
708
+ f" but found {key_padding_mask.dim()}-D tensor instead"
709
+ )
710
+
711
+ if attn_mask is not None:
712
+ assert attn_mask.dim() in (2, 3), (
713
+ "For unbatched (2-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
714
+ f" but found {attn_mask.dim()}-D tensor instead"
715
+ )
716
+ if attn_mask.dim() == 3:
717
+ expected_shape = (num_heads, query.shape[0], key.shape[0])
718
+ assert (
719
+ attn_mask.shape == expected_shape
720
+ ), f"Expected `attn_mask` shape to be {expected_shape} but got {attn_mask.shape}"
721
+ else:
722
+ raise AssertionError(
723
+ f"query should be unbatched 2D or batched 3D tensor but received {query.dim()}-D query tensor"
724
+ )
725
+
726
+ return is_batched
727
+
728
+
729
+ def _canonical_mask(
730
+ mask: Optional[Tensor],
731
+ mask_name: str,
732
+ other_type: Optional[DType],
733
+ other_name: str,
734
+ target_type: DType,
735
+ check_other: bool = True,
736
+ ) -> Optional[Tensor]:
737
+ if mask is not None:
738
+ _mask_dtype = mask.dtype
739
+ _mask_is_float = torch.is_floating_point(mask)
740
+ if _mask_dtype != torch.bool and not _mask_is_float:
741
+ raise AssertionError(f"only bool and floating types of {mask_name} are supported")
742
+ if check_other and other_type is not None:
743
+ if _mask_dtype != other_type:
744
+ warnings.warn(
745
+ f"Support for mismatched {mask_name} and {other_name} "
746
+ "is deprecated. Use same type for both instead."
747
+ )
748
+ if not _mask_is_float:
749
+ mask = torch.zeros_like(mask, dtype=target_type).masked_fill_(mask, float("-inf"))
750
+ return mask
751
+
752
+
753
+ def _none_or_dtype(input: Optional[Tensor]) -> Optional[DType]:
754
+ if input is None:
755
+ return None
756
+ elif isinstance(input, torch.Tensor):
757
+ return input.dtype
758
+ raise RuntimeError("input to _none_or_dtype() must be None or torch.Tensor")
759
+
760
+
761
+ def _in_projection_packed(
762
+ q: Tensor,
763
+ k: Tensor,
764
+ v: Tensor,
765
+ w: Tensor,
766
+ b: Optional[Tensor] = None,
767
+ ) -> List[Tensor]:
768
+ r"""
769
+ Performs the in-projection step of the attention operation, using packed weights.
770
+ Output is a triple containing projection tensors for query, key and value.
771
+ Args:
772
+ q, k, v: query, key and value tensors to be projected. For self-attention,
773
+ these are typically the same tensor; for encoder-decoder attention,
774
+ k and v are typically the same tensor. (We take advantage of these
775
+ identities for performance if they are present.) Regardless, q, k and v
776
+ must share a common embedding dimension; otherwise their shapes may vary.
777
+ w: projection weights for q, k and v, packed into a single tensor. Weights
778
+ are packed along dimension 0, in q, k, v order.
779
+ b: optional projection biases for q, k and v, packed into a single tensor
780
+ in q, k, v order.
781
+ Shape:
782
+ Inputs:
783
+ - q: :math:`(..., E)` where E is the embedding dimension
784
+ - k: :math:`(..., E)` where E is the embedding dimension
785
+ - v: :math:`(..., E)` where E is the embedding dimension
786
+ - w: :math:`(E * 3, E)` where E is the embedding dimension
787
+ - b: :math:`E * 3` where E is the embedding dimension
788
+ Output:
789
+ - in output list :math:`[q', k', v']`, each output tensor will have the
790
+ same shape as the corresponding input tensor.
791
+ """
792
+ E = q.size(-1)
793
+ if k is v:
794
+ if q is k:
795
+ # self-attention
796
+ proj = linear(q, w, b)
797
+ # reshape to 3, E and not E, 3 is deliberate for better memory coalescing and keeping same order as chunk()
798
+ proj = proj.unflatten(-1, (3, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
799
+ return proj[0], proj[1], proj[2]
800
+ else:
801
+ # encoder-decoder attention
802
+ w_q, w_kv = w.split([E, E * 2])
803
+ if b is None:
804
+ b_q = b_kv = None
805
+ else:
806
+ b_q, b_kv = b.split([E, E * 2])
807
+ q_proj = linear(q, w_q, b_q)
808
+ kv_proj = linear(k, w_kv, b_kv)
809
+ # reshape to 2, E and not E, 2 is deliberate for better memory coalescing and keeping same order as chunk()
810
+ kv_proj = kv_proj.unflatten(-1, (2, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
811
+ return (q_proj, kv_proj[0], kv_proj[1])
812
+ else:
813
+ w_q, w_k, w_v = w.chunk(3)
814
+ if b is None:
815
+ b_q = b_k = b_v = None
816
+ else:
817
+ b_q, b_k, b_v = b.chunk(3)
818
+ return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
819
+
820
+
821
+ def _in_projection(
822
+ q: Tensor,
823
+ k: Tensor,
824
+ v: Tensor,
825
+ w_q: Tensor,
826
+ w_k: Tensor,
827
+ w_v: Tensor,
828
+ b_q: Optional[Tensor] = None,
829
+ b_k: Optional[Tensor] = None,
830
+ b_v: Optional[Tensor] = None,
831
+ ) -> Tuple[Tensor, Tensor, Tensor]:
832
+ r"""
833
+ Performs the in-projection step of the attention operation. This is simply
834
+ a triple of linear projections, with shape constraints on the weights which
835
+ ensure embedding dimension uniformity in the projected outputs.
836
+ Output is a triple containing projection tensors for query, key and value.
837
+ Args:
838
+ q, k, v: query, key and value tensors to be projected.
839
+ w_q, w_k, w_v: weights for q, k and v, respectively.
840
+ b_q, b_k, b_v: optional biases for q, k and v, respectively.
841
+ Shape:
842
+ Inputs:
843
+ - q: :math:`(Qdims..., Eq)` where Eq is the query embedding dimension and Qdims are any
844
+ number of leading dimensions.
845
+ - k: :math:`(Kdims..., Ek)` where Ek is the key embedding dimension and Kdims are any
846
+ number of leading dimensions.
847
+ - v: :math:`(Vdims..., Ev)` where Ev is the value embedding dimension and Vdims are any
848
+ number of leading dimensions.
849
+ - w_q: :math:`(Eq, Eq)`
850
+ - w_k: :math:`(Eq, Ek)`
851
+ - w_v: :math:`(Eq, Ev)`
852
+ - b_q: :math:`(Eq)`
853
+ - b_k: :math:`(Eq)`
854
+ - b_v: :math:`(Eq)`
855
+ Output: in output triple :math:`(q', k', v')`,
856
+ - q': :math:`[Qdims..., Eq]`
857
+ - k': :math:`[Kdims..., Eq]`
858
+ - v': :math:`[Vdims..., Eq]`
859
+ """
860
+ Eq, Ek, Ev = q.size(-1), k.size(-1), v.size(-1)
861
+ assert w_q.shape == (Eq, Eq), f"expecting query weights shape of {(Eq, Eq)}, but got {w_q.shape}"
862
+ assert w_k.shape == (Eq, Ek), f"expecting key weights shape of {(Eq, Ek)}, but got {w_k.shape}"
863
+ assert w_v.shape == (Eq, Ev), f"expecting value weights shape of {(Eq, Ev)}, but got {w_v.shape}"
864
+ assert b_q is None or b_q.shape == (Eq,), f"expecting query bias shape of {(Eq,)}, but got {b_q.shape}"
865
+ assert b_k is None or b_k.shape == (Eq,), f"expecting key bias shape of {(Eq,)}, but got {b_k.shape}"
866
+ assert b_v is None or b_v.shape == (Eq,), f"expecting value bias shape of {(Eq,)}, but got {b_v.shape}"
867
+ return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
special_tokens_map.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<image>",
4
+ "</image>",
5
+ "<ref>",
6
+ "</ref>",
7
+ "<box>",
8
+ "</box>",
9
+ "<quad>",
10
+ "</quad>",
11
+ "<point>",
12
+ "</point>",
13
+ "<slice>",
14
+ "</slice>",
15
+ "<image_id>",
16
+ "</image_id>",
17
+ "<|reserved_special_token_0|>",
18
+ "<|reserved_special_token_1|>",
19
+ "<|reserved_special_token_2|>",
20
+ "<|reserved_special_token_3|>",
21
+ "<|reserved_special_token_4|>",
22
+ "<|reserved_special_token_5|>"
23
+ ],
24
+ "bos_token": {
25
+ "content": "<|im_start|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "eos_token": {
32
+ "content": "<|im_end|>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ },
38
+ "pad_token": {
39
+ "content": "<|endoftext|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false
44
+ },
45
+ "unk_token": {
46
+ "content": "<unk>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false
51
+ }
52
+ }
tokenization_minicpmv_fast.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.models.qwen2 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:9de76ce95f90e336b4d2b0ec11d37f3d5404f2dad0f7ac95298405474b2a3a90
3
+ size 11422257
tokenizer_config.json ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "128244": {
5
+ "content": "<unk>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151643": {
13
+ "content": "<|endoftext|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151644": {
21
+ "content": "<|im_start|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "151645": {
29
+ "content": "<|im_end|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "151646": {
37
+ "content": "<image>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "151647": {
45
+ "content": "</image>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "151648": {
53
+ "content": "<ref>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "151649": {
61
+ "content": "</ref>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "151650": {
69
+ "content": "<box>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "151651": {
77
+ "content": "</box>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "151652": {
85
+ "content": "<quad>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "151653": {
93
+ "content": "</quad>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "151654": {
101
+ "content": "<point>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "151655": {
109
+ "content": "</point>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ },
116
+ "151656": {
117
+ "content": "<slice>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": true
123
+ },
124
+ "151657": {
125
+ "content": "</slice>",
126
+ "lstrip": false,
127
+ "normalized": false,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": true
131
+ },
132
+ "151658": {
133
+ "content": "<image_id>",
134
+ "lstrip": false,
135
+ "normalized": false,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": true
139
+ },
140
+ "151659": {
141
+ "content": "</image_id>",
142
+ "lstrip": false,
143
+ "normalized": false,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": true
147
+ },
148
+ "151660": {
149
+ "content": "<|reserved_special_token_0|>",
150
+ "lstrip": false,
151
+ "normalized": false,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": true
155
+ },
156
+ "151661": {
157
+ "content": "<|reserved_special_token_1|>",
158
+ "lstrip": false,
159
+ "normalized": false,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": true
163
+ },
164
+ "151662": {
165
+ "content": "<|reserved_special_token_2|>",
166
+ "lstrip": false,
167
+ "normalized": false,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": true
171
+ },
172
+ "151663": {
173
+ "content": "<|reserved_special_token_3|>",
174
+ "lstrip": false,
175
+ "normalized": false,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": true
179
+ },
180
+ "151664": {
181
+ "content": "<|reserved_special_token_4|>",
182
+ "lstrip": false,
183
+ "normalized": false,
184
+ "rstrip": false,
185
+ "single_word": false,
186
+ "special": true
187
+ },
188
+ "151665": {
189
+ "content": "<|reserved_special_token_5|>",
190
+ "lstrip": false,
191
+ "normalized": false,
192
+ "rstrip": false,
193
+ "single_word": false,
194
+ "special": true
195
+ }
196
+ },
197
+ "additional_special_tokens": [
198
+ "<image>",
199
+ "</image>",
200
+ "<ref>",
201
+ "</ref>",
202
+ "<box>",
203
+ "</box>",
204
+ "<quad>",
205
+ "</quad>",
206
+ "<point>",
207
+ "</point>",
208
+ "<slice>",
209
+ "</slice>",
210
+ "<image_id>",
211
+ "</image_id>",
212
+ "<|reserved_special_token_0|>",
213
+ "<|reserved_special_token_1|>",
214
+ "<|reserved_special_token_2|>",
215
+ "<|reserved_special_token_3|>",
216
+ "<|reserved_special_token_4|>",
217
+ "<|reserved_special_token_5|>"
218
+ ],
219
+ "auto_map": {
220
+ "AutoTokenizer": [
221
+ "tokenization_minicpmv_fast.MiniCPMVTokenizerFast",
222
+ null
223
+ ]
224
+ },
225
+ "bos_token": "<|im_start|>",
226
+ "chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
227
+ "clean_up_tokenization_spaces": false,
228
+ "eos_token": "<|im_end|>",
229
+ "errors": "replace",
230
+ "model_max_length": 1000000000000000019884624838656,
231
+ "pad_token": "<|endoftext|>",
232
+ "processor_class": "MiniCPMVProcessor",
233
+ "split_special_tokens": false,
234
+ "tokenizer_class": "MiniCPMVTokenizer",
235
+ "unk_token": "<unk>"
236
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff