Feature Extraction
Safetensors
English
minicpmv
VisRAG
custom_code
tcy5156 commited on
Commit
c7a0be3
0 Parent(s):

upload weights

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ datasets:
4
+ - test-tcy/VisRAG-Ret-Train-In-domain-data
5
+ - test-tcy/VisRAG-Ret-Train-Synthetic-data
6
+ language:
7
+ - en
8
+ base_model:
9
+ - openbmb/MiniCPM-V-2
10
+ tags:
11
+ - VisRAG
12
+ pipeline_tag: feature-extraction
13
+ ---
14
+ # VisRAG: Vision-based Retrieval-augmented Generation on Multi-modality Documents
15
+ **VisRAG** is a novel vision-language model (VLM)-based RAG pipeline. In this pipeline, instead of first parsing the document to obtain text, the document is directly embedded using a VLM as an image and then retrieved to enhance the generation of a VLM.Compared to traditional text-based RAG, **VisRAG** maximizes the retention and utilization of the data information in the original documents, eliminating the information loss introduced during the parsing process.
16
+ <p align="center"><img width=800 src="https://github.com/tcy6/VisRAG/blob/master/assets/main_figure.png?raw=true"/></p>
17
+
18
+ ## VisRAG Description
19
+
20
+ ### VisRAG-Ret
21
+ **VisRAG-Ret** is a document embedding model built on [MiniCPM-V 2.0](https://huggingface.co/openbmb/MiniCPM-V-2), a vision-language model that integrates [SigLIP](https://huggingface.co/google/siglip-so400m-patch14-384) as the vision encoder and [MiniCPM-2B](https://huggingface.co/openbmb/MiniCPM-2B-sft-bf16) as the language model.
22
+
23
+ ### VisRAG-Gen
24
+ In the paper, We use MiniCPM-V 2.0, MiniCPM-V 2.6 and GPT-4o as the generators. Actually you can use any VLMs you like!
25
+
26
+ ## Training
27
+
28
+ ### VisRAG-Ret
29
+ Our training dataset of 362,110 Query-Document (Q-D) Pairs for **VisRAG-Ret** is comprised of train sets of openly available academic datasets (34%) and a synthetic dataset made up of pages from web-crawled PDF documents and augmented with VLM-generated (GPT-4o) pseudo-queries (66%).
30
+
31
+ ### VisRAG-Gen
32
+ The generation part does not use any fine-tuning; we directly use off-the-shelf LLMs/VLMs for generation.
33
+
34
+ ## Implementation Details
35
+ **VisRAG-Ret** is fine-tuned using [in-batch negatives](https://arxiv.org/abs/2004.04906) for one epoch with a batch size of 128 on 8 NVIDIA A100 80GB GPUs. The temperature is set to 0.02.
36
+
37
+ ## Requirements
38
+ ```
39
+ torch==2.1.2
40
+ torchvision==0.16.2
41
+ transformers==4.40.2
42
+ sentencepiece==0.1.99
43
+ decord==0.6.0
44
+ Pillow==10.1.0
45
+ accelerate==0.27.0
46
+ deepspeed==0.13.2
47
+ protobuf==4.25.0
48
+ pytrec_eval==0.5
49
+ ```
50
+
51
+ ## Usage
52
+
53
+ ### VisRAG-Ret
54
+ ```python
55
+ from transformers import AutoModel, AutoTokenizer
56
+ import torch
57
+ import torch.nn.functional as F
58
+ from PIL import Image
59
+ import os
60
+
61
+ def weighted_mean_pooling(hidden, attention_mask):
62
+ attention_mask_ = attention_mask * attention_mask.cumsum(dim=1)
63
+ s = torch.sum(hidden * attention_mask_.unsqueeze(-1).float(), dim=1)
64
+ d = attention_mask_.sum(dim=1, keepdim=True).float()
65
+ reps = s / d
66
+ return reps
67
+
68
+ @torch.no_grad()
69
+ def encode(text_or_image_list):
70
+
71
+ if (isinstance(text_or_image_list[0], str)):
72
+ inputs = {
73
+ "text": text_or_image_list,
74
+ 'image': [None] * len(text_or_image_list),
75
+ 'tokenizer': tokenizer
76
+ }
77
+ else:
78
+ inputs = {
79
+ "text": [''] * len(text_or_image_list),
80
+ 'image': text_or_image_list,
81
+ 'tokenizer': tokenizer
82
+ }
83
+ outputs = model(**inputs)
84
+ attention_mask = outputs.attention_mask
85
+ hidden = outputs.last_hidden_state
86
+
87
+ reps = weighted_mean_pooling(hidden, attention_mask)
88
+ embeddings = F.normalize(reps, p=2, dim=1).detach().cpu().numpy()
89
+ return embeddings
90
+
91
+ tokenizer = AutoTokenizer.from_pretrained("openbmb/VisRAG", trust_remote_code=True)
92
+ model = AutoModel.from_pretrained("openbmb/VisRAG", trust_remote_code=True)
93
+ model.eval()
94
+
95
+ script_dir = os.path.dirname(os.path.realpath(__file__))
96
+ queries = ["What does a dog look like?"]
97
+ passages = [
98
+ Image.open(os.path.join(script_dir, 'test_image/cat.jpeg')).convert('RGB'),
99
+ Image.open(os.path.join(script_dir, 'test_image/dog.jpg')).convert('RGB'),
100
+ ]
101
+
102
+ INSTRUCTION = "Represent this query for retrieving relavant documents: "
103
+ queries = [INSTRUCTION + query for query in queries]
104
+
105
+ embeddings_query = encode(queries)
106
+ embeddings_doc = encode(passages)
107
+
108
+ scores = (embeddings_query @ embeddings_doc.T)
109
+ print(scores.tolist())
110
+ ```
111
+
112
+ ## License
113
+
114
+ * The code in this repo is released under the [Apache-2.0](https://github.com/OpenBMB/MiniCPM/blob/main/LICENSE) License.
115
+ * The usage of **VisRAG-Ret** model weights must strictly follow [MiniCPM Model License.md](https://github.com/OpenBMB/MiniCPM/blob/main/MiniCPM%20Model%20License.md).
116
+ * The models and weights of **VisRAG-Ret** are completely free for academic research. After filling out a ["questionnaire"](https://modelbest.feishu.cn/share/base/form/shrcnpV5ZT9EJ6xYjh3Kx0J6v8g) for registration, **VisRAG-Ret** weights are also available for free commercial use.
117
+
118
+ ## Contact
119
+
120
+ - Shi Yu: [email protected]
121
+ - Chaoyue Tang: [email protected]
122
+
123
+ ## Citation
124
+
125
+ If you use any datasets or models from this organization in your research, please cite the original dataset as follows:
config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name_or_path": "openbmb/VisRAG",
3
+ "architectures": [
4
+ "VisRAG_Ret"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_minicpm.MiniCPMVConfig",
10
+ "AutoModel": "modeling_visrag_ret.VisRAG_Ret"
11
+ },
12
+ "bos_token_id": 1,
13
+ "dim_model_base": 256,
14
+ "drop_vision_last_layer": true,
15
+ "eos_token_id": 2,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2304,
18
+ "image_size": 448,
19
+ "initializer_range": 0.1,
20
+ "intermediate_size": 5760,
21
+ "max_position_embeddings": 4096,
22
+ "max_slice_nums": 9,
23
+ "mm_use_im_start_end": true,
24
+ "model_type": "minicpmv",
25
+ "num_attention_heads": 36,
26
+ "num_hidden_layers": 40,
27
+ "num_key_value_heads": 36,
28
+ "patch_size": 14,
29
+ "pretraining_tp": 1,
30
+ "query_num": 64,
31
+ "rms_norm_eps": 1e-05,
32
+ "rope_scaling": null,
33
+ "rope_theta": 10000.0,
34
+ "scale_depth": 1.4,
35
+ "scale_emb": 12,
36
+ "scale_resolution": 448,
37
+ "slice_mode": true,
38
+ "tie_word_embeddings": false,
39
+ "torch_dtype": "bfloat16",
40
+ "transformers_version": "4.40.2",
41
+ "use_cache": true,
42
+ "vision_encoder": "vit_so400m_patch14_siglip_384.webli",
43
+ "vocab_size": 122753
44
+ }
configuration_minicpm.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ MINICPM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
28
+
29
+
30
+ class MiniCPMConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`MiniCPMModel`]. It is used to instantiate an MiniCPM
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the MiniCPM-7B.
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the MiniCPM model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`MiniCPMModel`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 11008):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer decoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer decoder.
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
56
+ `num_attention_heads`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
60
+ The maximum sequence length that this model might ever be used with. MiniCPM 1 supports up to 2048 tokens,
61
+ MiniCPM 2 up to 4096, CodeMiniCPM up to 16384.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ pad_token_id (`int`, *optional*):
70
+ Padding token id.
71
+ bos_token_id (`int`, *optional*, defaults to 1):
72
+ Beginning of stream token id.
73
+ eos_token_id (`int`, *optional*, defaults to 2):
74
+ End of stream token id.
75
+ pretraining_tp (`int`, *optional*, defaults to 1):
76
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
77
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
78
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
79
+ issue](https://github.com/pytorch/pytorch/issues/76232).
80
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
81
+ Whether to tie weight embeddings
82
+ rope_theta (`float`, *optional*, defaults to 10000.0):
83
+ The base period of the RoPE embeddings.
84
+ rope_scaling (`Dict`, *optional*):
85
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
86
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
87
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
88
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
89
+ these scaling strategies behave:
90
+ https://www.reddit.com/r/LocalMiniCPM/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
91
+ experimental feature, subject to breaking API changes in future versions.
92
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
93
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
94
+ attention_dropout (`float`, *optional*, defaults to 0.0):
95
+ The dropout ratio for the attention probabilities.
96
+ ```python
97
+ >>> from transformers import MiniCPMModel, MiniCPMConfig
98
+ >>> # Initializing a MiniCPM minicpm-7b style configuration
99
+ >>> configuration = MiniCPMConfig()
100
+ >>> # Initializing a model from the minicpm-7b style configuration
101
+ >>> model = MiniCPMModel(configuration)
102
+ >>> # Accessing the model configuration
103
+ >>> configuration = model.config
104
+ ```"""
105
+
106
+ model_type = "minicpm"
107
+ keys_to_ignore_at_inference = ["past_key_values"]
108
+
109
+ def __init__(
110
+ self,
111
+ vocab_size=32000,
112
+ hidden_size=4096,
113
+ intermediate_size=11008,
114
+ num_hidden_layers=32,
115
+ num_attention_heads=32,
116
+ num_key_value_heads=None,
117
+ hidden_act="silu",
118
+ max_position_embeddings=2048,
119
+ initializer_range=0.02,
120
+ rms_norm_eps=1e-6,
121
+ use_cache=True,
122
+ pad_token_id=None,
123
+ bos_token_id=1,
124
+ eos_token_id=2,
125
+ pretraining_tp=1,
126
+ tie_word_embeddings=False,
127
+ rope_theta=10000.0,
128
+ rope_scaling=None,
129
+ attention_bias=False,
130
+ attention_dropout=0.0,
131
+ scale_emb=1,
132
+ dim_model_base=1,
133
+ scale_depth=1,
134
+ **kwargs,
135
+ ):
136
+ self.vocab_size = vocab_size
137
+ self.max_position_embeddings = max_position_embeddings
138
+ self.hidden_size = hidden_size
139
+ self.intermediate_size = intermediate_size
140
+ self.num_hidden_layers = num_hidden_layers
141
+ self.num_attention_heads = num_attention_heads
142
+
143
+ # for backward compatibility
144
+ if num_key_value_heads is None:
145
+ num_key_value_heads = num_attention_heads
146
+
147
+ self.num_key_value_heads = num_key_value_heads
148
+ self.hidden_act = hidden_act
149
+ self.initializer_range = initializer_range
150
+ self.rms_norm_eps = rms_norm_eps
151
+ self.pretraining_tp = pretraining_tp
152
+ self.use_cache = use_cache
153
+ self.rope_theta = rope_theta
154
+ self.rope_scaling = rope_scaling
155
+ self._rope_scaling_validation()
156
+ self.attention_bias = attention_bias
157
+ self.attention_dropout = attention_dropout
158
+ self.scale_emb = scale_emb
159
+ self.dim_model_base = dim_model_base
160
+ self.scale_depth = scale_depth
161
+
162
+ super().__init__(
163
+ pad_token_id=pad_token_id,
164
+ bos_token_id=bos_token_id,
165
+ eos_token_id=eos_token_id,
166
+ tie_word_embeddings=tie_word_embeddings,
167
+ **kwargs,
168
+ )
169
+
170
+ def _rope_scaling_validation(self):
171
+ """
172
+ Validate the `rope_scaling` configuration.
173
+ """
174
+ if self.rope_scaling is None:
175
+ return
176
+
177
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
178
+ raise ValueError(
179
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
180
+ f"got {self.rope_scaling}"
181
+ )
182
+ rope_scaling_type = self.rope_scaling.get("type", None)
183
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
184
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
185
+ raise ValueError(
186
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
187
+ )
188
+ if (
189
+ rope_scaling_factor is None
190
+ or not isinstance(rope_scaling_factor, float)
191
+ or rope_scaling_factor <= 1.0
192
+ ):
193
+ raise ValueError(
194
+ f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}"
195
+ )
196
+
197
+ class MiniCPMVConfig(MiniCPMConfig):
198
+ model_type = "minicpmv"
199
+ keys_to_ignore_at_inference = ["past_key_values"]
200
+
201
+ def __init__(
202
+ self,
203
+ vision_encoder="vit_so400m_patch14_siglip_384.webli",
204
+ query_num=64,
205
+ image_size=448,
206
+ drop_vision_last_layer=True,
207
+ slice_mode=True,
208
+ patch_size=14,
209
+ max_slice_nums=9,
210
+ scale_resolution=448,
211
+ **kwargs,
212
+ ):
213
+ self.query_num = query_num
214
+ self.image_size = image_size
215
+ self.patch_size = patch_size
216
+ self.drop_vision_last_layer = drop_vision_last_layer
217
+ self.slice_mode = slice_mode
218
+ self.max_slice_nums = max_slice_nums
219
+ self.scale_resolution = scale_resolution
220
+ self.vision_encoder = vision_encoder
221
+
222
+ super().__init__(**kwargs)
223
+
224
+
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f2f1f0b353cd125705111c0363dd45baa26a586972152b2d55858bb7e8e53a2
3
+ size 4993235928
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:85c5084077ee3ac7d0bae9bd746f78364ade0299b4fd074e245988e5e9b407f5
3
+ size 1876772888
model.safetensors.index.json ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 6869931584
4
+ },
5
+ "weight_map": {
6
+ "llm.lm_head.weight": "model-00002-of-00002.safetensors",
7
+ "llm.model.embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "llm.model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "llm.model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
10
+ "llm.model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
11
+ "llm.model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
12
+ "llm.model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
13
+ "llm.model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
14
+ "llm.model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
15
+ "llm.model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
16
+ "llm.model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
17
+ "llm.model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
18
+ "llm.model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
19
+ "llm.model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
20
+ "llm.model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
21
+ "llm.model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
22
+ "llm.model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
23
+ "llm.model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
24
+ "llm.model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
25
+ "llm.model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
26
+ "llm.model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
27
+ "llm.model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
28
+ "llm.model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
29
+ "llm.model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
30
+ "llm.model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
31
+ "llm.model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
32
+ "llm.model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
33
+ "llm.model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
34
+ "llm.model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
35
+ "llm.model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
36
+ "llm.model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
37
+ "llm.model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
38
+ "llm.model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
39
+ "llm.model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
40
+ "llm.model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
41
+ "llm.model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
42
+ "llm.model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
43
+ "llm.model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
44
+ "llm.model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
45
+ "llm.model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
46
+ "llm.model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
47
+ "llm.model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
48
+ "llm.model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
49
+ "llm.model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
50
+ "llm.model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
51
+ "llm.model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
52
+ "llm.model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
53
+ "llm.model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
54
+ "llm.model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
55
+ "llm.model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
56
+ "llm.model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
57
+ "llm.model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
58
+ "llm.model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
59
+ "llm.model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
60
+ "llm.model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
61
+ "llm.model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
62
+ "llm.model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
63
+ "llm.model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
64
+ "llm.model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
65
+ "llm.model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
66
+ "llm.model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
67
+ "llm.model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
68
+ "llm.model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
69
+ "llm.model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
70
+ "llm.model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
71
+ "llm.model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
72
+ "llm.model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
73
+ "llm.model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
74
+ "llm.model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
75
+ "llm.model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
76
+ "llm.model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
77
+ "llm.model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
78
+ "llm.model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
79
+ "llm.model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
80
+ "llm.model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
81
+ "llm.model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
82
+ "llm.model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
83
+ "llm.model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
84
+ "llm.model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
85
+ "llm.model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
86
+ "llm.model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
87
+ "llm.model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
88
+ "llm.model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
89
+ "llm.model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
90
+ "llm.model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
91
+ "llm.model.layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
92
+ "llm.model.layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
93
+ "llm.model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
94
+ "llm.model.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
95
+ "llm.model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
96
+ "llm.model.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
97
+ "llm.model.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
98
+ "llm.model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
99
+ "llm.model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
100
+ "llm.model.layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
101
+ "llm.model.layers.18.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
102
+ "llm.model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
103
+ "llm.model.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
104
+ "llm.model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
105
+ "llm.model.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
106
+ "llm.model.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
107
+ "llm.model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
108
+ "llm.model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
109
+ "llm.model.layers.19.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
110
+ "llm.model.layers.19.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
111
+ "llm.model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
112
+ "llm.model.layers.19.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
113
+ "llm.model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
114
+ "llm.model.layers.19.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
115
+ "llm.model.layers.19.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
116
+ "llm.model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
117
+ "llm.model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
118
+ "llm.model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
119
+ "llm.model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
120
+ "llm.model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
121
+ "llm.model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
122
+ "llm.model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
123
+ "llm.model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
124
+ "llm.model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
125
+ "llm.model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
126
+ "llm.model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
127
+ "llm.model.layers.20.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
128
+ "llm.model.layers.20.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
129
+ "llm.model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
130
+ "llm.model.layers.20.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
131
+ "llm.model.layers.20.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
132
+ "llm.model.layers.20.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
133
+ "llm.model.layers.20.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
134
+ "llm.model.layers.21.input_layernorm.weight": "model-00001-of-00002.safetensors",
135
+ "llm.model.layers.21.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
136
+ "llm.model.layers.21.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
137
+ "llm.model.layers.21.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
138
+ "llm.model.layers.21.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
139
+ "llm.model.layers.21.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
140
+ "llm.model.layers.21.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
141
+ "llm.model.layers.21.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
142
+ "llm.model.layers.21.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
143
+ "llm.model.layers.22.input_layernorm.weight": "model-00001-of-00002.safetensors",
144
+ "llm.model.layers.22.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
145
+ "llm.model.layers.22.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
146
+ "llm.model.layers.22.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
147
+ "llm.model.layers.22.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
148
+ "llm.model.layers.22.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
149
+ "llm.model.layers.22.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
150
+ "llm.model.layers.22.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
151
+ "llm.model.layers.22.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
152
+ "llm.model.layers.23.input_layernorm.weight": "model-00001-of-00002.safetensors",
153
+ "llm.model.layers.23.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
154
+ "llm.model.layers.23.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
155
+ "llm.model.layers.23.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
156
+ "llm.model.layers.23.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
157
+ "llm.model.layers.23.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
158
+ "llm.model.layers.23.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
159
+ "llm.model.layers.23.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
160
+ "llm.model.layers.23.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
161
+ "llm.model.layers.24.input_layernorm.weight": "model-00001-of-00002.safetensors",
162
+ "llm.model.layers.24.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
163
+ "llm.model.layers.24.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
164
+ "llm.model.layers.24.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
165
+ "llm.model.layers.24.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
166
+ "llm.model.layers.24.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
167
+ "llm.model.layers.24.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
168
+ "llm.model.layers.24.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
169
+ "llm.model.layers.24.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
170
+ "llm.model.layers.25.input_layernorm.weight": "model-00001-of-00002.safetensors",
171
+ "llm.model.layers.25.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
172
+ "llm.model.layers.25.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
173
+ "llm.model.layers.25.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
174
+ "llm.model.layers.25.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
175
+ "llm.model.layers.25.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
176
+ "llm.model.layers.25.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
177
+ "llm.model.layers.25.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
178
+ "llm.model.layers.25.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
179
+ "llm.model.layers.26.input_layernorm.weight": "model-00001-of-00002.safetensors",
180
+ "llm.model.layers.26.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
181
+ "llm.model.layers.26.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
182
+ "llm.model.layers.26.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
183
+ "llm.model.layers.26.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
184
+ "llm.model.layers.26.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
185
+ "llm.model.layers.26.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
186
+ "llm.model.layers.26.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
187
+ "llm.model.layers.26.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
188
+ "llm.model.layers.27.input_layernorm.weight": "model-00001-of-00002.safetensors",
189
+ "llm.model.layers.27.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
190
+ "llm.model.layers.27.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
191
+ "llm.model.layers.27.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
192
+ "llm.model.layers.27.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
193
+ "llm.model.layers.27.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
194
+ "llm.model.layers.27.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
195
+ "llm.model.layers.27.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
196
+ "llm.model.layers.27.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
197
+ "llm.model.layers.28.input_layernorm.weight": "model-00001-of-00002.safetensors",
198
+ "llm.model.layers.28.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
199
+ "llm.model.layers.28.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
200
+ "llm.model.layers.28.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
201
+ "llm.model.layers.28.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
202
+ "llm.model.layers.28.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
203
+ "llm.model.layers.28.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
204
+ "llm.model.layers.28.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
205
+ "llm.model.layers.28.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
206
+ "llm.model.layers.29.input_layernorm.weight": "model-00001-of-00002.safetensors",
207
+ "llm.model.layers.29.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
208
+ "llm.model.layers.29.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
209
+ "llm.model.layers.29.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
210
+ "llm.model.layers.29.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
211
+ "llm.model.layers.29.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
212
+ "llm.model.layers.29.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
213
+ "llm.model.layers.29.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
214
+ "llm.model.layers.29.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
215
+ "llm.model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
216
+ "llm.model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
217
+ "llm.model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
218
+ "llm.model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
219
+ "llm.model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
220
+ "llm.model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
221
+ "llm.model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
222
+ "llm.model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
223
+ "llm.model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
224
+ "llm.model.layers.30.input_layernorm.weight": "model-00001-of-00002.safetensors",
225
+ "llm.model.layers.30.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
226
+ "llm.model.layers.30.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
227
+ "llm.model.layers.30.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
228
+ "llm.model.layers.30.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
229
+ "llm.model.layers.30.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
230
+ "llm.model.layers.30.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
231
+ "llm.model.layers.30.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
232
+ "llm.model.layers.30.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
233
+ "llm.model.layers.31.input_layernorm.weight": "model-00001-of-00002.safetensors",
234
+ "llm.model.layers.31.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
235
+ "llm.model.layers.31.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
236
+ "llm.model.layers.31.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
237
+ "llm.model.layers.31.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
238
+ "llm.model.layers.31.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
239
+ "llm.model.layers.31.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
240
+ "llm.model.layers.31.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
241
+ "llm.model.layers.31.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
242
+ "llm.model.layers.32.input_layernorm.weight": "model-00001-of-00002.safetensors",
243
+ "llm.model.layers.32.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
244
+ "llm.model.layers.32.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
245
+ "llm.model.layers.32.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
246
+ "llm.model.layers.32.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
247
+ "llm.model.layers.32.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
248
+ "llm.model.layers.32.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
249
+ "llm.model.layers.32.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
250
+ "llm.model.layers.32.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
251
+ "llm.model.layers.33.input_layernorm.weight": "model-00001-of-00002.safetensors",
252
+ "llm.model.layers.33.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
253
+ "llm.model.layers.33.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
254
+ "llm.model.layers.33.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
255
+ "llm.model.layers.33.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
256
+ "llm.model.layers.33.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
257
+ "llm.model.layers.33.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
258
+ "llm.model.layers.33.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
259
+ "llm.model.layers.33.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
260
+ "llm.model.layers.34.input_layernorm.weight": "model-00001-of-00002.safetensors",
261
+ "llm.model.layers.34.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
262
+ "llm.model.layers.34.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
263
+ "llm.model.layers.34.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
264
+ "llm.model.layers.34.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
265
+ "llm.model.layers.34.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
266
+ "llm.model.layers.34.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
267
+ "llm.model.layers.34.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
268
+ "llm.model.layers.34.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
269
+ "llm.model.layers.35.input_layernorm.weight": "model-00001-of-00002.safetensors",
270
+ "llm.model.layers.35.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
271
+ "llm.model.layers.35.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
272
+ "llm.model.layers.35.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
273
+ "llm.model.layers.35.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
274
+ "llm.model.layers.35.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
275
+ "llm.model.layers.35.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
276
+ "llm.model.layers.35.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
277
+ "llm.model.layers.35.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
278
+ "llm.model.layers.36.input_layernorm.weight": "model-00002-of-00002.safetensors",
279
+ "llm.model.layers.36.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
280
+ "llm.model.layers.36.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
281
+ "llm.model.layers.36.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
282
+ "llm.model.layers.36.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
283
+ "llm.model.layers.36.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
284
+ "llm.model.layers.36.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
285
+ "llm.model.layers.36.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
286
+ "llm.model.layers.36.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
287
+ "llm.model.layers.37.input_layernorm.weight": "model-00002-of-00002.safetensors",
288
+ "llm.model.layers.37.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
289
+ "llm.model.layers.37.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
290
+ "llm.model.layers.37.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
291
+ "llm.model.layers.37.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
292
+ "llm.model.layers.37.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
293
+ "llm.model.layers.37.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
294
+ "llm.model.layers.37.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
295
+ "llm.model.layers.37.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
296
+ "llm.model.layers.38.input_layernorm.weight": "model-00002-of-00002.safetensors",
297
+ "llm.model.layers.38.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
298
+ "llm.model.layers.38.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
299
+ "llm.model.layers.38.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
300
+ "llm.model.layers.38.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
301
+ "llm.model.layers.38.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
302
+ "llm.model.layers.38.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
303
+ "llm.model.layers.38.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
304
+ "llm.model.layers.38.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
305
+ "llm.model.layers.39.input_layernorm.weight": "model-00002-of-00002.safetensors",
306
+ "llm.model.layers.39.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
307
+ "llm.model.layers.39.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
308
+ "llm.model.layers.39.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
309
+ "llm.model.layers.39.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
310
+ "llm.model.layers.39.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
311
+ "llm.model.layers.39.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
312
+ "llm.model.layers.39.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
313
+ "llm.model.layers.39.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
314
+ "llm.model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
315
+ "llm.model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
316
+ "llm.model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
317
+ "llm.model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
318
+ "llm.model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
319
+ "llm.model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
320
+ "llm.model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
321
+ "llm.model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
322
+ "llm.model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
323
+ "llm.model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
324
+ "llm.model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
325
+ "llm.model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
326
+ "llm.model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
327
+ "llm.model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
328
+ "llm.model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
329
+ "llm.model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
330
+ "llm.model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
331
+ "llm.model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
332
+ "llm.model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
333
+ "llm.model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
334
+ "llm.model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
335
+ "llm.model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
336
+ "llm.model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
337
+ "llm.model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
338
+ "llm.model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
339
+ "llm.model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
340
+ "llm.model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
341
+ "llm.model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
342
+ "llm.model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
343
+ "llm.model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
344
+ "llm.model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
345
+ "llm.model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
346
+ "llm.model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
347
+ "llm.model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
348
+ "llm.model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
349
+ "llm.model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
350
+ "llm.model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
351
+ "llm.model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
352
+ "llm.model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
353
+ "llm.model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
354
+ "llm.model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
355
+ "llm.model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
356
+ "llm.model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
357
+ "llm.model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
358
+ "llm.model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
359
+ "llm.model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
360
+ "llm.model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
361
+ "llm.model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
362
+ "llm.model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
363
+ "llm.model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
364
+ "llm.model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
365
+ "llm.model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
366
+ "llm.model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
367
+ "llm.model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
368
+ "llm.model.norm.weight": "model-00002-of-00002.safetensors",
369
+ "resampler.attn.in_proj_bias": "model-00002-of-00002.safetensors",
370
+ "resampler.attn.in_proj_weight": "model-00002-of-00002.safetensors",
371
+ "resampler.attn.out_proj.bias": "model-00002-of-00002.safetensors",
372
+ "resampler.attn.out_proj.weight": "model-00002-of-00002.safetensors",
373
+ "resampler.kv_proj.weight": "model-00002-of-00002.safetensors",
374
+ "resampler.ln_kv.bias": "model-00002-of-00002.safetensors",
375
+ "resampler.ln_kv.weight": "model-00002-of-00002.safetensors",
376
+ "resampler.ln_post.bias": "model-00002-of-00002.safetensors",
377
+ "resampler.ln_post.weight": "model-00002-of-00002.safetensors",
378
+ "resampler.ln_q.bias": "model-00002-of-00002.safetensors",
379
+ "resampler.ln_q.weight": "model-00002-of-00002.safetensors",
380
+ "resampler.pos_embed": "model-00002-of-00002.safetensors",
381
+ "resampler.proj": "model-00002-of-00002.safetensors",
382
+ "resampler.query": "model-00002-of-00002.safetensors",
383
+ "vpm.blocks.0.attn.proj.bias": "model-00002-of-00002.safetensors",
384
+ "vpm.blocks.0.attn.proj.weight": "model-00002-of-00002.safetensors",
385
+ "vpm.blocks.0.attn.qkv.bias": "model-00002-of-00002.safetensors",
386
+ "vpm.blocks.0.attn.qkv.weight": "model-00002-of-00002.safetensors",
387
+ "vpm.blocks.0.mlp.fc1.bias": "model-00002-of-00002.safetensors",
388
+ "vpm.blocks.0.mlp.fc1.weight": "model-00002-of-00002.safetensors",
389
+ "vpm.blocks.0.mlp.fc2.bias": "model-00002-of-00002.safetensors",
390
+ "vpm.blocks.0.mlp.fc2.weight": "model-00002-of-00002.safetensors",
391
+ "vpm.blocks.0.norm1.bias": "model-00002-of-00002.safetensors",
392
+ "vpm.blocks.0.norm1.weight": "model-00002-of-00002.safetensors",
393
+ "vpm.blocks.0.norm2.bias": "model-00002-of-00002.safetensors",
394
+ "vpm.blocks.0.norm2.weight": "model-00002-of-00002.safetensors",
395
+ "vpm.blocks.1.attn.proj.bias": "model-00002-of-00002.safetensors",
396
+ "vpm.blocks.1.attn.proj.weight": "model-00002-of-00002.safetensors",
397
+ "vpm.blocks.1.attn.qkv.bias": "model-00002-of-00002.safetensors",
398
+ "vpm.blocks.1.attn.qkv.weight": "model-00002-of-00002.safetensors",
399
+ "vpm.blocks.1.mlp.fc1.bias": "model-00002-of-00002.safetensors",
400
+ "vpm.blocks.1.mlp.fc1.weight": "model-00002-of-00002.safetensors",
401
+ "vpm.blocks.1.mlp.fc2.bias": "model-00002-of-00002.safetensors",
402
+ "vpm.blocks.1.mlp.fc2.weight": "model-00002-of-00002.safetensors",
403
+ "vpm.blocks.1.norm1.bias": "model-00002-of-00002.safetensors",
404
+ "vpm.blocks.1.norm1.weight": "model-00002-of-00002.safetensors",
405
+ "vpm.blocks.1.norm2.bias": "model-00002-of-00002.safetensors",
406
+ "vpm.blocks.1.norm2.weight": "model-00002-of-00002.safetensors",
407
+ "vpm.blocks.10.attn.proj.bias": "model-00002-of-00002.safetensors",
408
+ "vpm.blocks.10.attn.proj.weight": "model-00002-of-00002.safetensors",
409
+ "vpm.blocks.10.attn.qkv.bias": "model-00002-of-00002.safetensors",
410
+ "vpm.blocks.10.attn.qkv.weight": "model-00002-of-00002.safetensors",
411
+ "vpm.blocks.10.mlp.fc1.bias": "model-00002-of-00002.safetensors",
412
+ "vpm.blocks.10.mlp.fc1.weight": "model-00002-of-00002.safetensors",
413
+ "vpm.blocks.10.mlp.fc2.bias": "model-00002-of-00002.safetensors",
414
+ "vpm.blocks.10.mlp.fc2.weight": "model-00002-of-00002.safetensors",
415
+ "vpm.blocks.10.norm1.bias": "model-00002-of-00002.safetensors",
416
+ "vpm.blocks.10.norm1.weight": "model-00002-of-00002.safetensors",
417
+ "vpm.blocks.10.norm2.bias": "model-00002-of-00002.safetensors",
418
+ "vpm.blocks.10.norm2.weight": "model-00002-of-00002.safetensors",
419
+ "vpm.blocks.11.attn.proj.bias": "model-00002-of-00002.safetensors",
420
+ "vpm.blocks.11.attn.proj.weight": "model-00002-of-00002.safetensors",
421
+ "vpm.blocks.11.attn.qkv.bias": "model-00002-of-00002.safetensors",
422
+ "vpm.blocks.11.attn.qkv.weight": "model-00002-of-00002.safetensors",
423
+ "vpm.blocks.11.mlp.fc1.bias": "model-00002-of-00002.safetensors",
424
+ "vpm.blocks.11.mlp.fc1.weight": "model-00002-of-00002.safetensors",
425
+ "vpm.blocks.11.mlp.fc2.bias": "model-00002-of-00002.safetensors",
426
+ "vpm.blocks.11.mlp.fc2.weight": "model-00002-of-00002.safetensors",
427
+ "vpm.blocks.11.norm1.bias": "model-00002-of-00002.safetensors",
428
+ "vpm.blocks.11.norm1.weight": "model-00002-of-00002.safetensors",
429
+ "vpm.blocks.11.norm2.bias": "model-00002-of-00002.safetensors",
430
+ "vpm.blocks.11.norm2.weight": "model-00002-of-00002.safetensors",
431
+ "vpm.blocks.12.attn.proj.bias": "model-00002-of-00002.safetensors",
432
+ "vpm.blocks.12.attn.proj.weight": "model-00002-of-00002.safetensors",
433
+ "vpm.blocks.12.attn.qkv.bias": "model-00002-of-00002.safetensors",
434
+ "vpm.blocks.12.attn.qkv.weight": "model-00002-of-00002.safetensors",
435
+ "vpm.blocks.12.mlp.fc1.bias": "model-00002-of-00002.safetensors",
436
+ "vpm.blocks.12.mlp.fc1.weight": "model-00002-of-00002.safetensors",
437
+ "vpm.blocks.12.mlp.fc2.bias": "model-00002-of-00002.safetensors",
438
+ "vpm.blocks.12.mlp.fc2.weight": "model-00002-of-00002.safetensors",
439
+ "vpm.blocks.12.norm1.bias": "model-00002-of-00002.safetensors",
440
+ "vpm.blocks.12.norm1.weight": "model-00002-of-00002.safetensors",
441
+ "vpm.blocks.12.norm2.bias": "model-00002-of-00002.safetensors",
442
+ "vpm.blocks.12.norm2.weight": "model-00002-of-00002.safetensors",
443
+ "vpm.blocks.13.attn.proj.bias": "model-00002-of-00002.safetensors",
444
+ "vpm.blocks.13.attn.proj.weight": "model-00002-of-00002.safetensors",
445
+ "vpm.blocks.13.attn.qkv.bias": "model-00002-of-00002.safetensors",
446
+ "vpm.blocks.13.attn.qkv.weight": "model-00002-of-00002.safetensors",
447
+ "vpm.blocks.13.mlp.fc1.bias": "model-00002-of-00002.safetensors",
448
+ "vpm.blocks.13.mlp.fc1.weight": "model-00002-of-00002.safetensors",
449
+ "vpm.blocks.13.mlp.fc2.bias": "model-00002-of-00002.safetensors",
450
+ "vpm.blocks.13.mlp.fc2.weight": "model-00002-of-00002.safetensors",
451
+ "vpm.blocks.13.norm1.bias": "model-00002-of-00002.safetensors",
452
+ "vpm.blocks.13.norm1.weight": "model-00002-of-00002.safetensors",
453
+ "vpm.blocks.13.norm2.bias": "model-00002-of-00002.safetensors",
454
+ "vpm.blocks.13.norm2.weight": "model-00002-of-00002.safetensors",
455
+ "vpm.blocks.14.attn.proj.bias": "model-00002-of-00002.safetensors",
456
+ "vpm.blocks.14.attn.proj.weight": "model-00002-of-00002.safetensors",
457
+ "vpm.blocks.14.attn.qkv.bias": "model-00002-of-00002.safetensors",
458
+ "vpm.blocks.14.attn.qkv.weight": "model-00002-of-00002.safetensors",
459
+ "vpm.blocks.14.mlp.fc1.bias": "model-00002-of-00002.safetensors",
460
+ "vpm.blocks.14.mlp.fc1.weight": "model-00002-of-00002.safetensors",
461
+ "vpm.blocks.14.mlp.fc2.bias": "model-00002-of-00002.safetensors",
462
+ "vpm.blocks.14.mlp.fc2.weight": "model-00002-of-00002.safetensors",
463
+ "vpm.blocks.14.norm1.bias": "model-00002-of-00002.safetensors",
464
+ "vpm.blocks.14.norm1.weight": "model-00002-of-00002.safetensors",
465
+ "vpm.blocks.14.norm2.bias": "model-00002-of-00002.safetensors",
466
+ "vpm.blocks.14.norm2.weight": "model-00002-of-00002.safetensors",
467
+ "vpm.blocks.15.attn.proj.bias": "model-00002-of-00002.safetensors",
468
+ "vpm.blocks.15.attn.proj.weight": "model-00002-of-00002.safetensors",
469
+ "vpm.blocks.15.attn.qkv.bias": "model-00002-of-00002.safetensors",
470
+ "vpm.blocks.15.attn.qkv.weight": "model-00002-of-00002.safetensors",
471
+ "vpm.blocks.15.mlp.fc1.bias": "model-00002-of-00002.safetensors",
472
+ "vpm.blocks.15.mlp.fc1.weight": "model-00002-of-00002.safetensors",
473
+ "vpm.blocks.15.mlp.fc2.bias": "model-00002-of-00002.safetensors",
474
+ "vpm.blocks.15.mlp.fc2.weight": "model-00002-of-00002.safetensors",
475
+ "vpm.blocks.15.norm1.bias": "model-00002-of-00002.safetensors",
476
+ "vpm.blocks.15.norm1.weight": "model-00002-of-00002.safetensors",
477
+ "vpm.blocks.15.norm2.bias": "model-00002-of-00002.safetensors",
478
+ "vpm.blocks.15.norm2.weight": "model-00002-of-00002.safetensors",
479
+ "vpm.blocks.16.attn.proj.bias": "model-00002-of-00002.safetensors",
480
+ "vpm.blocks.16.attn.proj.weight": "model-00002-of-00002.safetensors",
481
+ "vpm.blocks.16.attn.qkv.bias": "model-00002-of-00002.safetensors",
482
+ "vpm.blocks.16.attn.qkv.weight": "model-00002-of-00002.safetensors",
483
+ "vpm.blocks.16.mlp.fc1.bias": "model-00002-of-00002.safetensors",
484
+ "vpm.blocks.16.mlp.fc1.weight": "model-00002-of-00002.safetensors",
485
+ "vpm.blocks.16.mlp.fc2.bias": "model-00002-of-00002.safetensors",
486
+ "vpm.blocks.16.mlp.fc2.weight": "model-00002-of-00002.safetensors",
487
+ "vpm.blocks.16.norm1.bias": "model-00002-of-00002.safetensors",
488
+ "vpm.blocks.16.norm1.weight": "model-00002-of-00002.safetensors",
489
+ "vpm.blocks.16.norm2.bias": "model-00002-of-00002.safetensors",
490
+ "vpm.blocks.16.norm2.weight": "model-00002-of-00002.safetensors",
491
+ "vpm.blocks.17.attn.proj.bias": "model-00002-of-00002.safetensors",
492
+ "vpm.blocks.17.attn.proj.weight": "model-00002-of-00002.safetensors",
493
+ "vpm.blocks.17.attn.qkv.bias": "model-00002-of-00002.safetensors",
494
+ "vpm.blocks.17.attn.qkv.weight": "model-00002-of-00002.safetensors",
495
+ "vpm.blocks.17.mlp.fc1.bias": "model-00002-of-00002.safetensors",
496
+ "vpm.blocks.17.mlp.fc1.weight": "model-00002-of-00002.safetensors",
497
+ "vpm.blocks.17.mlp.fc2.bias": "model-00002-of-00002.safetensors",
498
+ "vpm.blocks.17.mlp.fc2.weight": "model-00002-of-00002.safetensors",
499
+ "vpm.blocks.17.norm1.bias": "model-00002-of-00002.safetensors",
500
+ "vpm.blocks.17.norm1.weight": "model-00002-of-00002.safetensors",
501
+ "vpm.blocks.17.norm2.bias": "model-00002-of-00002.safetensors",
502
+ "vpm.blocks.17.norm2.weight": "model-00002-of-00002.safetensors",
503
+ "vpm.blocks.18.attn.proj.bias": "model-00002-of-00002.safetensors",
504
+ "vpm.blocks.18.attn.proj.weight": "model-00002-of-00002.safetensors",
505
+ "vpm.blocks.18.attn.qkv.bias": "model-00002-of-00002.safetensors",
506
+ "vpm.blocks.18.attn.qkv.weight": "model-00002-of-00002.safetensors",
507
+ "vpm.blocks.18.mlp.fc1.bias": "model-00002-of-00002.safetensors",
508
+ "vpm.blocks.18.mlp.fc1.weight": "model-00002-of-00002.safetensors",
509
+ "vpm.blocks.18.mlp.fc2.bias": "model-00002-of-00002.safetensors",
510
+ "vpm.blocks.18.mlp.fc2.weight": "model-00002-of-00002.safetensors",
511
+ "vpm.blocks.18.norm1.bias": "model-00002-of-00002.safetensors",
512
+ "vpm.blocks.18.norm1.weight": "model-00002-of-00002.safetensors",
513
+ "vpm.blocks.18.norm2.bias": "model-00002-of-00002.safetensors",
514
+ "vpm.blocks.18.norm2.weight": "model-00002-of-00002.safetensors",
515
+ "vpm.blocks.19.attn.proj.bias": "model-00002-of-00002.safetensors",
516
+ "vpm.blocks.19.attn.proj.weight": "model-00002-of-00002.safetensors",
517
+ "vpm.blocks.19.attn.qkv.bias": "model-00002-of-00002.safetensors",
518
+ "vpm.blocks.19.attn.qkv.weight": "model-00002-of-00002.safetensors",
519
+ "vpm.blocks.19.mlp.fc1.bias": "model-00002-of-00002.safetensors",
520
+ "vpm.blocks.19.mlp.fc1.weight": "model-00002-of-00002.safetensors",
521
+ "vpm.blocks.19.mlp.fc2.bias": "model-00002-of-00002.safetensors",
522
+ "vpm.blocks.19.mlp.fc2.weight": "model-00002-of-00002.safetensors",
523
+ "vpm.blocks.19.norm1.bias": "model-00002-of-00002.safetensors",
524
+ "vpm.blocks.19.norm1.weight": "model-00002-of-00002.safetensors",
525
+ "vpm.blocks.19.norm2.bias": "model-00002-of-00002.safetensors",
526
+ "vpm.blocks.19.norm2.weight": "model-00002-of-00002.safetensors",
527
+ "vpm.blocks.2.attn.proj.bias": "model-00002-of-00002.safetensors",
528
+ "vpm.blocks.2.attn.proj.weight": "model-00002-of-00002.safetensors",
529
+ "vpm.blocks.2.attn.qkv.bias": "model-00002-of-00002.safetensors",
530
+ "vpm.blocks.2.attn.qkv.weight": "model-00002-of-00002.safetensors",
531
+ "vpm.blocks.2.mlp.fc1.bias": "model-00002-of-00002.safetensors",
532
+ "vpm.blocks.2.mlp.fc1.weight": "model-00002-of-00002.safetensors",
533
+ "vpm.blocks.2.mlp.fc2.bias": "model-00002-of-00002.safetensors",
534
+ "vpm.blocks.2.mlp.fc2.weight": "model-00002-of-00002.safetensors",
535
+ "vpm.blocks.2.norm1.bias": "model-00002-of-00002.safetensors",
536
+ "vpm.blocks.2.norm1.weight": "model-00002-of-00002.safetensors",
537
+ "vpm.blocks.2.norm2.bias": "model-00002-of-00002.safetensors",
538
+ "vpm.blocks.2.norm2.weight": "model-00002-of-00002.safetensors",
539
+ "vpm.blocks.20.attn.proj.bias": "model-00002-of-00002.safetensors",
540
+ "vpm.blocks.20.attn.proj.weight": "model-00002-of-00002.safetensors",
541
+ "vpm.blocks.20.attn.qkv.bias": "model-00002-of-00002.safetensors",
542
+ "vpm.blocks.20.attn.qkv.weight": "model-00002-of-00002.safetensors",
543
+ "vpm.blocks.20.mlp.fc1.bias": "model-00002-of-00002.safetensors",
544
+ "vpm.blocks.20.mlp.fc1.weight": "model-00002-of-00002.safetensors",
545
+ "vpm.blocks.20.mlp.fc2.bias": "model-00002-of-00002.safetensors",
546
+ "vpm.blocks.20.mlp.fc2.weight": "model-00002-of-00002.safetensors",
547
+ "vpm.blocks.20.norm1.bias": "model-00002-of-00002.safetensors",
548
+ "vpm.blocks.20.norm1.weight": "model-00002-of-00002.safetensors",
549
+ "vpm.blocks.20.norm2.bias": "model-00002-of-00002.safetensors",
550
+ "vpm.blocks.20.norm2.weight": "model-00002-of-00002.safetensors",
551
+ "vpm.blocks.21.attn.proj.bias": "model-00002-of-00002.safetensors",
552
+ "vpm.blocks.21.attn.proj.weight": "model-00002-of-00002.safetensors",
553
+ "vpm.blocks.21.attn.qkv.bias": "model-00002-of-00002.safetensors",
554
+ "vpm.blocks.21.attn.qkv.weight": "model-00002-of-00002.safetensors",
555
+ "vpm.blocks.21.mlp.fc1.bias": "model-00002-of-00002.safetensors",
556
+ "vpm.blocks.21.mlp.fc1.weight": "model-00002-of-00002.safetensors",
557
+ "vpm.blocks.21.mlp.fc2.bias": "model-00002-of-00002.safetensors",
558
+ "vpm.blocks.21.mlp.fc2.weight": "model-00002-of-00002.safetensors",
559
+ "vpm.blocks.21.norm1.bias": "model-00002-of-00002.safetensors",
560
+ "vpm.blocks.21.norm1.weight": "model-00002-of-00002.safetensors",
561
+ "vpm.blocks.21.norm2.bias": "model-00002-of-00002.safetensors",
562
+ "vpm.blocks.21.norm2.weight": "model-00002-of-00002.safetensors",
563
+ "vpm.blocks.22.attn.proj.bias": "model-00002-of-00002.safetensors",
564
+ "vpm.blocks.22.attn.proj.weight": "model-00002-of-00002.safetensors",
565
+ "vpm.blocks.22.attn.qkv.bias": "model-00002-of-00002.safetensors",
566
+ "vpm.blocks.22.attn.qkv.weight": "model-00002-of-00002.safetensors",
567
+ "vpm.blocks.22.mlp.fc1.bias": "model-00002-of-00002.safetensors",
568
+ "vpm.blocks.22.mlp.fc1.weight": "model-00002-of-00002.safetensors",
569
+ "vpm.blocks.22.mlp.fc2.bias": "model-00002-of-00002.safetensors",
570
+ "vpm.blocks.22.mlp.fc2.weight": "model-00002-of-00002.safetensors",
571
+ "vpm.blocks.22.norm1.bias": "model-00002-of-00002.safetensors",
572
+ "vpm.blocks.22.norm1.weight": "model-00002-of-00002.safetensors",
573
+ "vpm.blocks.22.norm2.bias": "model-00002-of-00002.safetensors",
574
+ "vpm.blocks.22.norm2.weight": "model-00002-of-00002.safetensors",
575
+ "vpm.blocks.23.attn.proj.bias": "model-00002-of-00002.safetensors",
576
+ "vpm.blocks.23.attn.proj.weight": "model-00002-of-00002.safetensors",
577
+ "vpm.blocks.23.attn.qkv.bias": "model-00002-of-00002.safetensors",
578
+ "vpm.blocks.23.attn.qkv.weight": "model-00002-of-00002.safetensors",
579
+ "vpm.blocks.23.mlp.fc1.bias": "model-00002-of-00002.safetensors",
580
+ "vpm.blocks.23.mlp.fc1.weight": "model-00002-of-00002.safetensors",
581
+ "vpm.blocks.23.mlp.fc2.bias": "model-00002-of-00002.safetensors",
582
+ "vpm.blocks.23.mlp.fc2.weight": "model-00002-of-00002.safetensors",
583
+ "vpm.blocks.23.norm1.bias": "model-00002-of-00002.safetensors",
584
+ "vpm.blocks.23.norm1.weight": "model-00002-of-00002.safetensors",
585
+ "vpm.blocks.23.norm2.bias": "model-00002-of-00002.safetensors",
586
+ "vpm.blocks.23.norm2.weight": "model-00002-of-00002.safetensors",
587
+ "vpm.blocks.24.attn.proj.bias": "model-00002-of-00002.safetensors",
588
+ "vpm.blocks.24.attn.proj.weight": "model-00002-of-00002.safetensors",
589
+ "vpm.blocks.24.attn.qkv.bias": "model-00002-of-00002.safetensors",
590
+ "vpm.blocks.24.attn.qkv.weight": "model-00002-of-00002.safetensors",
591
+ "vpm.blocks.24.mlp.fc1.bias": "model-00002-of-00002.safetensors",
592
+ "vpm.blocks.24.mlp.fc1.weight": "model-00002-of-00002.safetensors",
593
+ "vpm.blocks.24.mlp.fc2.bias": "model-00002-of-00002.safetensors",
594
+ "vpm.blocks.24.mlp.fc2.weight": "model-00002-of-00002.safetensors",
595
+ "vpm.blocks.24.norm1.bias": "model-00002-of-00002.safetensors",
596
+ "vpm.blocks.24.norm1.weight": "model-00002-of-00002.safetensors",
597
+ "vpm.blocks.24.norm2.bias": "model-00002-of-00002.safetensors",
598
+ "vpm.blocks.24.norm2.weight": "model-00002-of-00002.safetensors",
599
+ "vpm.blocks.25.attn.proj.bias": "model-00002-of-00002.safetensors",
600
+ "vpm.blocks.25.attn.proj.weight": "model-00002-of-00002.safetensors",
601
+ "vpm.blocks.25.attn.qkv.bias": "model-00002-of-00002.safetensors",
602
+ "vpm.blocks.25.attn.qkv.weight": "model-00002-of-00002.safetensors",
603
+ "vpm.blocks.25.mlp.fc1.bias": "model-00002-of-00002.safetensors",
604
+ "vpm.blocks.25.mlp.fc1.weight": "model-00002-of-00002.safetensors",
605
+ "vpm.blocks.25.mlp.fc2.bias": "model-00002-of-00002.safetensors",
606
+ "vpm.blocks.25.mlp.fc2.weight": "model-00002-of-00002.safetensors",
607
+ "vpm.blocks.25.norm1.bias": "model-00002-of-00002.safetensors",
608
+ "vpm.blocks.25.norm1.weight": "model-00002-of-00002.safetensors",
609
+ "vpm.blocks.25.norm2.bias": "model-00002-of-00002.safetensors",
610
+ "vpm.blocks.25.norm2.weight": "model-00002-of-00002.safetensors",
611
+ "vpm.blocks.3.attn.proj.bias": "model-00002-of-00002.safetensors",
612
+ "vpm.blocks.3.attn.proj.weight": "model-00002-of-00002.safetensors",
613
+ "vpm.blocks.3.attn.qkv.bias": "model-00002-of-00002.safetensors",
614
+ "vpm.blocks.3.attn.qkv.weight": "model-00002-of-00002.safetensors",
615
+ "vpm.blocks.3.mlp.fc1.bias": "model-00002-of-00002.safetensors",
616
+ "vpm.blocks.3.mlp.fc1.weight": "model-00002-of-00002.safetensors",
617
+ "vpm.blocks.3.mlp.fc2.bias": "model-00002-of-00002.safetensors",
618
+ "vpm.blocks.3.mlp.fc2.weight": "model-00002-of-00002.safetensors",
619
+ "vpm.blocks.3.norm1.bias": "model-00002-of-00002.safetensors",
620
+ "vpm.blocks.3.norm1.weight": "model-00002-of-00002.safetensors",
621
+ "vpm.blocks.3.norm2.bias": "model-00002-of-00002.safetensors",
622
+ "vpm.blocks.3.norm2.weight": "model-00002-of-00002.safetensors",
623
+ "vpm.blocks.4.attn.proj.bias": "model-00002-of-00002.safetensors",
624
+ "vpm.blocks.4.attn.proj.weight": "model-00002-of-00002.safetensors",
625
+ "vpm.blocks.4.attn.qkv.bias": "model-00002-of-00002.safetensors",
626
+ "vpm.blocks.4.attn.qkv.weight": "model-00002-of-00002.safetensors",
627
+ "vpm.blocks.4.mlp.fc1.bias": "model-00002-of-00002.safetensors",
628
+ "vpm.blocks.4.mlp.fc1.weight": "model-00002-of-00002.safetensors",
629
+ "vpm.blocks.4.mlp.fc2.bias": "model-00002-of-00002.safetensors",
630
+ "vpm.blocks.4.mlp.fc2.weight": "model-00002-of-00002.safetensors",
631
+ "vpm.blocks.4.norm1.bias": "model-00002-of-00002.safetensors",
632
+ "vpm.blocks.4.norm1.weight": "model-00002-of-00002.safetensors",
633
+ "vpm.blocks.4.norm2.bias": "model-00002-of-00002.safetensors",
634
+ "vpm.blocks.4.norm2.weight": "model-00002-of-00002.safetensors",
635
+ "vpm.blocks.5.attn.proj.bias": "model-00002-of-00002.safetensors",
636
+ "vpm.blocks.5.attn.proj.weight": "model-00002-of-00002.safetensors",
637
+ "vpm.blocks.5.attn.qkv.bias": "model-00002-of-00002.safetensors",
638
+ "vpm.blocks.5.attn.qkv.weight": "model-00002-of-00002.safetensors",
639
+ "vpm.blocks.5.mlp.fc1.bias": "model-00002-of-00002.safetensors",
640
+ "vpm.blocks.5.mlp.fc1.weight": "model-00002-of-00002.safetensors",
641
+ "vpm.blocks.5.mlp.fc2.bias": "model-00002-of-00002.safetensors",
642
+ "vpm.blocks.5.mlp.fc2.weight": "model-00002-of-00002.safetensors",
643
+ "vpm.blocks.5.norm1.bias": "model-00002-of-00002.safetensors",
644
+ "vpm.blocks.5.norm1.weight": "model-00002-of-00002.safetensors",
645
+ "vpm.blocks.5.norm2.bias": "model-00002-of-00002.safetensors",
646
+ "vpm.blocks.5.norm2.weight": "model-00002-of-00002.safetensors",
647
+ "vpm.blocks.6.attn.proj.bias": "model-00002-of-00002.safetensors",
648
+ "vpm.blocks.6.attn.proj.weight": "model-00002-of-00002.safetensors",
649
+ "vpm.blocks.6.attn.qkv.bias": "model-00002-of-00002.safetensors",
650
+ "vpm.blocks.6.attn.qkv.weight": "model-00002-of-00002.safetensors",
651
+ "vpm.blocks.6.mlp.fc1.bias": "model-00002-of-00002.safetensors",
652
+ "vpm.blocks.6.mlp.fc1.weight": "model-00002-of-00002.safetensors",
653
+ "vpm.blocks.6.mlp.fc2.bias": "model-00002-of-00002.safetensors",
654
+ "vpm.blocks.6.mlp.fc2.weight": "model-00002-of-00002.safetensors",
655
+ "vpm.blocks.6.norm1.bias": "model-00002-of-00002.safetensors",
656
+ "vpm.blocks.6.norm1.weight": "model-00002-of-00002.safetensors",
657
+ "vpm.blocks.6.norm2.bias": "model-00002-of-00002.safetensors",
658
+ "vpm.blocks.6.norm2.weight": "model-00002-of-00002.safetensors",
659
+ "vpm.blocks.7.attn.proj.bias": "model-00002-of-00002.safetensors",
660
+ "vpm.blocks.7.attn.proj.weight": "model-00002-of-00002.safetensors",
661
+ "vpm.blocks.7.attn.qkv.bias": "model-00002-of-00002.safetensors",
662
+ "vpm.blocks.7.attn.qkv.weight": "model-00002-of-00002.safetensors",
663
+ "vpm.blocks.7.mlp.fc1.bias": "model-00002-of-00002.safetensors",
664
+ "vpm.blocks.7.mlp.fc1.weight": "model-00002-of-00002.safetensors",
665
+ "vpm.blocks.7.mlp.fc2.bias": "model-00002-of-00002.safetensors",
666
+ "vpm.blocks.7.mlp.fc2.weight": "model-00002-of-00002.safetensors",
667
+ "vpm.blocks.7.norm1.bias": "model-00002-of-00002.safetensors",
668
+ "vpm.blocks.7.norm1.weight": "model-00002-of-00002.safetensors",
669
+ "vpm.blocks.7.norm2.bias": "model-00002-of-00002.safetensors",
670
+ "vpm.blocks.7.norm2.weight": "model-00002-of-00002.safetensors",
671
+ "vpm.blocks.8.attn.proj.bias": "model-00002-of-00002.safetensors",
672
+ "vpm.blocks.8.attn.proj.weight": "model-00002-of-00002.safetensors",
673
+ "vpm.blocks.8.attn.qkv.bias": "model-00002-of-00002.safetensors",
674
+ "vpm.blocks.8.attn.qkv.weight": "model-00002-of-00002.safetensors",
675
+ "vpm.blocks.8.mlp.fc1.bias": "model-00002-of-00002.safetensors",
676
+ "vpm.blocks.8.mlp.fc1.weight": "model-00002-of-00002.safetensors",
677
+ "vpm.blocks.8.mlp.fc2.bias": "model-00002-of-00002.safetensors",
678
+ "vpm.blocks.8.mlp.fc2.weight": "model-00002-of-00002.safetensors",
679
+ "vpm.blocks.8.norm1.bias": "model-00002-of-00002.safetensors",
680
+ "vpm.blocks.8.norm1.weight": "model-00002-of-00002.safetensors",
681
+ "vpm.blocks.8.norm2.bias": "model-00002-of-00002.safetensors",
682
+ "vpm.blocks.8.norm2.weight": "model-00002-of-00002.safetensors",
683
+ "vpm.blocks.9.attn.proj.bias": "model-00002-of-00002.safetensors",
684
+ "vpm.blocks.9.attn.proj.weight": "model-00002-of-00002.safetensors",
685
+ "vpm.blocks.9.attn.qkv.bias": "model-00002-of-00002.safetensors",
686
+ "vpm.blocks.9.attn.qkv.weight": "model-00002-of-00002.safetensors",
687
+ "vpm.blocks.9.mlp.fc1.bias": "model-00002-of-00002.safetensors",
688
+ "vpm.blocks.9.mlp.fc1.weight": "model-00002-of-00002.safetensors",
689
+ "vpm.blocks.9.mlp.fc2.bias": "model-00002-of-00002.safetensors",
690
+ "vpm.blocks.9.mlp.fc2.weight": "model-00002-of-00002.safetensors",
691
+ "vpm.blocks.9.norm1.bias": "model-00002-of-00002.safetensors",
692
+ "vpm.blocks.9.norm1.weight": "model-00002-of-00002.safetensors",
693
+ "vpm.blocks.9.norm2.bias": "model-00002-of-00002.safetensors",
694
+ "vpm.blocks.9.norm2.weight": "model-00002-of-00002.safetensors",
695
+ "vpm.norm.bias": "model-00002-of-00002.safetensors",
696
+ "vpm.norm.weight": "model-00002-of-00002.safetensors",
697
+ "vpm.patch_embed.proj.bias": "model-00002-of-00002.safetensors",
698
+ "vpm.patch_embed.proj.weight": "model-00002-of-00002.safetensors",
699
+ "vpm.pos_embed": "model-00002-of-00002.safetensors"
700
+ }
701
+ }
modeling_minicpm.py ADDED
@@ -0,0 +1,1698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ PyTorch MiniCPM model."""
21
+ import math
22
+ import re
23
+ import warnings
24
+ from typing import Dict, List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import (
40
+ BaseModelOutputWithPast,
41
+ CausalLMOutputWithPast,
42
+ SequenceClassifierOutputWithPast,
43
+ )
44
+ from transformers.modeling_utils import PreTrainedModel
45
+ from transformers.pytorch_utils import (
46
+ ALL_LAYERNORM_LAYERS,
47
+ is_torch_greater_or_equal_than_1_13,
48
+ )
49
+ from transformers.utils import (
50
+ add_start_docstrings,
51
+ add_start_docstrings_to_model_forward,
52
+ is_flash_attn_2_available,
53
+ is_flash_attn_greater_or_equal_2_10,
54
+ logging,
55
+ replace_return_docstrings,
56
+ )
57
+ from transformers.utils.import_utils import is_torch_fx_available
58
+
59
+ from .configuration_minicpm import MiniCPMConfig
60
+
61
+ try:
62
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
63
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
64
+ except:
65
+ pass
66
+
67
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
68
+ # It means that the function will not be traced through and simply appear as a node in the graph.
69
+ if is_torch_fx_available():
70
+ if not is_torch_greater_or_equal_than_1_13:
71
+ import torch.fx
72
+
73
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+ _CONFIG_FOR_DOC = "MiniCPMConfig"
78
+
79
+
80
+ def _get_unpad_data(attention_mask):
81
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
82
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
83
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
84
+ cu_seqlens = F.pad(
85
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
86
+ )
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+
94
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
95
+ warnings.warn(
96
+ "Calling `transformers.models.minicpm.modeling_minicpm._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
97
+ )
98
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
99
+
100
+
101
+ def _make_causal_mask(
102
+ input_ids_shape: torch.Size,
103
+ dtype: torch.dtype,
104
+ device: torch.device,
105
+ past_key_values_length: int = 0,
106
+ ):
107
+ warnings.warn(
108
+ "Calling `transformers.models.minicpm.modeling_minicpm._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.minicpm.modeling_minicpm.AttentionMaskConverter._make_causal_mask"
109
+ )
110
+ return AttentionMaskConverter._make_causal_mask(
111
+ input_ids_shape=input_ids_shape,
112
+ dtype=dtype,
113
+ device=device,
114
+ past_key_values_length=past_key_values_length,
115
+ )
116
+
117
+
118
+ # @torch.jit.script # type: ignore
119
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
120
+ old_dtype = hidden.dtype
121
+ variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
122
+ hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
123
+ return hidden * weight
124
+
125
+
126
+ class MiniCPMRMSNorm(nn.Module):
127
+ def __init__(self, hidden_size, eps=1e-6):
128
+ """
129
+ MiniCPMRMSNorm is equivalent to T5LayerNorm
130
+ """
131
+ super().__init__()
132
+ self.weight = nn.Parameter(torch.ones(hidden_size))
133
+ self.variance_epsilon = eps
134
+
135
+ def forward(self, hidden_states):
136
+ return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
137
+
138
+
139
+ ALL_LAYERNORM_LAYERS.append(MiniCPMRMSNorm)
140
+
141
+
142
+ class MiniCPMRotaryEmbedding(nn.Module):
143
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
144
+ super().__init__()
145
+
146
+ self.dim = dim
147
+ self.max_position_embeddings = max_position_embeddings
148
+ self.base = base
149
+ inv_freq = 1.0 / (
150
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
151
+ )
152
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
153
+
154
+ # Build here to make `torch.jit.trace` work.
155
+ self._set_cos_sin_cache(
156
+ # seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
157
+ seq_len=max_position_embeddings,
158
+ device=self.inv_freq.device,
159
+ dtype=torch.float32,
160
+ )
161
+
162
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
163
+ self.max_seq_len_cached = seq_len
164
+ t = torch.arange(
165
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
166
+ )
167
+ freqs = torch.outer(t, self.inv_freq)
168
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
169
+ emb = torch.cat((freqs, freqs), dim=-1)
170
+
171
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
172
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
173
+
174
+ def forward(self, x, seq_len=None):
175
+ # x: [bs, num_attention_heads, seq_len, head_size]
176
+ if seq_len > self.max_seq_len_cached:
177
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
178
+
179
+ return (
180
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
181
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
182
+ )
183
+
184
+
185
+ class MiniCPMLinearScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
186
+ """MiniCPMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
187
+
188
+ def __init__(
189
+ self,
190
+ dim,
191
+ max_position_embeddings=2048,
192
+ base=10000,
193
+ device=None,
194
+ scaling_factor=1.0,
195
+ ):
196
+ self.scaling_factor = scaling_factor
197
+ super().__init__(dim, max_position_embeddings, base, device)
198
+
199
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
200
+ self.max_seq_len_cached = seq_len
201
+ t = torch.arange(
202
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
203
+ )
204
+ t = t / self.scaling_factor
205
+
206
+ freqs = torch.outer(t, self.inv_freq)
207
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
208
+ emb = torch.cat((freqs, freqs), dim=-1)
209
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
210
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
211
+
212
+
213
+ class MiniCPMDynamicNTKScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
214
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
215
+
216
+ def __init__(
217
+ self,
218
+ dim,
219
+ max_position_embeddings=2048,
220
+ base=10000,
221
+ device=None,
222
+ scaling_factor=1.0,
223
+ ):
224
+ self.scaling_factor = scaling_factor
225
+ super().__init__(dim, max_position_embeddings, base, device)
226
+
227
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
228
+ self.max_seq_len_cached = seq_len
229
+
230
+ if seq_len > self.max_position_embeddings:
231
+ base = self.base * (
232
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
233
+ - (self.scaling_factor - 1)
234
+ ) ** (self.dim / (self.dim - 2))
235
+ inv_freq = 1.0 / (
236
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
237
+ )
238
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
239
+
240
+ t = torch.arange(
241
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
242
+ )
243
+
244
+ freqs = torch.outer(t, self.inv_freq)
245
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
246
+ emb = torch.cat((freqs, freqs), dim=-1)
247
+
248
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
249
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
250
+
251
+
252
+ def rotate_half(x):
253
+ """Rotates half the hidden dims of the input."""
254
+ x1 = x[..., : x.shape[-1] // 2]
255
+ x2 = x[..., x.shape[-1] // 2 :]
256
+ return torch.cat((-x2, x1), dim=-1)
257
+
258
+
259
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
260
+ """Applies Rotary Position Embedding to the query and key tensors.
261
+ Args:
262
+ q (`torch.Tensor`): The query tensor.
263
+ k (`torch.Tensor`): The key tensor.
264
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
265
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
266
+ position_ids (`torch.Tensor`):
267
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
268
+ used to pass offsetted position ids when working with a KV-cache.
269
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
270
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
271
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
272
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
273
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
274
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
275
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
276
+ Returns:
277
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
278
+ """
279
+ # cos = cos[position_ids].unsqueeze(unsqueeze_dim)
280
+ # sin = sin[position_ids].unsqueeze(unsqueeze_dim)
281
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
282
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
283
+ orig_dtype = k.dtype
284
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
285
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
286
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
287
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
288
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
289
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
290
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
291
+
292
+
293
+ class MiniCPMMLP(nn.Module):
294
+ def __init__(self, config):
295
+ super().__init__()
296
+ self.config = config
297
+ self.hidden_size = config.hidden_size
298
+ self.intermediate_size = config.intermediate_size
299
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
300
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
301
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
302
+ self.act_fn = ACT2FN[config.hidden_act]
303
+
304
+ def forward(self, x):
305
+ if self.config.pretraining_tp > 1:
306
+ slice = self.intermediate_size // self.config.pretraining_tp
307
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
308
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
309
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
310
+
311
+ gate_proj = torch.cat(
312
+ [
313
+ F.linear(x, gate_proj_slices[i])
314
+ for i in range(self.config.pretraining_tp)
315
+ ],
316
+ dim=-1,
317
+ )
318
+ up_proj = torch.cat(
319
+ [
320
+ F.linear(x, up_proj_slices[i])
321
+ for i in range(self.config.pretraining_tp)
322
+ ],
323
+ dim=-1,
324
+ )
325
+
326
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
327
+ down_proj = [
328
+ F.linear(intermediate_states[i], down_proj_slices[i])
329
+ for i in range(self.config.pretraining_tp)
330
+ ]
331
+ down_proj = sum(down_proj)
332
+ else:
333
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
334
+
335
+ return down_proj
336
+
337
+
338
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
339
+ """
340
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
341
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
342
+ """
343
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
344
+ if n_rep == 1:
345
+ return hidden_states
346
+ hidden_states = hidden_states[:, :, None, :, :].expand(
347
+ batch, num_key_value_heads, n_rep, slen, head_dim
348
+ )
349
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
350
+
351
+
352
+ class MiniCPMAttention(nn.Module):
353
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
354
+
355
+ def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
356
+ super().__init__()
357
+ self.config = config
358
+ self.layer_idx = layer_idx
359
+ if layer_idx is None:
360
+ logger.warning_once(
361
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
362
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
363
+ "when creating this class."
364
+ )
365
+
366
+ self.attention_dropout = config.attention_dropout
367
+ self.hidden_size = config.hidden_size
368
+ self.num_heads = config.num_attention_heads
369
+ self.head_dim = self.hidden_size // self.num_heads
370
+ self.num_key_value_heads = config.num_key_value_heads
371
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
372
+ self.max_position_embeddings = config.max_position_embeddings
373
+ self.rope_theta = config.rope_theta
374
+ self.is_causal = True
375
+
376
+ if (self.head_dim * self.num_heads) != self.hidden_size:
377
+ raise ValueError(
378
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
379
+ f" and `num_heads`: {self.num_heads})."
380
+ )
381
+
382
+ self.q_proj = nn.Linear(
383
+ self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias
384
+ )
385
+ self.k_proj = nn.Linear(
386
+ self.hidden_size,
387
+ self.num_key_value_heads * self.head_dim,
388
+ bias=config.attention_bias,
389
+ )
390
+ self.v_proj = nn.Linear(
391
+ self.hidden_size,
392
+ self.num_key_value_heads * self.head_dim,
393
+ bias=config.attention_bias,
394
+ )
395
+ self.o_proj = nn.Linear(
396
+ self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias
397
+ )
398
+ self._init_rope()
399
+
400
+ def _init_rope(self):
401
+ if self.config.rope_scaling is None:
402
+ self.rotary_emb = MiniCPMRotaryEmbedding(
403
+ self.head_dim,
404
+ max_position_embeddings=self.max_position_embeddings,
405
+ base=self.rope_theta,
406
+ )
407
+ else:
408
+ scaling_type = self.config.rope_scaling["type"]
409
+ scaling_factor = self.config.rope_scaling["factor"]
410
+ if scaling_type == "linear":
411
+ self.rotary_emb = MiniCPMLinearScalingRotaryEmbedding(
412
+ self.head_dim,
413
+ max_position_embeddings=self.max_position_embeddings,
414
+ scaling_factor=scaling_factor,
415
+ base=self.rope_theta,
416
+ )
417
+ elif scaling_type == "dynamic":
418
+ self.rotary_emb = MiniCPMDynamicNTKScalingRotaryEmbedding(
419
+ self.head_dim,
420
+ max_position_embeddings=self.max_position_embeddings,
421
+ scaling_factor=scaling_factor,
422
+ base=self.rope_theta,
423
+ )
424
+ else:
425
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
426
+
427
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
428
+ return (
429
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
430
+ .transpose(1, 2)
431
+ .contiguous()
432
+ )
433
+
434
+ def forward(
435
+ self,
436
+ hidden_states: torch.Tensor,
437
+ attention_mask: Optional[torch.Tensor] = None,
438
+ position_ids: Optional[torch.LongTensor] = None,
439
+ past_key_value: Optional[Cache] = None,
440
+ output_attentions: bool = False,
441
+ use_cache: bool = False,
442
+ **kwargs,
443
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
444
+ if "padding_mask" in kwargs:
445
+ warnings.warn(
446
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
447
+ )
448
+
449
+ bsz, q_len, _ = hidden_states.size()
450
+
451
+ if self.config.pretraining_tp > 1:
452
+ key_value_slicing = (
453
+ self.num_key_value_heads * self.head_dim
454
+ ) // self.config.pretraining_tp
455
+ query_slices = self.q_proj.weight.split(
456
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
457
+ )
458
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
459
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
460
+
461
+ query_states = [
462
+ F.linear(hidden_states, query_slices[i])
463
+ for i in range(self.config.pretraining_tp)
464
+ ]
465
+ query_states = torch.cat(query_states, dim=-1)
466
+
467
+ key_states = [
468
+ F.linear(hidden_states, key_slices[i])
469
+ for i in range(self.config.pretraining_tp)
470
+ ]
471
+ key_states = torch.cat(key_states, dim=-1)
472
+
473
+ value_states = [
474
+ F.linear(hidden_states, value_slices[i])
475
+ for i in range(self.config.pretraining_tp)
476
+ ]
477
+ value_states = torch.cat(value_states, dim=-1)
478
+
479
+ else:
480
+ query_states = self.q_proj(hidden_states)
481
+ key_states = self.k_proj(hidden_states)
482
+ value_states = self.v_proj(hidden_states)
483
+
484
+ query_states = query_states.view(
485
+ bsz, q_len, self.num_heads, self.head_dim
486
+ ).transpose(1, 2)
487
+ key_states = key_states.view(
488
+ bsz, q_len, self.num_key_value_heads, self.head_dim
489
+ ).transpose(1, 2)
490
+ value_states = value_states.view(
491
+ bsz, q_len, self.num_key_value_heads, self.head_dim
492
+ ).transpose(1, 2)
493
+
494
+ kv_seq_len = key_states.shape[-2]
495
+ if past_key_value is not None:
496
+ if self.layer_idx is None:
497
+ raise ValueError(
498
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
499
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
500
+ "with a layer index."
501
+ )
502
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
503
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
504
+
505
+ query_states, key_states = apply_rotary_pos_emb(
506
+ query_states, key_states, cos, sin, position_ids
507
+ )
508
+
509
+ if past_key_value is not None:
510
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
511
+ key_states, value_states = past_key_value.update(
512
+ key_states, value_states, self.layer_idx, cache_kwargs
513
+ )
514
+
515
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
516
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
517
+
518
+ attn_weights = torch.matmul(
519
+ query_states, key_states.transpose(2, 3)
520
+ ) / math.sqrt(self.head_dim)
521
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
522
+ raise ValueError(
523
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
524
+ f" {attn_weights.size()}"
525
+ )
526
+
527
+ if attention_mask is not None:
528
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
529
+ raise ValueError(
530
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
531
+ )
532
+ attn_weights = attn_weights + attention_mask
533
+
534
+ # upcast attention to fp32
535
+ attn_weights = nn.functional.softmax(
536
+ attn_weights, dim=-1, dtype=torch.float32
537
+ ).to(query_states.dtype)
538
+ attn_weights = nn.functional.dropout(
539
+ attn_weights, p=self.attention_dropout, training=self.training
540
+ )
541
+ attn_output = torch.matmul(attn_weights, value_states)
542
+
543
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
544
+ raise ValueError(
545
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
546
+ f" {attn_output.size()}"
547
+ )
548
+
549
+ attn_output = attn_output.transpose(1, 2).contiguous()
550
+
551
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
552
+
553
+ if self.config.pretraining_tp > 1:
554
+ attn_output = attn_output.split(
555
+ self.hidden_size // self.config.pretraining_tp, dim=2
556
+ )
557
+ o_proj_slices = self.o_proj.weight.split(
558
+ self.hidden_size // self.config.pretraining_tp, dim=1
559
+ )
560
+ attn_output = sum(
561
+ [
562
+ F.linear(attn_output[i], o_proj_slices[i])
563
+ for i in range(self.config.pretraining_tp)
564
+ ]
565
+ )
566
+ else:
567
+ attn_output = self.o_proj(attn_output)
568
+
569
+ if not output_attentions:
570
+ attn_weights = None
571
+
572
+ return attn_output, attn_weights, past_key_value
573
+
574
+
575
+ class MiniCPMFlashAttention2(MiniCPMAttention):
576
+ """
577
+ MiniCPM flash attention module. This module inherits from `MiniCPMAttention` as the weights of the module stays
578
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
579
+ flash attention and deal with padding tokens in case the input contains any of them.
580
+ """
581
+
582
+ def __init__(self, *args, **kwargs):
583
+ super().__init__(*args, **kwargs)
584
+
585
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
586
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
587
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
588
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
589
+
590
+ def forward(
591
+ self,
592
+ hidden_states: torch.Tensor,
593
+ attention_mask: Optional[torch.LongTensor] = None,
594
+ position_ids: Optional[torch.LongTensor] = None,
595
+ past_key_value: Optional[Cache] = None,
596
+ output_attentions: bool = False,
597
+ use_cache: bool = False,
598
+ **kwargs,
599
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
600
+ # MiniCPMFlashAttention2 attention does not support output_attentions
601
+ if "padding_mask" in kwargs:
602
+ warnings.warn(
603
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
604
+ )
605
+
606
+ # overwrite attention_mask with padding_mask
607
+ attention_mask = kwargs.pop("padding_mask")
608
+
609
+ output_attentions = False
610
+
611
+ bsz, q_len, _ = hidden_states.size()
612
+
613
+ query_states = self.q_proj(hidden_states)
614
+ key_states = self.k_proj(hidden_states)
615
+ value_states = self.v_proj(hidden_states)
616
+
617
+ # Flash attention requires the input to have the shape
618
+ # batch_size x seq_length x head_dim x hidden_dim
619
+ # therefore we just need to keep the original shape
620
+ query_states = query_states.view(
621
+ bsz, q_len, self.num_heads, self.head_dim
622
+ ).transpose(1, 2)
623
+ key_states = key_states.view(
624
+ bsz, q_len, self.num_key_value_heads, self.head_dim
625
+ ).transpose(1, 2)
626
+ value_states = value_states.view(
627
+ bsz, q_len, self.num_key_value_heads, self.head_dim
628
+ ).transpose(1, 2)
629
+
630
+ kv_seq_len = key_states.shape[-2]
631
+ if past_key_value is not None:
632
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
633
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
634
+ query_states, key_states = apply_rotary_pos_emb(
635
+ query_states, key_states, cos, sin, position_ids
636
+ )
637
+
638
+ if past_key_value is not None:
639
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
640
+ key_states, value_states = past_key_value.update(
641
+ key_states, value_states, self.layer_idx, cache_kwargs
642
+ )
643
+
644
+ # 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
645
+ # to be able to avoid many of these transpose/reshape/view.
646
+ query_states = query_states.transpose(1, 2)
647
+ key_states = key_states.transpose(1, 2)
648
+ value_states = value_states.transpose(1, 2)
649
+
650
+ dropout_rate = self.attention_dropout if self.training else 0.0
651
+
652
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
653
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
654
+ # cast them back in the correct dtype just to be sure everything works as expected.
655
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
656
+ # in fp32. (MiniCPMRMSNorm handles it correctly)
657
+
658
+ input_dtype = query_states.dtype
659
+ if input_dtype == torch.float32:
660
+ # Handle the case where the model is quantized
661
+ if hasattr(self.config, "_pre_quantization_dtype"):
662
+ target_dtype = self.config._pre_quantization_dtype
663
+ else:
664
+ target_dtype = self.q_proj.weight.dtype
665
+
666
+ logger.warning_once(
667
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
668
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
669
+ f" {target_dtype}."
670
+ )
671
+
672
+ query_states = query_states.to(target_dtype)
673
+ key_states = key_states.to(target_dtype)
674
+ value_states = value_states.to(target_dtype)
675
+
676
+ attn_output = self._flash_attention_forward(
677
+ query_states,
678
+ key_states,
679
+ value_states,
680
+ attention_mask,
681
+ q_len,
682
+ dropout=dropout_rate,
683
+ )
684
+
685
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
686
+ attn_output = self.o_proj(attn_output)
687
+
688
+ if not output_attentions:
689
+ attn_weights = None
690
+
691
+ return attn_output, attn_weights, past_key_value
692
+
693
+ def _flash_attention_forward(
694
+ self,
695
+ query_states,
696
+ key_states,
697
+ value_states,
698
+ attention_mask,
699
+ query_length,
700
+ dropout=0.0,
701
+ softmax_scale=None,
702
+ ):
703
+ """
704
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
705
+ first unpad the input, then computes the attention scores and pad the final attention scores.
706
+ Args:
707
+ query_states (`torch.Tensor`):
708
+ Input query states to be passed to Flash Attention API
709
+ key_states (`torch.Tensor`):
710
+ Input key states to be passed to Flash Attention API
711
+ value_states (`torch.Tensor`):
712
+ Input value states to be passed to Flash Attention API
713
+ attention_mask (`torch.Tensor`):
714
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
715
+ position of padding tokens and 1 for the position of non-padding tokens.
716
+ dropout (`int`, *optional*):
717
+ Attention dropout
718
+ softmax_scale (`float`, *optional*):
719
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
720
+ """
721
+ if not self._flash_attn_uses_top_left_mask:
722
+ causal = self.is_causal
723
+ else:
724
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in MiniCPMFlashAttention2 __init__.
725
+ causal = self.is_causal and query_length != 1
726
+ # Contains at least one padding token in the sequence
727
+ if attention_mask is not None:
728
+ batch_size = query_states.shape[0]
729
+ (
730
+ query_states,
731
+ key_states,
732
+ value_states,
733
+ indices_q,
734
+ cu_seq_lens,
735
+ max_seq_lens,
736
+ ) = self._upad_input(
737
+ query_states, key_states, value_states, attention_mask, query_length
738
+ )
739
+
740
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
741
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
742
+ attn_output_unpad = flash_attn_varlen_func(
743
+ query_states,
744
+ key_states,
745
+ value_states,
746
+ cu_seqlens_q=cu_seqlens_q,
747
+ cu_seqlens_k=cu_seqlens_k,
748
+ max_seqlen_q=max_seqlen_in_batch_q,
749
+ max_seqlen_k=max_seqlen_in_batch_k,
750
+ dropout_p=dropout,
751
+ softmax_scale=softmax_scale,
752
+ causal=causal,
753
+ )
754
+
755
+ attn_output = pad_input(
756
+ attn_output_unpad, indices_q, batch_size, query_length
757
+ )
758
+ else:
759
+ attn_output = flash_attn_func(
760
+ query_states,
761
+ key_states,
762
+ value_states,
763
+ dropout,
764
+ softmax_scale=softmax_scale,
765
+ causal=causal,
766
+ )
767
+
768
+ return attn_output
769
+
770
+ def _upad_input(
771
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
772
+ ):
773
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
774
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
775
+
776
+ key_layer = index_first_axis(
777
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
778
+ indices_k,
779
+ )
780
+ value_layer = index_first_axis(
781
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
782
+ indices_k,
783
+ )
784
+ if query_length == kv_seq_len:
785
+ query_layer = index_first_axis(
786
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
787
+ indices_k,
788
+ )
789
+ cu_seqlens_q = cu_seqlens_k
790
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
791
+ indices_q = indices_k
792
+ elif query_length == 1:
793
+ max_seqlen_in_batch_q = 1
794
+ cu_seqlens_q = torch.arange(
795
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
796
+ ) # There is a memcpy here, that is very bad.
797
+ indices_q = cu_seqlens_q[:-1]
798
+ query_layer = query_layer.squeeze(1)
799
+ else:
800
+ # The -q_len: slice assumes left padding.
801
+ attention_mask = attention_mask[:, -query_length:]
802
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
803
+ query_layer, attention_mask
804
+ )
805
+
806
+ return (
807
+ query_layer,
808
+ key_layer,
809
+ value_layer,
810
+ indices_q,
811
+ (cu_seqlens_q, cu_seqlens_k),
812
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
813
+ )
814
+
815
+
816
+ class MiniCPMSdpaAttention(MiniCPMAttention):
817
+ """
818
+ MiniCPM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
819
+ `MiniCPMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
820
+ SDPA API.
821
+ """
822
+
823
+ # Adapted from MiniCPMAttention.forward
824
+ def forward(
825
+ self,
826
+ hidden_states: torch.Tensor,
827
+ attention_mask: Optional[torch.Tensor] = None,
828
+ position_ids: Optional[torch.LongTensor] = None,
829
+ past_key_value: Optional[Cache] = None,
830
+ output_attentions: bool = False,
831
+ use_cache: bool = False,
832
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
833
+ if output_attentions:
834
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
835
+ logger.warning_once(
836
+ "MiniCPMModel is using MiniCPMSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
837
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
838
+ )
839
+ return super().forward(
840
+ hidden_states=hidden_states,
841
+ attention_mask=attention_mask,
842
+ position_ids=position_ids,
843
+ past_key_value=past_key_value,
844
+ output_attentions=output_attentions,
845
+ use_cache=use_cache,
846
+ )
847
+
848
+ bsz, q_len, _ = hidden_states.size()
849
+
850
+ query_states = self.q_proj(hidden_states)
851
+ key_states = self.k_proj(hidden_states)
852
+ value_states = self.v_proj(hidden_states)
853
+
854
+ query_states = query_states.view(
855
+ bsz, q_len, self.num_heads, self.head_dim
856
+ ).transpose(1, 2)
857
+ key_states = key_states.view(
858
+ bsz, q_len, self.num_key_value_heads, self.head_dim
859
+ ).transpose(1, 2)
860
+ value_states = value_states.view(
861
+ bsz, q_len, self.num_key_value_heads, self.head_dim
862
+ ).transpose(1, 2)
863
+
864
+ kv_seq_len = key_states.shape[-2]
865
+ if past_key_value is not None:
866
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
867
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
868
+
869
+ query_states, key_states = apply_rotary_pos_emb(
870
+ query_states, key_states, cos, sin, position_ids
871
+ )
872
+
873
+ if past_key_value is not None:
874
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
875
+ key_states, value_states = past_key_value.update(
876
+ key_states, value_states, self.layer_idx, cache_kwargs
877
+ )
878
+
879
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
880
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
881
+
882
+ if attention_mask is not None:
883
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
884
+ raise ValueError(
885
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
886
+ )
887
+
888
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
889
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
890
+ if query_states.device.type == "cuda" and attention_mask is not None:
891
+ query_states = query_states.contiguous()
892
+ key_states = key_states.contiguous()
893
+ value_states = value_states.contiguous()
894
+
895
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
896
+ query_states,
897
+ key_states,
898
+ value_states,
899
+ attn_mask=attention_mask,
900
+ dropout_p=self.attention_dropout if self.training else 0.0,
901
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
902
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
903
+ )
904
+
905
+ attn_output = attn_output.transpose(1, 2).contiguous()
906
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
907
+
908
+ attn_output = self.o_proj(attn_output)
909
+
910
+ return attn_output, None, past_key_value
911
+
912
+
913
+ MINICPM_ATTENTION_CLASSES = {
914
+ "eager": MiniCPMAttention,
915
+ "flash_attention_2": MiniCPMFlashAttention2,
916
+ "sdpa": MiniCPMSdpaAttention,
917
+ }
918
+
919
+
920
+ class MiniCPMDecoderLayer(nn.Module):
921
+ def __init__(self, config: MiniCPMConfig, layer_idx: int):
922
+ super().__init__()
923
+ self.hidden_size = config.hidden_size
924
+ self.self_attn = MINICPM_ATTENTION_CLASSES[config._attn_implementation](
925
+ config=config, layer_idx=layer_idx
926
+ )
927
+
928
+ self.mlp = MiniCPMMLP(config)
929
+ self.input_layernorm = MiniCPMRMSNorm(
930
+ config.hidden_size, eps=config.rms_norm_eps
931
+ )
932
+ self.post_attention_layernorm = MiniCPMRMSNorm(
933
+ config.hidden_size, eps=config.rms_norm_eps
934
+ )
935
+
936
+ self.scale_depth = config.scale_depth
937
+ self.num_hidden_layers = config.num_hidden_layers
938
+
939
+ def forward(
940
+ self,
941
+ hidden_states: torch.Tensor,
942
+ attention_mask: Optional[torch.Tensor] = None,
943
+ position_ids: Optional[torch.LongTensor] = None,
944
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
945
+ output_attentions: Optional[bool] = False,
946
+ use_cache: Optional[bool] = False,
947
+ **kwargs,
948
+ ) -> Tuple[
949
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
950
+ ]:
951
+ """
952
+ Args:
953
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
954
+ attention_mask (`torch.FloatTensor`, *optional*):
955
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
956
+ query_sequence_length, key_sequence_length)` if default attention is used.
957
+ output_attentions (`bool`, *optional*):
958
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
959
+ returned tensors for more detail.
960
+ use_cache (`bool`, *optional*):
961
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
962
+ (see `past_key_values`).
963
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
964
+ """
965
+ if "padding_mask" in kwargs:
966
+ warnings.warn(
967
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
968
+ )
969
+
970
+ residual = hidden_states
971
+ hidden_states = self.input_layernorm(hidden_states)
972
+ # Self Attention
973
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
974
+ hidden_states=hidden_states,
975
+ attention_mask=attention_mask,
976
+ position_ids=position_ids,
977
+ past_key_value=past_key_value,
978
+ output_attentions=output_attentions,
979
+ use_cache=use_cache,
980
+ **kwargs,
981
+ )
982
+
983
+ hidden_states = residual + hidden_states * (
984
+ self.scale_depth / math.sqrt(self.num_hidden_layers)
985
+ )
986
+
987
+ # Fully Connected
988
+ residual = hidden_states
989
+ hidden_states = self.post_attention_layernorm(hidden_states)
990
+
991
+ hidden_states = self.mlp(hidden_states)
992
+ hidden_states = residual + hidden_states * (
993
+ self.scale_depth / math.sqrt(self.num_hidden_layers)
994
+ )
995
+
996
+ outputs = (hidden_states,)
997
+
998
+ if output_attentions:
999
+ outputs += (self_attn_weights,)
1000
+
1001
+ if use_cache:
1002
+ outputs += (present_key_value,)
1003
+
1004
+ return outputs
1005
+
1006
+
1007
+ MINICPM_START_DOCSTRING = r"""
1008
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1009
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1010
+ etc.)
1011
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1012
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1013
+ and behavior.
1014
+ Parameters:
1015
+ config ([`MiniCPMConfig`]):
1016
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1017
+ load the weights associated with the model, only the configuration. Check out the
1018
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1019
+ """
1020
+
1021
+
1022
+ @add_start_docstrings(
1023
+ "The bare MiniCPM Model outputting raw hidden-states without any specific head on top.",
1024
+ MINICPM_START_DOCSTRING,
1025
+ )
1026
+ class MiniCPMPreTrainedModel(PreTrainedModel):
1027
+ config_class = MiniCPMConfig
1028
+ base_model_prefix = "model"
1029
+ supports_gradient_checkpointing = True
1030
+ _no_split_modules = ["MiniCPMDecoderLayer"]
1031
+ _skip_keys_device_placement = "past_key_values"
1032
+ _supports_flash_attn_2 = True
1033
+ _supports_sdpa = True
1034
+ _supports_cache_class = True
1035
+
1036
+ def _init_weights(self, module):
1037
+ std = self.config.initializer_range
1038
+ if isinstance(module, nn.Linear):
1039
+ module.weight.data.normal_(mean=0.0, std=std)
1040
+ if module.bias is not None:
1041
+ module.bias.data.zero_()
1042
+ elif isinstance(module, nn.Embedding):
1043
+ module.weight.data.normal_(mean=0.0, std=std)
1044
+ if module.padding_idx is not None:
1045
+ module.weight.data[module.padding_idx].zero_()
1046
+
1047
+
1048
+ MINICPM_INPUTS_DOCSTRING = r"""
1049
+ Args:
1050
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1051
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1052
+ it.
1053
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1054
+ [`PreTrainedTokenizer.__call__`] for details.
1055
+ [What are input IDs?](../glossary#input-ids)
1056
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1057
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1058
+ - 1 for tokens that are **not masked**,
1059
+ - 0 for tokens that are **masked**.
1060
+ [What are attention masks?](../glossary#attention-mask)
1061
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1062
+ [`PreTrainedTokenizer.__call__`] for details.
1063
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1064
+ `past_key_values`).
1065
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1066
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1067
+ information on the default strategy.
1068
+ - 1 indicates the head is **not masked**,
1069
+ - 0 indicates the head is **masked**.
1070
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1071
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1072
+ config.n_positions - 1]`.
1073
+ [What are position IDs?](../glossary#position-ids)
1074
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1075
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1076
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1077
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1078
+ Two formats are allowed:
1079
+ - a [`~cache_utils.Cache`] instance;
1080
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1081
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1082
+ cache format.
1083
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1084
+ legacy cache format will be returned.
1085
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1086
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1087
+ of shape `(batch_size, sequence_length)`.
1088
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1089
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1090
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1091
+ model's internal embedding lookup matrix.
1092
+ use_cache (`bool`, *optional*):
1093
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1094
+ `past_key_values`).
1095
+ output_attentions (`bool`, *optional*):
1096
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1097
+ tensors for more detail.
1098
+ output_hidden_states (`bool`, *optional*):
1099
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1100
+ more detail.
1101
+ return_dict (`bool`, *optional*):
1102
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1103
+ """
1104
+
1105
+
1106
+ @add_start_docstrings(
1107
+ "The bare MiniCPM Model outputting raw hidden-states without any specific head on top.",
1108
+ MINICPM_START_DOCSTRING,
1109
+ )
1110
+ class MiniCPMModel(MiniCPMPreTrainedModel):
1111
+ """
1112
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
1113
+ Args:
1114
+ config: MiniCPMConfig
1115
+ """
1116
+
1117
+ def __init__(self, config: MiniCPMConfig):
1118
+ super().__init__(config)
1119
+ self.padding_idx = config.pad_token_id
1120
+ self.vocab_size = config.vocab_size
1121
+
1122
+ self.embed_tokens = nn.Embedding(
1123
+ config.vocab_size, config.hidden_size, self.padding_idx
1124
+ )
1125
+ self.layers = nn.ModuleList(
1126
+ [
1127
+ MiniCPMDecoderLayer(config, layer_idx)
1128
+ for layer_idx in range(config.num_hidden_layers)
1129
+ ]
1130
+ )
1131
+ self._use_sdpa = config._attn_implementation == "sdpa"
1132
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1133
+
1134
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1135
+
1136
+ self.gradient_checkpointing = False
1137
+ # Initialize weights and apply final processing
1138
+ self.post_init()
1139
+
1140
+ def get_input_embeddings(self):
1141
+ return self.embed_tokens
1142
+
1143
+ def set_input_embeddings(self, value):
1144
+ self.embed_tokens = value
1145
+
1146
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1147
+ def forward(
1148
+ self,
1149
+ input_ids: torch.LongTensor = None,
1150
+ attention_mask: Optional[torch.Tensor] = None,
1151
+ position_ids: Optional[torch.LongTensor] = None,
1152
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1153
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1154
+ use_cache: Optional[bool] = None,
1155
+ output_attentions: Optional[bool] = None,
1156
+ output_hidden_states: Optional[bool] = None,
1157
+ return_dict: Optional[bool] = None,
1158
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1159
+ # print("attention mask", attention_mask)
1160
+ output_attentions = (
1161
+ output_attentions
1162
+ if output_attentions is not None
1163
+ else self.config.output_attentions
1164
+ )
1165
+ output_hidden_states = (
1166
+ output_hidden_states
1167
+ if output_hidden_states is not None
1168
+ else self.config.output_hidden_states
1169
+ )
1170
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1171
+
1172
+ return_dict = (
1173
+ return_dict if return_dict is not None else self.config.use_return_dict
1174
+ )
1175
+
1176
+ # retrieve input_ids and inputs_embeds
1177
+ if input_ids is not None and inputs_embeds is not None:
1178
+ raise ValueError(
1179
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1180
+ )
1181
+ elif input_ids is not None:
1182
+ batch_size, seq_length = input_ids.shape[:2]
1183
+ elif inputs_embeds is not None:
1184
+ batch_size, seq_length = inputs_embeds.shape[:2]
1185
+ else:
1186
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1187
+
1188
+ if self.gradient_checkpointing and self.training:
1189
+ if use_cache:
1190
+ logger.warning_once(
1191
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1192
+ )
1193
+ use_cache = False
1194
+
1195
+ past_key_values_length = 0
1196
+ if use_cache:
1197
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1198
+ if use_legacy_cache:
1199
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1200
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1201
+
1202
+ if position_ids is None:
1203
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1204
+ position_ids = torch.arange(
1205
+ past_key_values_length,
1206
+ seq_length + past_key_values_length,
1207
+ dtype=torch.long,
1208
+ device=device,
1209
+ )
1210
+ position_ids = position_ids.unsqueeze(0)
1211
+
1212
+ if inputs_embeds is None:
1213
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1214
+
1215
+ if self._use_flash_attention_2:
1216
+ # 2d mask is passed through the layers
1217
+ attention_mask = (
1218
+ attention_mask
1219
+ if (attention_mask is not None and 0 in attention_mask)
1220
+ else None
1221
+ )
1222
+ elif self._use_sdpa and not output_attentions:
1223
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1224
+ # the manual implementation that requires a 4D causal mask in all cases.
1225
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1226
+ attention_mask,
1227
+ (batch_size, seq_length),
1228
+ inputs_embeds,
1229
+ past_key_values_length,
1230
+ )
1231
+ else:
1232
+ # 4d mask is passed through the layers
1233
+ attention_mask = _prepare_4d_causal_attention_mask(
1234
+ attention_mask,
1235
+ (batch_size, seq_length),
1236
+ inputs_embeds,
1237
+ past_key_values_length,
1238
+ )
1239
+
1240
+ # embed positions
1241
+ hidden_states = inputs_embeds
1242
+
1243
+ # decoder layers
1244
+ all_hidden_states = () if output_hidden_states else None
1245
+ all_self_attns = () if output_attentions else None
1246
+ next_decoder_cache = None
1247
+
1248
+ for decoder_layer in self.layers:
1249
+ if output_hidden_states:
1250
+ all_hidden_states += (hidden_states,)
1251
+
1252
+ if self.gradient_checkpointing and self.training:
1253
+ layer_outputs = self._gradient_checkpointing_func(
1254
+ decoder_layer.__call__,
1255
+ hidden_states,
1256
+ attention_mask,
1257
+ position_ids,
1258
+ past_key_values,
1259
+ output_attentions,
1260
+ use_cache,
1261
+ )
1262
+ else:
1263
+ layer_outputs = decoder_layer(
1264
+ hidden_states,
1265
+ attention_mask=attention_mask,
1266
+ position_ids=position_ids,
1267
+ past_key_value=past_key_values,
1268
+ output_attentions=output_attentions,
1269
+ use_cache=use_cache,
1270
+ )
1271
+
1272
+ hidden_states = layer_outputs[0]
1273
+
1274
+ if use_cache:
1275
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1276
+
1277
+ if output_attentions:
1278
+ all_self_attns += (layer_outputs[1],)
1279
+
1280
+ hidden_states = self.norm(hidden_states)
1281
+
1282
+ # add hidden states from the last decoder layer
1283
+ if output_hidden_states:
1284
+ all_hidden_states += (hidden_states,)
1285
+
1286
+ next_cache = None
1287
+ if use_cache:
1288
+ next_cache = (
1289
+ next_decoder_cache.to_legacy_cache()
1290
+ if use_legacy_cache
1291
+ else next_decoder_cache
1292
+ )
1293
+ if not return_dict:
1294
+ return tuple(
1295
+ v
1296
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1297
+ if v is not None
1298
+ )
1299
+ return BaseModelOutputWithPast(
1300
+ last_hidden_state=hidden_states,
1301
+ past_key_values=next_cache,
1302
+ hidden_states=all_hidden_states,
1303
+ attentions=all_self_attns,
1304
+ )
1305
+
1306
+
1307
+ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
1308
+ _tied_weights_keys = ["lm_head.weight"]
1309
+
1310
+ def __init__(self, config):
1311
+ super().__init__(config)
1312
+ self.model = MiniCPMModel(config)
1313
+ self.vocab_size = config.vocab_size
1314
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1315
+
1316
+ # Initialize weights and apply final processing
1317
+ self.post_init()
1318
+
1319
+ def get_input_embeddings(self):
1320
+ return self.model.embed_tokens
1321
+
1322
+ def set_input_embeddings(self, value):
1323
+ self.model.embed_tokens = value
1324
+
1325
+ def get_output_embeddings(self):
1326
+ return self.lm_head
1327
+
1328
+ def set_output_embeddings(self, new_embeddings):
1329
+ self.lm_head = new_embeddings
1330
+
1331
+ def set_decoder(self, decoder):
1332
+ self.model = decoder
1333
+
1334
+ def get_decoder(self):
1335
+ return self.model
1336
+
1337
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1338
+ @replace_return_docstrings(
1339
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1340
+ )
1341
+ def forward(
1342
+ self,
1343
+ input_ids: torch.LongTensor = None,
1344
+ attention_mask: Optional[torch.Tensor] = None,
1345
+ position_ids: Optional[torch.LongTensor] = None,
1346
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1347
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1348
+ labels: Optional[torch.LongTensor] = None,
1349
+ use_cache: Optional[bool] = None,
1350
+ output_attentions: Optional[bool] = None,
1351
+ output_hidden_states: Optional[bool] = None,
1352
+ return_dict: Optional[bool] = None,
1353
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1354
+ r"""
1355
+ Args:
1356
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1357
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1358
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1359
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1360
+ Returns:
1361
+ Example:
1362
+ ```python
1363
+ >>> from transformers import AutoTokenizer, MiniCPMForCausalLM
1364
+ >>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1365
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1366
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1367
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1368
+ >>> # Generate
1369
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1370
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1371
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1372
+ ```"""
1373
+ output_attentions = (
1374
+ output_attentions
1375
+ if output_attentions is not None
1376
+ else self.config.output_attentions
1377
+ )
1378
+ output_hidden_states = (
1379
+ output_hidden_states
1380
+ if output_hidden_states is not None
1381
+ else self.config.output_hidden_states
1382
+ )
1383
+ return_dict = (
1384
+ return_dict if return_dict is not None else self.config.use_return_dict
1385
+ )
1386
+
1387
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1388
+ outputs = self.model(
1389
+ input_ids=input_ids,
1390
+ attention_mask=attention_mask,
1391
+ position_ids=position_ids,
1392
+ past_key_values=past_key_values,
1393
+ inputs_embeds=inputs_embeds,
1394
+ use_cache=use_cache,
1395
+ output_attentions=output_attentions,
1396
+ output_hidden_states=output_hidden_states,
1397
+ return_dict=return_dict,
1398
+ )
1399
+
1400
+ hidden_states = outputs[0]
1401
+ if self.config.pretraining_tp > 1:
1402
+ lm_head_slices = self.lm_head.weight.split(
1403
+ self.vocab_size // self.config.pretraining_tp, dim=0
1404
+ )
1405
+ logits = [
1406
+ F.linear(hidden_states, lm_head_slices[i])
1407
+ for i in range(self.config.pretraining_tp)
1408
+ ]
1409
+ logits = torch.cat(logits, dim=-1)
1410
+ else:
1411
+ logits = self.lm_head(
1412
+ hidden_states / (self.config.hidden_size / self.config.dim_model_base)
1413
+ )
1414
+ logits = logits.float()
1415
+
1416
+ loss = None
1417
+ if labels is not None:
1418
+ # Shift so that tokens < n predict n
1419
+ shift_logits = logits[..., :-1, :].contiguous()
1420
+ shift_labels = labels[..., 1:].contiguous()
1421
+ # Flatten the tokens
1422
+ loss_fct = CrossEntropyLoss()
1423
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1424
+ shift_labels = shift_labels.view(-1)
1425
+ # Enable model parallelism
1426
+ shift_labels = shift_labels.to(shift_logits.device)
1427
+ loss = loss_fct(shift_logits, shift_labels)
1428
+
1429
+ if not return_dict:
1430
+ output = (logits,) + outputs[1:]
1431
+ return (loss,) + output if loss is not None else output
1432
+
1433
+ return CausalLMOutputWithPast(
1434
+ loss=loss,
1435
+ logits=logits,
1436
+ past_key_values=outputs.past_key_values,
1437
+ hidden_states=outputs.hidden_states,
1438
+ attentions=outputs.attentions,
1439
+ )
1440
+
1441
+ def prepare_inputs_for_generation(
1442
+ self,
1443
+ input_ids,
1444
+ past_key_values=None,
1445
+ attention_mask=None,
1446
+ inputs_embeds=None,
1447
+ **kwargs,
1448
+ ):
1449
+ if past_key_values is not None:
1450
+ if isinstance(past_key_values, Cache):
1451
+ cache_length = past_key_values.get_seq_length()
1452
+ past_length = past_key_values.seen_tokens
1453
+ max_cache_length = past_key_values.get_max_length()
1454
+ else:
1455
+ cache_length = past_length = past_key_values[0][0].shape[2]
1456
+ max_cache_length = None
1457
+
1458
+ # Keep only the unprocessed tokens:
1459
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1460
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1461
+ # input)
1462
+ if (
1463
+ attention_mask is not None
1464
+ and attention_mask.shape[1] > input_ids.shape[1]
1465
+ ):
1466
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1467
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1468
+ # input_ids based on the past_length.
1469
+ elif past_length < input_ids.shape[1]:
1470
+ input_ids = input_ids[:, past_length:]
1471
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1472
+
1473
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1474
+ if (
1475
+ max_cache_length is not None
1476
+ and attention_mask is not None
1477
+ and cache_length + input_ids.shape[1] > max_cache_length
1478
+ ):
1479
+ attention_mask = attention_mask[:, -max_cache_length:]
1480
+
1481
+ position_ids = kwargs.get("position_ids", None)
1482
+ if attention_mask is not None and position_ids is None:
1483
+ # create position_ids on the fly for batch generation
1484
+ position_ids = attention_mask.long().cumsum(-1) - 1
1485
+ position_ids.masked_fill_(attention_mask == 0, 1)
1486
+ if past_key_values:
1487
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1488
+
1489
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1490
+ if inputs_embeds is not None and past_key_values is None:
1491
+ model_inputs = {"inputs_embeds": inputs_embeds}
1492
+ else:
1493
+ model_inputs = {"input_ids": input_ids}
1494
+
1495
+ model_inputs.update(
1496
+ {
1497
+ "position_ids": position_ids,
1498
+ "past_key_values": past_key_values,
1499
+ "use_cache": kwargs.get("use_cache"),
1500
+ "attention_mask": attention_mask,
1501
+ }
1502
+ )
1503
+ return model_inputs
1504
+
1505
+ @staticmethod
1506
+ def _reorder_cache(past_key_values, beam_idx):
1507
+ reordered_past = ()
1508
+ for layer_past in past_key_values:
1509
+ reordered_past += (
1510
+ tuple(
1511
+ past_state.index_select(0, beam_idx.to(past_state.device))
1512
+ for past_state in layer_past
1513
+ ),
1514
+ )
1515
+ return reordered_past
1516
+
1517
+ @torch.inference_mode()
1518
+ def chat(
1519
+ self,
1520
+ tokenizer,
1521
+ query: str,
1522
+ history: List[Dict] = None,
1523
+ role: str = "user",
1524
+ max_length: int = 4096,
1525
+ num_beams=1,
1526
+ do_sample=True,
1527
+ top_p=0.8,
1528
+ temperature=0.3,
1529
+ logits_processor=None,
1530
+ **kwargs,
1531
+ ):
1532
+ if history is None:
1533
+ history = []
1534
+ if logits_processor:
1535
+ gen_kwargs = {
1536
+ "max_length": max_length,
1537
+ "num_beams": num_beams,
1538
+ "do_sample": do_sample,
1539
+ "top_p": top_p,
1540
+ "temperature": temperature,
1541
+ "logits_processor": logits_processor,
1542
+ **kwargs,
1543
+ }
1544
+ else:
1545
+ gen_kwargs = {
1546
+ "max_length": max_length,
1547
+ "num_beams": num_beams,
1548
+ "do_sample": do_sample,
1549
+ "top_p": top_p,
1550
+ "temperature": temperature,
1551
+ "logits_processor": logits_processor,
1552
+ **kwargs,
1553
+ }
1554
+
1555
+ history.append({"role": role, "content": query})
1556
+ history_str = tokenizer.apply_chat_template(
1557
+ history, tokenize=False, add_generation_prompt=False
1558
+ )
1559
+ inputs = tokenizer(history_str, return_tensors="pt").to(self.device)
1560
+ outputs = self.generate(**inputs, **gen_kwargs)
1561
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]) : -1]
1562
+ response = tokenizer.decode(outputs)
1563
+ pattern = re.compile(r".*?(?=<AI>|<用户>)", re.DOTALL)
1564
+ matches = pattern.findall(response)
1565
+ if len(matches) > 0:
1566
+ response = matches[0]
1567
+ history.append({"role": "assistant", "content": response})
1568
+ return response, history
1569
+
1570
+
1571
+ @add_start_docstrings(
1572
+ """
1573
+ The MiniCPM Model transformer with a sequence classification head on top (linear layer).
1574
+ [`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1575
+ (e.g. GPT-2) do.
1576
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1577
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1578
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1579
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1580
+ each row of the batch).
1581
+ """,
1582
+ MINICPM_START_DOCSTRING,
1583
+ )
1584
+ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
1585
+ def __init__(self, config):
1586
+ super().__init__(config)
1587
+ self.num_labels = config.num_labels
1588
+ self.model = MiniCPMModel(config)
1589
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1590
+
1591
+ # Initialize weights and apply final processing
1592
+ self.post_init()
1593
+
1594
+ def get_input_embeddings(self):
1595
+ return self.model.embed_tokens
1596
+
1597
+ def set_input_embeddings(self, value):
1598
+ self.model.embed_tokens = value
1599
+
1600
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1601
+ def forward(
1602
+ self,
1603
+ input_ids: torch.LongTensor = None,
1604
+ attention_mask: Optional[torch.Tensor] = None,
1605
+ position_ids: Optional[torch.LongTensor] = None,
1606
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1607
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1608
+ labels: Optional[torch.LongTensor] = None,
1609
+ use_cache: Optional[bool] = None,
1610
+ output_attentions: Optional[bool] = None,
1611
+ output_hidden_states: Optional[bool] = None,
1612
+ return_dict: Optional[bool] = None,
1613
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1614
+ r"""
1615
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1616
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1617
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1618
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1619
+ """
1620
+ return_dict = (
1621
+ return_dict if return_dict is not None else self.config.use_return_dict
1622
+ )
1623
+
1624
+ transformer_outputs = self.model(
1625
+ input_ids,
1626
+ attention_mask=attention_mask,
1627
+ position_ids=position_ids,
1628
+ past_key_values=past_key_values,
1629
+ inputs_embeds=inputs_embeds,
1630
+ use_cache=use_cache,
1631
+ output_attentions=output_attentions,
1632
+ output_hidden_states=output_hidden_states,
1633
+ return_dict=return_dict,
1634
+ )
1635
+ hidden_states = transformer_outputs[0]
1636
+ logits = self.score(hidden_states)
1637
+
1638
+ if input_ids is not None:
1639
+ batch_size = input_ids.shape[0]
1640
+ else:
1641
+ batch_size = inputs_embeds.shape[0]
1642
+
1643
+ if self.config.pad_token_id is None and batch_size != 1:
1644
+ raise ValueError(
1645
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1646
+ )
1647
+ if self.config.pad_token_id is None:
1648
+ sequence_lengths = -1
1649
+ else:
1650
+ if input_ids is not None:
1651
+ sequence_lengths = (
1652
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1653
+ ).to(logits.device)
1654
+ else:
1655
+ sequence_lengths = -1
1656
+
1657
+ pooled_logits = logits[
1658
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1659
+ ]
1660
+
1661
+ loss = None
1662
+ if labels is not None:
1663
+ labels = labels.to(logits.device)
1664
+ if self.config.problem_type is None:
1665
+ if self.num_labels == 1:
1666
+ self.config.problem_type = "regression"
1667
+ elif self.num_labels > 1 and (
1668
+ labels.dtype == torch.long or labels.dtype == torch.int
1669
+ ):
1670
+ self.config.problem_type = "single_label_classification"
1671
+ else:
1672
+ self.config.problem_type = "multi_label_classification"
1673
+
1674
+ if self.config.problem_type == "regression":
1675
+ loss_fct = MSELoss()
1676
+ if self.num_labels == 1:
1677
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1678
+ else:
1679
+ loss = loss_fct(pooled_logits, labels)
1680
+ elif self.config.problem_type == "single_label_classification":
1681
+ loss_fct = CrossEntropyLoss()
1682
+ loss = loss_fct(
1683
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1684
+ )
1685
+ elif self.config.problem_type == "multi_label_classification":
1686
+ loss_fct = BCEWithLogitsLoss()
1687
+ loss = loss_fct(pooled_logits, labels)
1688
+ if not return_dict:
1689
+ output = (pooled_logits,) + transformer_outputs[1:]
1690
+ return ((loss,) + output) if loss is not None else output
1691
+
1692
+ return SequenceClassifierOutputWithPast(
1693
+ loss=loss,
1694
+ logits=pooled_logits,
1695
+ past_key_values=transformer_outputs.past_key_values,
1696
+ hidden_states=transformer_outputs.hidden_states,
1697
+ attentions=transformer_outputs.attentions,
1698
+ )
modeling_minicpmv.py ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import List, Optional
3
+ import json
4
+ import timm
5
+ import torch
6
+
7
+ import time
8
+
9
+ import torchvision
10
+ from PIL import Image
11
+ from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD
12
+ from torchvision import transforms
13
+ from transformers import LlamaTokenizer
14
+ from transformers import BatchEncoding # note that, MiniCPMV do padding during forward, not before forward
15
+ from transformers.utils import ModelOutput
16
+ from typing import Optional
17
+
18
+ from dataclasses import dataclass
19
+
20
+ from .configuration_minicpm import MiniCPMVConfig
21
+ from .modeling_minicpm import MiniCPMForCausalLM, MiniCPMPreTrainedModel
22
+ from .resampler import Resampler
23
+
24
+ # for faster batch inference
25
+ from concurrent.futures import ThreadPoolExecutor
26
+
27
+
28
+ class MiniCPMVPreTrainedModel(MiniCPMPreTrainedModel):
29
+ config_class = MiniCPMVConfig
30
+
31
+
32
+ class MiniCPMV(MiniCPMVPreTrainedModel):
33
+ def __init__(self, config):
34
+ super().__init__(config)
35
+
36
+ self.llm = MiniCPMForCausalLM(config)
37
+ self.vpm = self.init_vision_module()
38
+ self.vision_dim = self.vpm.embed_dim
39
+ self.embed_dim = self.llm.config.hidden_size
40
+ self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
41
+ self.transform = self.init_transform()
42
+
43
+ # hack code because we find that sometimes the dtype of pos_embed is not the same as other layers in resampler
44
+ dtype = self.vpm.pos_embed.data.dtype
45
+ self.resampler.pos_embed.data = self.resampler.pos_embed.data.to(dtype)
46
+
47
+
48
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs):
49
+ print(gradient_checkpointing_kwargs)
50
+ print(f"MiniCPMV.gradient_checkpointing enbale called: {gradient_checkpointing_kwargs}")
51
+ self.llm.gradient_checkpointing_enable(gradient_checkpointing_kwargs=gradient_checkpointing_kwargs)
52
+ print("self.llm.gradient_checkpointing_enable ... OK")
53
+ self.vpm.set_grad_checkpointing(enable=True)
54
+ print("self.vpm.gradient_checkpointing_enable ... OK")
55
+ return
56
+
57
+ def init_vision_module(self):
58
+ model = timm.create_model(
59
+ self.config.vision_encoder,
60
+ pretrained=False,
61
+ num_classes=0,
62
+ dynamic_img_size=True,
63
+ dynamic_img_pad=True
64
+ )
65
+
66
+ if isinstance(model, timm.models.VisionTransformer):
67
+ if model.attn_pool is not None:
68
+ model.attn_pool = torch.nn.Identity()
69
+
70
+ if self.config.drop_vision_last_layer:
71
+ model.blocks = model.blocks[:-1]
72
+
73
+ return model
74
+
75
+ def init_resampler(self, embed_dim, vision_dim):
76
+ return Resampler(
77
+ grid_size=int(math.sqrt(self.config.query_num)),
78
+ embed_dim=embed_dim,
79
+ num_heads=embed_dim // 128,
80
+ kv_dim=vision_dim,
81
+ adaptive=True
82
+ )
83
+
84
+ def init_transform(self):
85
+ return transforms.Compose(
86
+ [
87
+ transforms.ToTensor(),
88
+ transforms.Normalize(
89
+ mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD
90
+ ),
91
+ ]
92
+ )
93
+
94
+ # @Vision encoder 把raw pixels变成visual tokens
95
+ def get_vision_embedding(self, pixel_values):
96
+
97
+ # hack: get dtype
98
+ dtype = self.vpm.pos_embed.data.dtype
99
+
100
+ res = []
101
+
102
+ # first slice
103
+ H, W = pixel_values[0].shape[-2:]
104
+ tgt_size = (
105
+ math.ceil(H / self.vpm.patch_embed.patch_size[0]), math.ceil(W / self.vpm.patch_embed.patch_size[0])
106
+ )
107
+
108
+ vision_embedding = self.vpm.forward_features(pixel_values[0].unsqueeze(0).type(dtype))
109
+
110
+ res.append(self.resampler(vision_embedding, tgt_size))
111
+
112
+ # remaining slices
113
+ if len(pixel_values) > 1:
114
+
115
+ H, W = pixel_values[1].shape[-2:]
116
+ tgt_size = (
117
+ math.ceil(H / self.vpm.patch_embed.patch_size[0]), math.ceil(W / self.vpm.patch_embed.patch_size[0])
118
+ )
119
+ vision_embedding = self.vpm.forward_features(torch.stack(pixel_values[1:], dim=0).type(dtype))
120
+ res.append(self.resampler(vision_embedding, tgt_size))
121
+
122
+ return torch.vstack(res)
123
+
124
+ def get_vllm_embedding(self, data):
125
+
126
+ if "vision_hidden_states" not in data:
127
+ pixel_values_list = data["pixel_values"]
128
+ vision_hidden_states = []
129
+
130
+ for pixel_values in pixel_values_list:
131
+
132
+ if len(pixel_values) > 0:
133
+ vision_hidden_states.append(self.get_vision_embedding(pixel_values))
134
+ else:
135
+ vision_hidden_states.append([])
136
+ else:
137
+ vision_hidden_states = data["vision_hidden_states"]
138
+
139
+ vllm_embedding = (
140
+ self.llm.model.embed_tokens(data["input_ids"]) * self.llm.config.scale_emb
141
+ )
142
+
143
+ vision_hidden_states = [
144
+ i.type(vllm_embedding.dtype) if isinstance(i, torch.Tensor) else i
145
+ for i in vision_hidden_states
146
+ ]
147
+
148
+ bs = len(data["input_ids"])
149
+ for i in range(bs):
150
+ cur_vs_hs = vision_hidden_states[i]
151
+ if len(cur_vs_hs) > 0:
152
+ cur_vllm_emb = vllm_embedding[i]
153
+ cur_image_bound = data["image_bound"][i]
154
+ if len(cur_image_bound) > 0:
155
+ image_indices = torch.stack(
156
+ [
157
+ torch.arange(r[0], r[1], dtype=torch.long)
158
+ for r in cur_image_bound
159
+ ]
160
+ ).to(vllm_embedding.device)
161
+
162
+ cur_vllm_emb.scatter_(
163
+ 0,
164
+ image_indices.view(-1, 1).repeat(1, cur_vllm_emb.shape[-1]),
165
+ cur_vs_hs.view(-1, cur_vs_hs.shape[-1]),
166
+ )
167
+ elif self.training:
168
+ cur_vllm_emb += cur_vs_hs[0].mean() * 0
169
+
170
+
171
+ return vllm_embedding, vision_hidden_states
172
+
173
+ def _convert_to_tensors(
174
+ self, tokenizer, input_str, max_inp_length: Optional[int] = None):
175
+ if tokenizer.add_bos_token:
176
+ input_ids = tokenizer.encode(input_str)
177
+ else:
178
+ input_ids = [tokenizer.bos_id] + tokenizer.encode(input_str)
179
+ if max_inp_length is not None:
180
+ input_ids = input_ids[:max_inp_length]
181
+ input_ids = torch.tensor(input_ids, dtype=torch.int32)
182
+
183
+ image_start_tokens = torch.where(input_ids == tokenizer.im_start_id)[0]
184
+
185
+ image_start_tokens += 1
186
+ image_end_tokens = torch.where(input_ids == tokenizer.im_end_id)[0]
187
+ valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
188
+ image_bound = torch.hstack(
189
+ [
190
+ image_start_tokens[:valid_image_nums].unsqueeze(-1),
191
+ image_end_tokens[:valid_image_nums].unsqueeze(-1),
192
+ ]
193
+ )
194
+
195
+ model_input = {}
196
+ model_input["input_ids"] = input_ids.unsqueeze(0).to(self.device)
197
+ model_input["image_bound"] = image_bound
198
+
199
+
200
+ return model_input
201
+
202
+ def _process_list( # pad input tensors
203
+ self, tokenizer, data_list: List[str], max_inp_length: Optional[int] = None, padding_side: str = "right"
204
+ ):
205
+ input_tensors = []
206
+ for data in data_list:
207
+ input_tensors.append(
208
+ self._convert_to_tensors(tokenizer, data, max_inp_length)
209
+ )
210
+
211
+
212
+ padded = pad([i["input_ids"] for i in input_tensors], padding_side=padding_side)
213
+
214
+ padded = padded.to(self.device)
215
+ padded["image_bound"] = [i["image_bound"] for i in input_tensors]
216
+ return padded
217
+
218
+ def _decode(self, model_inputs, tokenizer, **kwargs): # fixed version of _decode
219
+ output = self.llm.generate(
220
+ inputs_embeds=model_inputs["inputs_embeds"],
221
+ attention_mask=model_inputs["attention_mask"],
222
+ pad_token_id=0,
223
+ eos_token_id=tokenizer.eos_token_id,
224
+ **kwargs
225
+ )
226
+ return self._decode_text(output, tokenizer)
227
+
228
+ def _decode_text(self, result_ids, tokenizer):
229
+ result_text = []
230
+ for result in result_ids:
231
+ result = result[result != 0]
232
+ if result[0] == tokenizer.bos_id:
233
+ result = result[1:]
234
+ if result[-1] == tokenizer.eos_id:
235
+ result = result[:-1]
236
+ result_text.append(tokenizer.decode(result).strip())
237
+ return result_text
238
+
239
+ def slice_image(self, image):
240
+ return slice_image(
241
+ image,
242
+ self.config.max_slice_nums,
243
+ self.config.scale_resolution,
244
+ self.config.patch_size,
245
+ )
246
+
247
+ def get_slice_image_placeholder(self, image, tokenizer):
248
+ image_placeholder = (
249
+ tokenizer.im_start
250
+ + tokenizer.unk_token * self.config.query_num
251
+ + tokenizer.im_end
252
+ )
253
+
254
+ slice_images = []
255
+
256
+ source_image, patches, best_grid = slice_image(
257
+ image,
258
+ self.config.max_slice_nums,
259
+ self.config.scale_resolution,
260
+ self.config.patch_size,
261
+ )
262
+
263
+ slice_images.append(source_image)
264
+ final_placeholder = image_placeholder
265
+
266
+ if len(patches) > 0:
267
+ for i in range(len(patches)):
268
+ for j in range(len(patches[0])):
269
+ slice_images.append(patches[i][j])
270
+
271
+ final_placeholder += get_grid_placeholder(
272
+ tokenizer, best_grid, self.config.query_num
273
+ )
274
+ return slice_images, final_placeholder
275
+
276
+ def generate(
277
+ self,
278
+ data_list=None, # List[str]
279
+ img_list=None, # List[List[PIL.Image]]
280
+ tokenizer=None,
281
+ max_inp_length: Optional[int] = None,
282
+ vision_hidden_states=None, # default None
283
+ return_vision_hidden_states=False,
284
+ **kwargs):
285
+
286
+ assert data_list is not None
287
+ bs = len(data_list)
288
+ if img_list == None:
289
+ img_list = [[] for i in range(bs)]
290
+ assert bs == len(img_list)
291
+
292
+ model_inputs = self._process_list(tokenizer, data_list, max_inp_length, padding_side="right") # will add attention mask
293
+
294
+ if vision_hidden_states is None:
295
+ pixel_values = []
296
+ for i in range(bs):
297
+ img_inps = []
298
+ for img in img_list[i]:
299
+ img_inps.append(self.transform(img).to(self.device))
300
+ if img_inps:
301
+ pixel_values.append(img_inps)
302
+ else:
303
+ pixel_values.append([])
304
+ model_inputs["pixel_values"] = pixel_values
305
+ else:
306
+ model_inputs["vision_hidden_states"] = vision_hidden_states
307
+
308
+ with torch.inference_mode():
309
+ (
310
+ model_inputs["inputs_embeds"],
311
+ vision_hidden_states,
312
+ ) = self.get_vllm_embedding(model_inputs)
313
+
314
+ result = self._decode(model_inputs, tokenizer, **kwargs)
315
+
316
+ if return_vision_hidden_states:
317
+ return result, vision_hidden_states
318
+
319
+ return result
320
+
321
+ def chat(
322
+ self,
323
+ image_list, # List[ PIL.Image ] B*PIL.Image, one image for each data
324
+ msgs_list, # List[Dict[str, str]] B*ChatML, one ChatML Dict for each data
325
+ tokenizer,
326
+ vision_hidden_states=None,
327
+ max_new_tokens=1024,
328
+ sampling=True,
329
+ max_inp_length=2048,
330
+ **kwargs):
331
+
332
+ processed_image_list = []
333
+ processed_msgs_list = []
334
+
335
+ for msgs, image in zip(msgs_list, image_list):
336
+ if not isinstance(msgs, list):
337
+ raise NotImplementedError(f"chatml format expected, expect outmost type to be list but got {type(msgs)}")
338
+
339
+ # msgs to prompt
340
+ prompt = ""
341
+ for i, msg in enumerate(msgs):
342
+ role = msg["role"]
343
+ content = msg["content"]
344
+ assert role in ["user", "assistant"]
345
+ if i == 0:
346
+ assert role == "user", "The role of first msg should be user"
347
+ if self.config.slice_mode:
348
+ images, final_placeholder = self.get_slice_image_placeholder(
349
+ image, tokenizer
350
+ ) # crop one image into multiple sub images -> List[Image]
351
+ content = final_placeholder + "\n" + content
352
+ else:
353
+ images = [image] # only keep one image without cropping -> List[Image]
354
+ content = (
355
+ tokenizer.im_start
356
+ + tokenizer.unk_token * self.config.query_num
357
+ + tokenizer.im_end
358
+ + "\n"
359
+ + content
360
+ )
361
+ prompt += "<用户>" if role == "user" else "<AI>"
362
+ prompt += content
363
+ final_input = prompt
364
+
365
+
366
+ processed_msgs_list.append(final_input)
367
+ processed_image_list.append(images)
368
+
369
+ if sampling:
370
+ generation_config = {
371
+ "temperature": 0.7,
372
+ "do_sample": True,
373
+ "repetition_penalty": 1.02
374
+ }
375
+ else:
376
+ generation_config = {
377
+ "num_beams": 3,
378
+ "repetition_penalty": 1.2,
379
+ }
380
+
381
+ generation_config.update(
382
+ (k, kwargs[k]) for k in generation_config.keys() & kwargs.keys()
383
+ )
384
+
385
+ with torch.inference_mode():
386
+ res, vision_hidden_states = self.generate(
387
+ data_list=processed_msgs_list,
388
+ max_inp_length=max_inp_length,
389
+ img_list=processed_image_list,
390
+ tokenizer=tokenizer,
391
+ max_new_tokens=max_new_tokens,
392
+ vision_hidden_states=vision_hidden_states, # this is None by default.
393
+ return_vision_hidden_states=True,
394
+ **generation_config
395
+ )
396
+ answers = res
397
+
398
+ return answers
399
+
400
+
401
+
402
+
403
+
404
+ class LlamaTokenizerWrapper(LlamaTokenizer):
405
+ def __init__(self, **kwargs):
406
+ super().__init__(**kwargs)
407
+ self.im_start = "<image>"
408
+ self.im_end = "</image>"
409
+ self.ref_start = "<ref>"
410
+ self.ref_end = "</ref>"
411
+ self.box_start = "<box>"
412
+ self.box_end = "</box>"
413
+ self.quad_start = "<quad>"
414
+ self.quad_end = "</quad>"
415
+ self.point_start = "<point>"
416
+ self.point_end = "</point>"
417
+ self.slice_start = "<slice>"
418
+ self.slice_end = "</slice>"
419
+
420
+ @property
421
+ def eos_id(self):
422
+ return self.sp_model.eos_id()
423
+
424
+ @property
425
+ def bos_id(self):
426
+ return self.sp_model.bos_id()
427
+
428
+ @property
429
+ def unk_id(self):
430
+ return self.sp_model.unk_id()
431
+
432
+ @property
433
+ def im_start_id(self):
434
+ return self._convert_token_to_id(self.im_start)
435
+
436
+ @property
437
+ def im_end_id(self):
438
+ return self._convert_token_to_id(self.im_end)
439
+
440
+ def pad(orig_items, max_length=None, padding_value=0, padding_side="right"):
441
+ """
442
+ Args:
443
+ orig_items: a list of input_ids, each input_ids should be [1, length_i]
444
+ """
445
+
446
+ padding_value = 0
447
+
448
+ assert isinstance(orig_items, list)
449
+ assert isinstance(orig_items[0], torch.Tensor)
450
+
451
+ items = [t.squeeze() for t in orig_items]
452
+
453
+ batch_size = len(items)
454
+ shape = items[0].shape
455
+
456
+ dim = len(shape)
457
+
458
+ assert dim == 1, "This pad function only expect B*Tensor([seq_len]) input." # Assuming 1D tensors for simplicity
459
+
460
+ if max_length is None:
461
+ max_length = max(item.shape[0] for item in items)
462
+
463
+ tensor = torch.full((batch_size, max_length), padding_value, dtype=items[0].dtype)
464
+ attention_mask = torch.zeros((batch_size, max_length), dtype=torch.int8)
465
+
466
+ for i, item in enumerate(items):
467
+ length = item.shape[0]
468
+ if padding_side == "left":
469
+ raise NotImplementedError("fuck!")
470
+ else:
471
+ tensor[i, :length] = item
472
+ attention_mask[i, :length] = 1
473
+
474
+ return_dict = {
475
+ "input_ids": tensor,
476
+ "attention_mask": attention_mask,
477
+ }
478
+
479
+ return BatchEncoding(return_dict)
480
+
481
+
482
+ def slice_image(
483
+ image, max_slice_nums=9, scale_resolution=448, patch_size=14, never_split=False):
484
+ original_size = image.size
485
+ original_width, original_height = original_size
486
+ log_ratio = math.log(original_width / original_height)
487
+ ratio = original_width * original_height / (scale_resolution * scale_resolution)
488
+ multiple = min(math.ceil(ratio), max_slice_nums)
489
+
490
+ source_image = None
491
+ best_grid = None
492
+ patches = []
493
+
494
+ if multiple <= 1 or never_split:
495
+ # dont need to slice, upsample
496
+ best_size = find_best_resize(
497
+ original_size, scale_resolution, patch_size, allow_upscale=True
498
+ )
499
+ source_image = image.resize(best_size, Image.Resampling.BICUBIC)
500
+ else:
501
+ candidate_split_grids_nums = []
502
+ for i in [multiple - 1, multiple, multiple + 1]:
503
+ if i == 1 or i > max_slice_nums:
504
+ continue
505
+ candidate_split_grids_nums.append(i)
506
+
507
+ # source image, down-sampling and ensure divided by patch_size
508
+ best_resize = find_best_resize(original_size, scale_resolution, patch_size)
509
+
510
+ source_image = image.copy().resize(best_resize, Image.Resampling.BICUBIC)
511
+ candidate_grids = []
512
+
513
+ # find best grid
514
+ for split_grids_nums in candidate_split_grids_nums:
515
+ m = 1
516
+ while m <= split_grids_nums:
517
+ if split_grids_nums % m == 0:
518
+ candidate_grids.append([m, split_grids_nums // m])
519
+ m += 1
520
+
521
+ best_grid = [1, 1]
522
+ min_error = float("inf")
523
+ for grid in candidate_grids:
524
+ error = abs(log_ratio - math.log(grid[0] / grid[1]))
525
+ if error < min_error:
526
+ best_grid = grid
527
+ min_error = error
528
+
529
+ refine_size = get_refine_size(
530
+ original_size, best_grid, scale_resolution, patch_size, allow_upscale=True
531
+ )
532
+
533
+ refine_image = image.resize(refine_size, Image.Resampling.BICUBIC)
534
+
535
+ patches = split_to_patches(refine_image, best_grid)
536
+
537
+ return source_image, patches, best_grid
538
+
539
+
540
+ def ensure_divide(length, patch_size):
541
+ return max(round(length / patch_size) * patch_size, patch_size)
542
+
543
+
544
+ def find_best_resize(original_size, scale_resolution, patch_size, allow_upscale=False):
545
+ width, height = original_size
546
+ if (width * height > scale_resolution * scale_resolution) or allow_upscale:
547
+ r = width / height
548
+ height = int(scale_resolution / math.sqrt(r))
549
+ width = int(height * r)
550
+ best_width = ensure_divide(width, patch_size)
551
+ best_height = ensure_divide(height, patch_size)
552
+ return (best_width, best_height)
553
+
554
+
555
+ def get_refine_size(
556
+ original_size, grid, scale_resolution, patch_size, allow_upscale=False):
557
+ width, height = original_size
558
+ grid_x, grid_y = grid
559
+
560
+ refine_width = ensure_divide(width, grid_x)
561
+ refine_height = ensure_divide(height, grid_y)
562
+
563
+ grid_width = refine_width / grid_x
564
+ grid_height = refine_height / grid_y
565
+
566
+ best_grid_size = find_best_resize(
567
+ (grid_width, grid_height),
568
+ scale_resolution,
569
+ patch_size,
570
+ allow_upscale=allow_upscale,
571
+ )
572
+
573
+ refine_size = (best_grid_size[0] * grid_x, best_grid_size[1] * grid_y)
574
+
575
+ return refine_size
576
+
577
+
578
+ def split_to_patches(image, grid):
579
+ patches = []
580
+ width, height = image.size
581
+ grid_x = int(width / grid[0])
582
+ grid_y = int(height / grid[1])
583
+
584
+ for i in range(0, height, grid_y):
585
+ images = []
586
+ for j in range(0, width, grid_x):
587
+ box = (j, i, j + grid_x, i + grid_y)
588
+ patch = image.crop(box)
589
+ images.append(patch)
590
+ patches.append(images)
591
+
592
+ return patches
593
+
594
+
595
+ def get_grid_placeholder(tokenizer, grid, query_num):
596
+ image_placeholder = (
597
+ tokenizer.im_start + tokenizer.unk_token * query_num + tokenizer.im_end
598
+ )
599
+
600
+ cols = grid[0]
601
+ rows = grid[1]
602
+ slices = []
603
+ for i in range(rows):
604
+ lines = []
605
+ for j in range(cols):
606
+ lines.append(image_placeholder)
607
+ slices.append("".join(lines))
608
+ slice_placeholder = tokenizer.slice_start + "\n".join(slices) + tokenizer.slice_end
609
+ return slice_placeholder
610
+
611
+
612
+ def transform_image_mp(img_list, transform, device, max_workers=None):
613
+ pixel_values = []
614
+
615
+ # 使用ThreadPoolExecutor
616
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
617
+ for img_batch in img_list:
618
+ img_inps = list(executor.map(transform, img_batch))
619
+ for i in range(len(img_inps)):
620
+ img_inps[i] = img_inps[i].to(device)
621
+ pixel_values.append(img_inps if img_inps else [])
622
+
623
+ return pixel_values
modeling_visrag_ret.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from dataclasses import dataclass
3
+ from transformers.utils import ModelOutput
4
+ from typing import Optional
5
+ from .modeling_minicpmv import MiniCPMV
6
+ from .modeling_minicpm import MiniCPMForCausalLM
7
+ from .resampler import Resampler
8
+ from concurrent.futures import ThreadPoolExecutor
9
+
10
+
11
+ def transform_image_mp(img_list, transform, device, max_workers=None):
12
+ pixel_values = []
13
+
14
+
15
+
16
+ # 使用ThreadPoolExecutor
17
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
18
+ for img_batch in img_list:
19
+ img_inps = list(executor.map(transform, img_batch))
20
+ for i in range(len(img_inps)):
21
+ img_inps[i] = img_inps[i].to(device)
22
+ pixel_values.append(img_inps if img_inps else [])
23
+
24
+ return pixel_values
25
+
26
+
27
+ @dataclass
28
+ class BaseModelOutputWithAttentionMask(ModelOutput):
29
+ last_hidden_state: torch.FloatTensor = None
30
+ attention_mask: Optional[torch.Tensor] = None
31
+
32
+ class VisRAG_Ret(MiniCPMV): # -> MiniCPMV -> Ultimately a CausalLM
33
+ def fused_tokenize(
34
+ self,
35
+ data_list=None, # List[str]
36
+ img_list=None, # List[List[PIL.Image]]
37
+ tokenizer=None,
38
+ max_inp_length: Optional[int] = None,
39
+ vision_hidden_states=None, # default None
40
+ return_vision_hidden_states=False,
41
+ **kwargs):
42
+
43
+ assert data_list is not None
44
+ bs = len(data_list)
45
+ if img_list == None:
46
+ img_list = [[] for i in range(bs)]
47
+ assert bs == len(img_list)
48
+
49
+ model_inputs = self._process_list(tokenizer, data_list, max_inp_length, padding_side="right")
50
+
51
+ if vision_hidden_states is None:
52
+ pixel_values = transform_image_mp(img_list, self.transform, self.device, max_workers=8)
53
+ model_inputs["pixel_values"] = pixel_values
54
+ else:
55
+ model_inputs["vision_hidden_states"] = vision_hidden_states
56
+
57
+ return model_inputs
58
+
59
+ def prepare_context(self, inputs, tokenizer):
60
+ text_, image_ = inputs
61
+ if not isinstance(text_, str):
62
+ raise NotImplementedError(f"chatml format expected, expect outmost type to be str but got {type(text_)}")
63
+
64
+ # 1.add text
65
+ content = text_
66
+
67
+ # 2. add image
68
+ if image_:
69
+ if self.config.slice_mode:
70
+ images, final_placeholder = self.get_slice_image_placeholder(
71
+ image_, tokenizer
72
+ ) # crop one image into multiple sub images -> List[Image]
73
+ content = final_placeholder + "\n" + content
74
+ else:
75
+ images = [image_] # only keep one image without cropping -> List[Image]
76
+ content = (
77
+ tokenizer.im_start
78
+ + tokenizer.unk_token * self.config.query_num
79
+ + tokenizer.im_end
80
+ + "\n"
81
+ + content
82
+ )
83
+ else:
84
+ images = []
85
+
86
+ return content, images
87
+
88
+ def forward(
89
+ self,
90
+ text, # List[str] B*str
91
+ image, # List[ PIL.Image ] B*PIL.Image, one image for each data
92
+ tokenizer,
93
+ vision_hidden_states=None,
94
+ max_inp_length=2048,
95
+ **kwargs):
96
+
97
+ processed_image = []
98
+ processed_text = []
99
+
100
+ with ThreadPoolExecutor(max_workers=8) as executor:
101
+ contexts = list(executor.map(lambda inputs: self.prepare_context(inputs, tokenizer), zip(text, image)))
102
+
103
+ for context in contexts:
104
+ content_, image_ = context
105
+ processed_text.append(content_)
106
+ processed_image.append(image_)
107
+
108
+ model_inputs = self.fused_tokenize(
109
+ data_list=processed_text, # List[str]
110
+ img_list=processed_image, # List[List[PIL.Image]]
111
+ tokenizer=tokenizer,
112
+ max_inp_length=max_inp_length
113
+ )
114
+
115
+ # this is vision encoder forward.
116
+ model_inputs["inputs_embeds"], vision_hidden_states = self.get_vllm_embedding(model_inputs)
117
+ vlm_outputs = self.llm.model(
118
+ input_ids=None, # because image and text have been merged into model_inputs["inputs_embeds"] here, we don't give input_ids
119
+ position_ids=None,
120
+ inputs_embeds=model_inputs["inputs_embeds"],
121
+ attention_mask=model_inputs["attention_mask"],
122
+ return_dict=True
123
+ )
124
+
125
+ return BaseModelOutputWithAttentionMask(
126
+ last_hidden_state=vlm_outputs.last_hidden_state,
127
+ attention_mask=model_inputs.attention_mask
128
+ )
129
+
resampler.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from collections import OrderedDict
7
+ import math
8
+ import requests
9
+ from io import BytesIO
10
+ from functools import partial
11
+ from PIL import Image
12
+ from typing import Callable, Optional, Sequence, Tuple, List, Union
13
+ import numpy as np
14
+
15
+ import torch
16
+ from torch import nn
17
+ from torch.nn import functional as F
18
+ from torch.nn.init import trunc_normal_
19
+ from torchvision import transforms
20
+ from torchvision.transforms import InterpolationMode
21
+
22
+ def get_abs_pos(abs_pos, tgt_size):
23
+ # abs_pos: L, C
24
+ # tgt_size: (H, W)
25
+ # return: M, C
26
+ src_size = int(math.sqrt(abs_pos.size(0)))
27
+ dtype = abs_pos.dtype
28
+
29
+ return F.interpolate(
30
+ abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2),
31
+ size=(tgt_size[0], tgt_size[1]),
32
+ mode="bicubic",
33
+ align_corners=False,
34
+ ).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype)
35
+
36
+
37
+ # https://github.com/facebookresearch/mae/blob/efb2a8062c206524e35e47d04501ed4f544c0ae8/util/pos_embed.py#L20
38
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
39
+ """
40
+ grid_size: int of the grid height and width
41
+ return:
42
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
43
+ """
44
+ if isinstance(grid_size, int):
45
+ grid_h_size, grid_w_size = grid_size, grid_size
46
+ else:
47
+ grid_h_size, grid_w_size = grid_size[0], grid_size[1]
48
+
49
+ grid_h = np.arange(grid_h_size, dtype=np.float32)
50
+ grid_w = np.arange(grid_w_size, dtype=np.float32)
51
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
52
+ grid = np.stack(grid, axis=0)
53
+
54
+ grid = grid.reshape([2, 1, grid_h_size, grid_w_size])
55
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
56
+ if cls_token:
57
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
58
+ return pos_embed
59
+
60
+
61
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
62
+ assert embed_dim % 2 == 0
63
+
64
+ # use half of dimensions to encode grid_h
65
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
66
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
67
+
68
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
69
+ return emb
70
+
71
+
72
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
73
+ """
74
+ embed_dim: output dimension for each position
75
+ pos: a list of positions to be encoded: size (M,)
76
+ out: (M, D)
77
+ """
78
+ assert embed_dim % 2 == 0
79
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
80
+ omega /= embed_dim / 2.
81
+ omega = 1. / 10000 ** omega # (D/2,)
82
+
83
+ pos = pos.reshape(-1) # (M,)
84
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
85
+
86
+ emb_sin = np.sin(out) # (M, D/2)
87
+ emb_cos = np.cos(out) # (M, D/2)
88
+
89
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
90
+ return emb
91
+
92
+
93
+ class Resampler(nn.Module):
94
+ """
95
+ A 2D perceiver-resampler network with one cross attention layers by
96
+ (grid_size**2) learnable queries and 2d sincos pos_emb
97
+ Outputs:
98
+ A tensor with the shape of (grid_size**2, embed_dim)
99
+ """
100
+
101
+ def __init__(
102
+ self,
103
+ grid_size,
104
+ embed_dim,
105
+ num_heads,
106
+ kv_dim=None,
107
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
108
+ adaptive=False
109
+ ):
110
+ super().__init__()
111
+ self.num_queries = grid_size ** 2
112
+ self.embed_dim = embed_dim
113
+ self.num_heads = num_heads
114
+ self.adaptive = adaptive
115
+
116
+ self.pos_embed = nn.Parameter(
117
+ torch.from_numpy(get_2d_sincos_pos_embed(embed_dim, grid_size)).float()
118
+ ).requires_grad_(False)
119
+
120
+ self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
121
+ trunc_normal_(self.query, std=.02)
122
+
123
+ if kv_dim is not None and kv_dim != embed_dim:
124
+ self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
125
+ else:
126
+ self.kv_proj = nn.Identity()
127
+
128
+ self.attn = nn.MultiheadAttention(embed_dim, num_heads)
129
+ self.ln_q = norm_layer(embed_dim)
130
+ self.ln_kv = norm_layer(embed_dim)
131
+
132
+ self.ln_post = norm_layer(embed_dim)
133
+ self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
134
+
135
+ self.apply(self._init_weights)
136
+
137
+ def _init_weights(self, m):
138
+ if isinstance(m, nn.Linear):
139
+ trunc_normal_(m.weight, std=.02)
140
+ if isinstance(m, nn.Linear) and m.bias is not None:
141
+ nn.init.constant_(m.bias, 0)
142
+ elif isinstance(m, nn.LayerNorm):
143
+ nn.init.constant_(m.bias, 0)
144
+ nn.init.constant_(m.weight, 1.0)
145
+
146
+ def forward(self, x, tgt_size=None, attn_mask=None):
147
+ if self.adaptive:
148
+ # print("adaptive")
149
+ # raise Exception
150
+ pos_embed = torch.Tensor(get_2d_sincos_pos_embed(self.embed_dim, tgt_size)).float().to(device=x.device, dtype=x.dtype)
151
+ else:
152
+ pos_embed = get_abs_pos(self.pos_embed, tgt_size)
153
+
154
+ x = self.kv_proj(x)
155
+ x = self.ln_kv(x).permute(1, 0, 2)
156
+
157
+ N = x.shape[1]
158
+ q = self.ln_q(self.query)
159
+ out = self.attn(
160
+ self._repeat(q, N) + self.pos_embed.unsqueeze(1),
161
+ x + pos_embed.unsqueeze(1),
162
+ x,
163
+ attn_mask=attn_mask)[0]
164
+ x = out.permute(1, 0, 2)
165
+
166
+ x = self.ln_post(x)
167
+ x = x @ self.proj
168
+ return x
169
+
170
+ def _repeat(self, query, N: int):
171
+ return query.unsqueeze(1).repeat(1, N, 1)
special_tokens_map.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<image>",
4
+ "</image>",
5
+ "<ref>",
6
+ "</ref>",
7
+ "<box>",
8
+ "</box>",
9
+ "<quad>",
10
+ "</quad>",
11
+ "<point>",
12
+ "</point>",
13
+ "<slice>",
14
+ "</slice>"
15
+ ],
16
+ "bos_token": {
17
+ "content": "<s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "eos_token": {
24
+ "content": "</s>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": {
31
+ "content": "<unk>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "unk_token": {
38
+ "content": "<unk>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ }
44
+ }
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:b046f377b2f09a90623a46611bd5d23cb76ac89ca7804a372408f37aff7b96a0
3
+ size 1994817
tokenizer.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import LlamaTokenizer
2
+
3
+ class LlamaTokenizerWrapper(LlamaTokenizer):
4
+ def __init__(self, **kwargs):
5
+ super().__init__(**kwargs)
6
+ self.im_start = "<image>"
7
+ self.im_end = "</image>"
8
+ self.ref_start = "<ref>"
9
+ self.ref_end = "</ref>"
10
+ self.box_start = "<box>"
11
+ self.box_end = "</box>"
12
+ self.quad_start = "<quad>"
13
+ self.quad_end = "</quad>"
14
+ self.point_start = "<point>"
15
+ self.point_end = "</point>"
16
+ self.slice_start = "<slice>"
17
+ self.slice_end = "</slice>"
18
+
19
+ @property
20
+ def eos_id(self):
21
+ return self.sp_model.eos_id()
22
+
23
+ @property
24
+ def bos_id(self):
25
+ return self.sp_model.bos_id()
26
+
27
+ @property
28
+ def unk_id(self):
29
+ return self.sp_model.unk_id()
30
+
31
+ @property
32
+ def im_start_id(self):
33
+ return self._convert_token_to_id(self.im_start)
34
+
35
+ @property
36
+ def im_end_id(self):
37
+ return self._convert_token_to_id(self.im_end)
tokenizer_config.json ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
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
+ },
127
+ "additional_special_tokens": [
128
+ "<image>",
129
+ "</image>",
130
+ "<ref>",
131
+ "</ref>",
132
+ "<box>",
133
+ "</box>",
134
+ "<quad>",
135
+ "</quad>",
136
+ "<point>",
137
+ "</point>",
138
+ "<slice>",
139
+ "</slice>"
140
+ ],
141
+ "auto_map": {
142
+ "AutoTokenizer": [
143
+ "tokenizer.LlamaTokenizerWrapper",
144
+ null
145
+ ]
146
+ },
147
+ "bos_token": "<s>",
148
+ "clean_up_tokenization_spaces": false,
149
+ "eos_token": "</s>",
150
+ "legacy": true,
151
+ "model_max_length": 2048,
152
+ "pad_token": "<unk>",
153
+ "padding_side": "right",
154
+ "sp_model_kwargs": {},
155
+ "spaces_between_special_tokens": false,
156
+ "tokenizer_class": "LlamaTokenizerWrapper",
157
+ "truncation_side": "right",
158
+ "unk_token": "<unk>",
159
+ "use_default_system_prompt": false,
160
+ "use_fast": false
161
+ }