snake7gun commited on
Commit
062c88d
·
verified ·
1 Parent(s): 957a005

Upload folder using huggingface_hub

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