cs70 commited on
Commit
68dcd95
·
verified ·
1 Parent(s): 2267734

Initial commit

Browse files
config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./model_MiniCPM-V-2/",
3
+ "architectures": [
4
+ "MiniCPMV"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_minicpm.MiniCPMVConfig",
10
+ "AutoModel": "modeling_minicpmv.MiniCPMV",
11
+ "AutoModelForCausalLM": "openbmb/MiniCPM-V-2--modeling_minicpmv.MiniCPMV"
12
+ },
13
+ "bos_token_id": 1,
14
+ "dim_model_base": 256,
15
+ "drop_vision_last_layer": true,
16
+ "eos_token_id": 2,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 2304,
19
+ "im_end_token_id": 102,
20
+ "im_start_token_id": 101,
21
+ "image_size": 448,
22
+ "initializer_range": 0.1,
23
+ "intermediate_size": 5760,
24
+ "max_position_embeddings": 4096,
25
+ "max_slice_nums": 9,
26
+ "mm_use_im_start_end": true,
27
+ "model_type": "minicpmv",
28
+ "num_attention_heads": 36,
29
+ "num_hidden_layers": 40,
30
+ "num_key_value_heads": 36,
31
+ "patch_size": 14,
32
+ "pretraining_tp": 1,
33
+ "query_num": 64,
34
+ "rms_norm_eps": 1e-05,
35
+ "rope_scaling": null,
36
+ "rope_theta": 10000.0,
37
+ "scale_depth": 1.4,
38
+ "scale_emb": 12,
39
+ "scale_resolution": 448,
40
+ "slice_end_token_id": 112,
41
+ "slice_mode": true,
42
+ "slice_start_token_id": 111,
43
+ "tie_word_embeddings": false,
44
+ "torch_dtype": "bfloat16",
45
+ "transformers_version": "4.36.0",
46
+ "unk_token_id": 0,
47
+ "use_cache": true,
48
+ "vision_encoder": "vit_so400m_patch14_siglip_384.webli",
49
+ "vocab_size": 122753
50
+ }
configuration_minicpm.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
198
+ class MiniCPMVConfig(MiniCPMConfig):
199
+ model_type = "minicpmv"
200
+ keys_to_ignore_at_inference = ["past_key_values"]
201
+
202
+ def __init__(
203
+ self,
204
+ vision_encoder="vit_so400m_patch14_siglip_384.webli",
205
+ query_num=64,
206
+ image_size=448,
207
+ drop_vision_last_layer=True,
208
+ slice_mode=True,
209
+ patch_size=14,
210
+ max_slice_nums=9,
211
+ scale_resolution=448,
212
+ im_start_token_id=101,
213
+ im_end_token_id=102,
214
+ slice_start_token_id=111,
215
+ slice_end_token_id=112,
216
+ unk_token_id=0,
217
+ **kwargs,
218
+ ):
219
+ self.vision_encoder = vision_encoder
220
+ self.query_num = query_num
221
+ self.image_size = image_size
222
+ self.drop_vision_last_layer = drop_vision_last_layer
223
+ self.slice_mode = slice_mode
224
+ self.patch_size = patch_size
225
+ self.max_slice_nums = max_slice_nums
226
+ self.scale_resolution = scale_resolution
227
+ self.im_start_token_id = im_start_token_id
228
+ self.im_end_token_id = im_end_token_id
229
+ self.slice_start_token_id = slice_start_token_id
230
+ self.slice_end_token_id = slice_end_token_id
231
+ self.unk_token_id = unk_token_id
232
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.36.0"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6372d92536d50145c27dac022bd2a2b4a0e717b524dfe0f41372c6ccc1d39e75
3
+ size 6870008904
modeling_minicpm.py ADDED
@@ -0,0 +1,1697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ output_attentions = (
1160
+ output_attentions
1161
+ if output_attentions is not None
1162
+ else self.config.output_attentions
1163
+ )
1164
+ output_hidden_states = (
1165
+ output_hidden_states
1166
+ if output_hidden_states is not None
1167
+ else self.config.output_hidden_states
1168
+ )
1169
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1170
+
1171
+ return_dict = (
1172
+ return_dict if return_dict is not None else self.config.use_return_dict
1173
+ )
1174
+
1175
+ # retrieve input_ids and inputs_embeds
1176
+ if input_ids is not None and inputs_embeds is not None:
1177
+ raise ValueError(
1178
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1179
+ )
1180
+ elif input_ids is not None:
1181
+ batch_size, seq_length = input_ids.shape[:2]
1182
+ elif inputs_embeds is not None:
1183
+ batch_size, seq_length = inputs_embeds.shape[:2]
1184
+ else:
1185
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1186
+
1187
+ if self.gradient_checkpointing and self.training:
1188
+ if use_cache:
1189
+ logger.warning_once(
1190
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1191
+ )
1192
+ use_cache = False
1193
+
1194
+ past_key_values_length = 0
1195
+ if use_cache:
1196
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1197
+ if use_legacy_cache:
1198
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1199
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1200
+
1201
+ if position_ids is None:
1202
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1203
+ position_ids = torch.arange(
1204
+ past_key_values_length,
1205
+ seq_length + past_key_values_length,
1206
+ dtype=torch.long,
1207
+ device=device,
1208
+ )
1209
+ position_ids = position_ids.unsqueeze(0)
1210
+
1211
+ if inputs_embeds is None:
1212
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1213
+
1214
+ if self._use_flash_attention_2:
1215
+ # 2d mask is passed through the layers
1216
+ attention_mask = (
1217
+ attention_mask
1218
+ if (attention_mask is not None and 0 in attention_mask)
1219
+ else None
1220
+ )
1221
+ elif self._use_sdpa and not output_attentions:
1222
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1223
+ # the manual implementation that requires a 4D causal mask in all cases.
1224
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1225
+ attention_mask,
1226
+ (batch_size, seq_length),
1227
+ inputs_embeds,
1228
+ past_key_values_length,
1229
+ )
1230
+ else:
1231
+ # 4d mask is passed through the layers
1232
+ attention_mask = _prepare_4d_causal_attention_mask(
1233
+ attention_mask,
1234
+ (batch_size, seq_length),
1235
+ inputs_embeds,
1236
+ past_key_values_length,
1237
+ )
1238
+
1239
+ # embed positions
1240
+ hidden_states = inputs_embeds
1241
+
1242
+ # decoder layers
1243
+ all_hidden_states = () if output_hidden_states else None
1244
+ all_self_attns = () if output_attentions else None
1245
+ next_decoder_cache = None
1246
+
1247
+ for decoder_layer in self.layers:
1248
+ if output_hidden_states:
1249
+ all_hidden_states += (hidden_states,)
1250
+
1251
+ if self.gradient_checkpointing and self.training:
1252
+ layer_outputs = self._gradient_checkpointing_func(
1253
+ decoder_layer.__call__,
1254
+ hidden_states,
1255
+ attention_mask,
1256
+ position_ids,
1257
+ past_key_values,
1258
+ output_attentions,
1259
+ use_cache,
1260
+ )
1261
+ else:
1262
+ layer_outputs = decoder_layer(
1263
+ hidden_states,
1264
+ attention_mask=attention_mask,
1265
+ position_ids=position_ids,
1266
+ past_key_value=past_key_values,
1267
+ output_attentions=output_attentions,
1268
+ use_cache=use_cache,
1269
+ )
1270
+
1271
+ hidden_states = layer_outputs[0]
1272
+
1273
+ if use_cache:
1274
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1275
+
1276
+ if output_attentions:
1277
+ all_self_attns += (layer_outputs[1],)
1278
+
1279
+ hidden_states = self.norm(hidden_states)
1280
+
1281
+ # add hidden states from the last decoder layer
1282
+ if output_hidden_states:
1283
+ all_hidden_states += (hidden_states,)
1284
+
1285
+ next_cache = None
1286
+ if use_cache:
1287
+ next_cache = (
1288
+ next_decoder_cache.to_legacy_cache()
1289
+ if use_legacy_cache
1290
+ else next_decoder_cache
1291
+ )
1292
+ if not return_dict:
1293
+ return tuple(
1294
+ v
1295
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1296
+ if v is not None
1297
+ )
1298
+ return BaseModelOutputWithPast(
1299
+ last_hidden_state=hidden_states,
1300
+ past_key_values=next_cache,
1301
+ hidden_states=all_hidden_states,
1302
+ attentions=all_self_attns,
1303
+ )
1304
+
1305
+
1306
+ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
1307
+ _tied_weights_keys = ["lm_head.weight"]
1308
+
1309
+ def __init__(self, config):
1310
+ super().__init__(config)
1311
+ self.model = MiniCPMModel(config)
1312
+ self.vocab_size = config.vocab_size
1313
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1314
+
1315
+ # Initialize weights and apply final processing
1316
+ self.post_init()
1317
+
1318
+ def get_input_embeddings(self):
1319
+ return self.model.embed_tokens
1320
+
1321
+ def set_input_embeddings(self, value):
1322
+ self.model.embed_tokens = value
1323
+
1324
+ def get_output_embeddings(self):
1325
+ return self.lm_head
1326
+
1327
+ def set_output_embeddings(self, new_embeddings):
1328
+ self.lm_head = new_embeddings
1329
+
1330
+ def set_decoder(self, decoder):
1331
+ self.model = decoder
1332
+
1333
+ def get_decoder(self):
1334
+ return self.model
1335
+
1336
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1337
+ @replace_return_docstrings(
1338
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1339
+ )
1340
+ def forward(
1341
+ self,
1342
+ input_ids: torch.LongTensor = None,
1343
+ attention_mask: Optional[torch.Tensor] = None,
1344
+ position_ids: Optional[torch.LongTensor] = None,
1345
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1346
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1347
+ labels: Optional[torch.LongTensor] = None,
1348
+ use_cache: Optional[bool] = None,
1349
+ output_attentions: Optional[bool] = None,
1350
+ output_hidden_states: Optional[bool] = None,
1351
+ return_dict: Optional[bool] = None,
1352
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1353
+ r"""
1354
+ Args:
1355
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1356
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1357
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1358
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1359
+ Returns:
1360
+ Example:
1361
+ ```python
1362
+ >>> from transformers import AutoTokenizer, MiniCPMForCausalLM
1363
+ >>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1364
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1365
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1366
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1367
+ >>> # Generate
1368
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1369
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1370
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1371
+ ```"""
1372
+ output_attentions = (
1373
+ output_attentions
1374
+ if output_attentions is not None
1375
+ else self.config.output_attentions
1376
+ )
1377
+ output_hidden_states = (
1378
+ output_hidden_states
1379
+ if output_hidden_states is not None
1380
+ else self.config.output_hidden_states
1381
+ )
1382
+ return_dict = (
1383
+ return_dict if return_dict is not None else self.config.use_return_dict
1384
+ )
1385
+
1386
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1387
+ outputs = self.model(
1388
+ input_ids=input_ids,
1389
+ attention_mask=attention_mask,
1390
+ position_ids=position_ids,
1391
+ past_key_values=past_key_values,
1392
+ inputs_embeds=inputs_embeds,
1393
+ use_cache=use_cache,
1394
+ output_attentions=output_attentions,
1395
+ output_hidden_states=output_hidden_states,
1396
+ return_dict=return_dict,
1397
+ )
1398
+
1399
+ hidden_states = outputs[0]
1400
+ if self.config.pretraining_tp > 1:
1401
+ lm_head_slices = self.lm_head.weight.split(
1402
+ self.vocab_size // self.config.pretraining_tp, dim=0
1403
+ )
1404
+ logits = [
1405
+ F.linear(hidden_states, lm_head_slices[i])
1406
+ for i in range(self.config.pretraining_tp)
1407
+ ]
1408
+ logits = torch.cat(logits, dim=-1)
1409
+ else:
1410
+ logits = self.lm_head(
1411
+ hidden_states / (self.config.hidden_size / self.config.dim_model_base)
1412
+ )
1413
+ logits = logits.float()
1414
+
1415
+ loss = None
1416
+ if labels is not None:
1417
+ # Shift so that tokens < n predict n
1418
+ shift_logits = logits[..., :-1, :].contiguous()
1419
+ shift_labels = labels[..., 1:].contiguous()
1420
+ # Flatten the tokens
1421
+ loss_fct = CrossEntropyLoss()
1422
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1423
+ shift_labels = shift_labels.view(-1)
1424
+ # Enable model parallelism
1425
+ shift_labels = shift_labels.to(shift_logits.device)
1426
+ loss = loss_fct(shift_logits, shift_labels)
1427
+
1428
+ if not return_dict:
1429
+ output = (logits,) + outputs[1:]
1430
+ return (loss,) + output if loss is not None else output
1431
+
1432
+ return CausalLMOutputWithPast(
1433
+ loss=loss,
1434
+ logits=logits,
1435
+ past_key_values=outputs.past_key_values,
1436
+ hidden_states=outputs.hidden_states,
1437
+ attentions=outputs.attentions,
1438
+ )
1439
+
1440
+ def prepare_inputs_for_generation(
1441
+ self,
1442
+ input_ids,
1443
+ past_key_values=None,
1444
+ attention_mask=None,
1445
+ inputs_embeds=None,
1446
+ **kwargs,
1447
+ ):
1448
+ if past_key_values is not None:
1449
+ if isinstance(past_key_values, Cache):
1450
+ cache_length = past_key_values.get_seq_length()
1451
+ past_length = past_key_values.seen_tokens
1452
+ max_cache_length = past_key_values.get_max_length()
1453
+ else:
1454
+ cache_length = past_length = past_key_values[0][0].shape[2]
1455
+ max_cache_length = None
1456
+
1457
+ # Keep only the unprocessed tokens:
1458
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1459
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1460
+ # input)
1461
+ if (
1462
+ attention_mask is not None
1463
+ and attention_mask.shape[1] > input_ids.shape[1]
1464
+ ):
1465
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1466
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1467
+ # input_ids based on the past_length.
1468
+ elif past_length < input_ids.shape[1]:
1469
+ input_ids = input_ids[:, past_length:]
1470
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1471
+
1472
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1473
+ if (
1474
+ max_cache_length is not None
1475
+ and attention_mask is not None
1476
+ and cache_length + input_ids.shape[1] > max_cache_length
1477
+ ):
1478
+ attention_mask = attention_mask[:, -max_cache_length:]
1479
+
1480
+ position_ids = kwargs.get("position_ids", None)
1481
+ if attention_mask is not None and position_ids is None:
1482
+ # create position_ids on the fly for batch generation
1483
+ position_ids = attention_mask.long().cumsum(-1) - 1
1484
+ position_ids.masked_fill_(attention_mask == 0, 1)
1485
+ if past_key_values:
1486
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1487
+
1488
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1489
+ if inputs_embeds is not None and past_key_values is None:
1490
+ model_inputs = {"inputs_embeds": inputs_embeds}
1491
+ else:
1492
+ model_inputs = {"input_ids": input_ids}
1493
+
1494
+ model_inputs.update(
1495
+ {
1496
+ "position_ids": position_ids,
1497
+ "past_key_values": past_key_values,
1498
+ "use_cache": kwargs.get("use_cache"),
1499
+ "attention_mask": attention_mask,
1500
+ }
1501
+ )
1502
+ return model_inputs
1503
+
1504
+ @staticmethod
1505
+ def _reorder_cache(past_key_values, beam_idx):
1506
+ reordered_past = ()
1507
+ for layer_past in past_key_values:
1508
+ reordered_past += (
1509
+ tuple(
1510
+ past_state.index_select(0, beam_idx.to(past_state.device))
1511
+ for past_state in layer_past
1512
+ ),
1513
+ )
1514
+ return reordered_past
1515
+
1516
+ @torch.inference_mode()
1517
+ def chat(
1518
+ self,
1519
+ tokenizer,
1520
+ query: str,
1521
+ history: List[Dict] = None,
1522
+ role: str = "user",
1523
+ max_length: int = 4096,
1524
+ num_beams=1,
1525
+ do_sample=True,
1526
+ top_p=0.8,
1527
+ temperature=0.3,
1528
+ logits_processor=None,
1529
+ **kwargs,
1530
+ ):
1531
+ if history is None:
1532
+ history = []
1533
+ if logits_processor:
1534
+ gen_kwargs = {
1535
+ "max_length": max_length,
1536
+ "num_beams": num_beams,
1537
+ "do_sample": do_sample,
1538
+ "top_p": top_p,
1539
+ "temperature": temperature,
1540
+ "logits_processor": logits_processor,
1541
+ **kwargs,
1542
+ }
1543
+ else:
1544
+ gen_kwargs = {
1545
+ "max_length": max_length,
1546
+ "num_beams": num_beams,
1547
+ "do_sample": do_sample,
1548
+ "top_p": top_p,
1549
+ "temperature": temperature,
1550
+ "logits_processor": logits_processor,
1551
+ **kwargs,
1552
+ }
1553
+
1554
+ history.append({"role": role, "content": query})
1555
+ history_str = tokenizer.apply_chat_template(
1556
+ history, tokenize=False, add_generation_prompt=False
1557
+ )
1558
+ inputs = tokenizer(history_str, return_tensors="pt").to(self.device)
1559
+ outputs = self.generate(**inputs, **gen_kwargs)
1560
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]) : -1]
1561
+ response = tokenizer.decode(outputs)
1562
+ pattern = re.compile(r".*?(?=<AI>|<用户>)", re.DOTALL)
1563
+ matches = pattern.findall(response)
1564
+ if len(matches) > 0:
1565
+ response = matches[0]
1566
+ history.append({"role": "assistant", "content": response})
1567
+ return response, history
1568
+
1569
+
1570
+ @add_start_docstrings(
1571
+ """
1572
+ The MiniCPM Model transformer with a sequence classification head on top (linear layer).
1573
+ [`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1574
+ (e.g. GPT-2) do.
1575
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1576
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1577
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1578
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1579
+ each row of the batch).
1580
+ """,
1581
+ MINICPM_START_DOCSTRING,
1582
+ )
1583
+ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
1584
+ def __init__(self, config):
1585
+ super().__init__(config)
1586
+ self.num_labels = config.num_labels
1587
+ self.model = MiniCPMModel(config)
1588
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1589
+
1590
+ # Initialize weights and apply final processing
1591
+ self.post_init()
1592
+
1593
+ def get_input_embeddings(self):
1594
+ return self.model.embed_tokens
1595
+
1596
+ def set_input_embeddings(self, value):
1597
+ self.model.embed_tokens = value
1598
+
1599
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1600
+ def forward(
1601
+ self,
1602
+ input_ids: torch.LongTensor = None,
1603
+ attention_mask: Optional[torch.Tensor] = None,
1604
+ position_ids: Optional[torch.LongTensor] = None,
1605
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1606
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1607
+ labels: Optional[torch.LongTensor] = None,
1608
+ use_cache: Optional[bool] = None,
1609
+ output_attentions: Optional[bool] = None,
1610
+ output_hidden_states: Optional[bool] = None,
1611
+ return_dict: Optional[bool] = None,
1612
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1613
+ r"""
1614
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1615
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1616
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1617
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1618
+ """
1619
+ return_dict = (
1620
+ return_dict if return_dict is not None else self.config.use_return_dict
1621
+ )
1622
+
1623
+ transformer_outputs = self.model(
1624
+ input_ids,
1625
+ attention_mask=attention_mask,
1626
+ position_ids=position_ids,
1627
+ past_key_values=past_key_values,
1628
+ inputs_embeds=inputs_embeds,
1629
+ use_cache=use_cache,
1630
+ output_attentions=output_attentions,
1631
+ output_hidden_states=output_hidden_states,
1632
+ return_dict=return_dict,
1633
+ )
1634
+ hidden_states = transformer_outputs[0]
1635
+ logits = self.score(hidden_states)
1636
+
1637
+ if input_ids is not None:
1638
+ batch_size = input_ids.shape[0]
1639
+ else:
1640
+ batch_size = inputs_embeds.shape[0]
1641
+
1642
+ if self.config.pad_token_id is None and batch_size != 1:
1643
+ raise ValueError(
1644
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1645
+ )
1646
+ if self.config.pad_token_id is None:
1647
+ sequence_lengths = -1
1648
+ else:
1649
+ if input_ids is not None:
1650
+ sequence_lengths = (
1651
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1652
+ ).to(logits.device)
1653
+ else:
1654
+ sequence_lengths = -1
1655
+
1656
+ pooled_logits = logits[
1657
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1658
+ ]
1659
+
1660
+ loss = None
1661
+ if labels is not None:
1662
+ labels = labels.to(logits.device)
1663
+ if self.config.problem_type is None:
1664
+ if self.num_labels == 1:
1665
+ self.config.problem_type = "regression"
1666
+ elif self.num_labels > 1 and (
1667
+ labels.dtype == torch.long or labels.dtype == torch.int
1668
+ ):
1669
+ self.config.problem_type = "single_label_classification"
1670
+ else:
1671
+ self.config.problem_type = "multi_label_classification"
1672
+
1673
+ if self.config.problem_type == "regression":
1674
+ loss_fct = MSELoss()
1675
+ if self.num_labels == 1:
1676
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1677
+ else:
1678
+ loss = loss_fct(pooled_logits, labels)
1679
+ elif self.config.problem_type == "single_label_classification":
1680
+ loss_fct = CrossEntropyLoss()
1681
+ loss = loss_fct(
1682
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1683
+ )
1684
+ elif self.config.problem_type == "multi_label_classification":
1685
+ loss_fct = BCEWithLogitsLoss()
1686
+ loss = loss_fct(pooled_logits, labels)
1687
+ if not return_dict:
1688
+ output = (pooled_logits,) + transformer_outputs[1:]
1689
+ return ((loss,) + output) if loss is not None else output
1690
+
1691
+ return SequenceClassifierOutputWithPast(
1692
+ loss=loss,
1693
+ logits=pooled_logits,
1694
+ past_key_values=transformer_outputs.past_key_values,
1695
+ hidden_states=transformer_outputs.hidden_states,
1696
+ attentions=transformer_outputs.attentions,
1697
+ )
modeling_minicpmv.py ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import json
3
+ import timm
4
+ import torch
5
+ import torchvision
6
+ from PIL import Image
7
+ from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD
8
+ from torchvision import transforms
9
+ from transformers import LlamaTokenizer
10
+ from transformers.integrations import is_deepspeed_zero3_enabled
11
+ from .configuration_minicpm import MiniCPMVConfig
12
+ from .modeling_minicpm import MiniCPMForCausalLM, MiniCPMPreTrainedModel
13
+ from .resampler import Resampler
14
+ from functools import partial
15
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
16
+ from peft.utils.other import ModulesToSaveWrapper
17
+
18
+
19
+ class MiniCPMVPreTrainedModel(MiniCPMPreTrainedModel):
20
+ config_class = MiniCPMVConfig
21
+
22
+
23
+ class MiniCPMV(MiniCPMVPreTrainedModel):
24
+ def __init__(self, config):
25
+ super().__init__(config)
26
+
27
+ self.llm = MiniCPMForCausalLM(config)
28
+ self.vpm = self.init_vision_module()
29
+ self.vision_dim = self.vpm.embed_dim
30
+ self.embed_dim = self.llm.config.hidden_size
31
+ self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
32
+ self.transform = self.init_transform()
33
+
34
+ def init_vision_module(self):
35
+ model = timm.create_model(
36
+ self.config.vision_encoder,
37
+ pretrained=False,
38
+ num_classes=0,
39
+ dynamic_img_size=True,
40
+ dynamic_img_pad=True
41
+ )
42
+
43
+ if isinstance(model, timm.models.VisionTransformer):
44
+ if model.attn_pool is not None:
45
+ model.attn_pool = torch.nn.Identity()
46
+
47
+ if self.config.drop_vision_last_layer:
48
+ model.blocks = model.blocks[:-1]
49
+
50
+ return model
51
+
52
+ def init_resampler(self, embed_dim, vision_dim):
53
+ return Resampler(
54
+ grid_size=int(math.sqrt(self.config.query_num)),
55
+ embed_dim=embed_dim,
56
+ num_heads=embed_dim // 128,
57
+ kv_dim=vision_dim,
58
+ adaptive=True
59
+ )
60
+
61
+ def init_transform(self):
62
+ return transforms.Compose(
63
+ [
64
+ transforms.ToTensor(),
65
+ transforms.Normalize(
66
+ mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD
67
+ ),
68
+ ]
69
+ )
70
+
71
+ def get_input_embeddings(self):
72
+ return self.llm.get_input_embeddings()
73
+
74
+ def set_input_embeddings(self, value):
75
+ self.llm.embed_tokens = value
76
+
77
+ def vpm_forward_features(self, pixel_value):
78
+ if isinstance(self.vpm, ModulesToSaveWrapper):
79
+ if self.vpm.disable_adapters or (self.vpm.active_adapter not in self.vpm.modules_to_save):
80
+ return self.vpm.original_module.forward_features(pixel_value)
81
+ return self.vpm.modules_to_save[self.vpm.active_adapter].forward_features(pixel_value)
82
+ else:
83
+ return self.vpm.forward_features(pixel_value)
84
+
85
+ def get_vision_embedding(self, pixel_values):
86
+ res = []
87
+ dtype = self.llm.lm_head.weight.dtype
88
+ def process_each_pixel(pixel_value, dtype, config, vpm, resampler):
89
+ H, W = pixel_value.shape[-2:]
90
+ target_size = (math.ceil(H / config.patch_size), math.ceil(W / config.patch_size))
91
+ vision_embedding = self.vpm_forward_features(pixel_value.unsqueeze(0).type(dtype))
92
+
93
+ if hasattr(vpm, 'num_prefix_tokens') and vpm.num_prefix_tokens > 0:
94
+ vision_embedding = vision_embedding[:, vpm.num_prefix_tokens:]
95
+ return resampler(vision_embedding, target_size)
96
+
97
+ for pixel_value in pixel_values:
98
+ result = process_each_pixel(pixel_value, dtype, self.config, self.vpm, self.resampler)
99
+ res.append(result)
100
+ return torch.vstack(res)
101
+
102
+ def get_vllm_embedding(self, data):
103
+ if "vision_hidden_states" not in data:
104
+ pixel_values_list = data["pixel_values"]
105
+ vision_hidden_states = []
106
+ for pixel_values in pixel_values_list:
107
+ if len(pixel_values) > 0:
108
+ vision_hidden_states.append(self.get_vision_embedding(pixel_values))
109
+ elif self.training:
110
+ dtype = self.llm.lm_head.weight.dtype
111
+ device = self.llm.lm_head.weight.device
112
+ dummy_image = torch.zeros(
113
+ (1, 3, 224, 224), device=device, dtype=dtype
114
+ )
115
+ vision_hidden_states.append(self.get_vision_embedding(dummy_image))
116
+ else:
117
+ vision_hidden_states.append([])
118
+
119
+ else:
120
+ vision_hidden_states = data["vision_hidden_states"]
121
+
122
+ vllm_embedding = (
123
+ self.llm.model.embed_tokens(data["input_ids"]) * self.llm.config.scale_emb
124
+ )
125
+ vision_hidden_states = [
126
+ i.type(vllm_embedding.dtype) if isinstance(i, torch.Tensor) else i
127
+ for i in vision_hidden_states
128
+ ]
129
+
130
+ bs = len(data["input_ids"])
131
+ for i in range(bs):
132
+ cur_vs_hs = vision_hidden_states[i]
133
+ if len(cur_vs_hs) > 0:
134
+ cur_vllm_emb = vllm_embedding[i]
135
+ cur_image_bound = data["image_bound"][i]
136
+ if len(cur_image_bound) > 0:
137
+ image_indices = torch.stack(
138
+ [
139
+ torch.arange(r[0], r[1], dtype=torch.long)
140
+ for r in cur_image_bound
141
+ ]
142
+ ).to(vllm_embedding.device)
143
+
144
+ cur_vllm_emb.scatter_(
145
+ 0,
146
+ image_indices.view(-1, 1).repeat(1, cur_vllm_emb.shape[-1]),
147
+ cur_vs_hs.view(-1, cur_vs_hs.shape[-1]),
148
+ )
149
+ elif self.training:
150
+ cur_vllm_emb += cur_vs_hs[0].mean() * 0
151
+
152
+ return vllm_embedding, vision_hidden_states
153
+
154
+ def forward(self, data, **kwargs):
155
+ vllm_embedding, vision_hidden_states = self.get_vllm_embedding(data)
156
+ position_ids = data["position_ids"]
157
+ if position_ids.dtype != torch.int64:
158
+ position_ids = position_ids.long()
159
+
160
+ return self.llm(
161
+ input_ids=None,
162
+ position_ids=position_ids,
163
+ inputs_embeds=vllm_embedding,
164
+ **kwargs
165
+ )
166
+
167
+ def _convert_to_tensors(
168
+ self, tokenizer, input_str, max_inp_length: Optional[int] = None
169
+ ):
170
+ if tokenizer.add_bos_token:
171
+ input_ids = tokenizer.encode(input_str)
172
+ else:
173
+ input_ids = [tokenizer.bos_id] + tokenizer.encode(input_str)
174
+ if max_inp_length is not None:
175
+ input_ids = input_ids[:max_inp_length]
176
+ input_ids = torch.tensor(input_ids, dtype=torch.int32)
177
+
178
+ image_start_tokens = torch.where(input_ids == tokenizer.im_start_id)[0]
179
+ # 跳过 im_start
180
+ image_start_tokens += 1
181
+ image_end_tokens = torch.where(input_ids == tokenizer.im_end_id)[0]
182
+ valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
183
+ image_bound = torch.hstack(
184
+ [
185
+ image_start_tokens[:valid_image_nums].unsqueeze(-1),
186
+ image_end_tokens[:valid_image_nums].unsqueeze(-1),
187
+ ]
188
+ )
189
+
190
+ model_input = {}
191
+ model_input["input_ids"] = input_ids.unsqueeze(0).to(self.device)
192
+ model_input["image_bound"] = image_bound
193
+
194
+ return model_input
195
+
196
+ def _process_list(
197
+ self, tokenizer, data_list: List[str], max_inp_length: Optional[int] = None
198
+ ):
199
+ pad_keys = ["input_ids"]
200
+ input_tensors = []
201
+ for data in data_list:
202
+ input_tensors.append(
203
+ self._convert_to_tensors(tokenizer, data, max_inp_length)
204
+ )
205
+ padded = {}
206
+ for key in pad_keys:
207
+ padded[key] = pad(input_tensors, key, padding_side="left").to(self.device)
208
+ padded["image_bound"] = [i["image_bound"] for i in input_tensors]
209
+ return padded
210
+
211
+ def _decode(self, inputs_embeds, tokenizer, **kwargs):
212
+ output = self.llm.generate(
213
+ inputs_embeds=inputs_embeds,
214
+ pad_token_id=0,
215
+ eos_token_id=tokenizer.eos_token_id,
216
+ **kwargs
217
+ )
218
+ return self._decode_text(output, tokenizer)
219
+
220
+ def _decode_text(self, result_ids, tokenizer):
221
+ result_text = []
222
+ for result in result_ids:
223
+ result = result[result != 0]
224
+ if result[0] == tokenizer.bos_id:
225
+ result = result[1:]
226
+ if result[-1] == tokenizer.eos_id:
227
+ result = result[:-1]
228
+ result_text.append(tokenizer.decode(result).strip())
229
+ return result_text
230
+
231
+ def slice_image(self, image):
232
+ return slice_image(
233
+ image,
234
+ self.config.max_slice_nums,
235
+ self.config.scale_resolution,
236
+ self.config.patch_size,
237
+ )
238
+
239
+ def get_slice_image_placeholder(self, image, tokenizer):
240
+ image_placeholder = (
241
+ tokenizer.im_start
242
+ + tokenizer.unk_token * self.config.query_num
243
+ + tokenizer.im_end
244
+ )
245
+
246
+ slice_images = []
247
+
248
+ source_image, patches, best_grid = slice_image(
249
+ image,
250
+ self.config.max_slice_nums,
251
+ self.config.scale_resolution,
252
+ self.config.patch_size,
253
+ )
254
+
255
+ slice_images.append(source_image)
256
+ final_placeholder = image_placeholder
257
+
258
+ if len(patches) > 0:
259
+ for i in range(len(patches)):
260
+ for j in range(len(patches[0])):
261
+ slice_images.append(patches[i][j])
262
+
263
+ final_placeholder += get_grid_placeholder(
264
+ tokenizer, best_grid, self.config.query_num
265
+ )
266
+
267
+ return slice_images, final_placeholder
268
+
269
+ def generate(
270
+ self,
271
+ data_list=None,
272
+ img_list=None,
273
+ tokenizer=None,
274
+ max_inp_length: Optional[int] = None,
275
+ vision_hidden_states=None,
276
+ return_vision_hidden_states=False,
277
+ **kwargs
278
+ ):
279
+
280
+ assert data_list is not None
281
+ bs = len(data_list)
282
+ if img_list == None:
283
+ img_list = [[] for i in range(bs)]
284
+ assert bs == len(img_list)
285
+
286
+ model_inputs = self._process_list(tokenizer, data_list, max_inp_length)
287
+
288
+ if vision_hidden_states is None:
289
+ pixel_values = []
290
+ for i in range(bs):
291
+ img_inps = []
292
+ for img in img_list[i]:
293
+ img_inps.append(self.transform(img).to(self.device))
294
+ if img_inps:
295
+ pixel_values.append(img_inps)
296
+ else:
297
+ pixel_values.append([])
298
+ model_inputs["pixel_values"] = pixel_values
299
+ else:
300
+ model_inputs["vision_hidden_states"] = vision_hidden_states
301
+
302
+ with torch.inference_mode():
303
+ (
304
+ model_inputs["inputs_embeds"],
305
+ vision_hidden_states,
306
+ ) = self.get_vllm_embedding(model_inputs)
307
+
308
+ result = self._decode(model_inputs["inputs_embeds"], tokenizer, **kwargs)
309
+
310
+ if return_vision_hidden_states:
311
+ return result, vision_hidden_states
312
+
313
+ return result
314
+
315
+ def chat(
316
+ self,
317
+ image,
318
+ msgs,
319
+ context,
320
+ tokenizer,
321
+ vision_hidden_states=None,
322
+ max_new_tokens=1024,
323
+ sampling=True,
324
+ max_inp_length=2048,
325
+ **kwargs
326
+ ):
327
+ if isinstance(msgs, str):
328
+ msgs = json.loads(msgs)
329
+ # msgs to prompt
330
+ prompt = ""
331
+ for i, msg in enumerate(msgs):
332
+ role = msg["role"]
333
+ content = msg["content"]
334
+ assert role in ["user", "assistant"]
335
+ if i == 0:
336
+ assert role == "user", "The role of first msg should be user"
337
+ if self.config.slice_mode:
338
+ images, final_placeholder = self.get_slice_image_placeholder(
339
+ image, tokenizer
340
+ )
341
+ content = final_placeholder + "\n" + content
342
+ else:
343
+ images = [image]
344
+ content = (
345
+ tokenizer.im_start
346
+ + tokenizer.unk_token * self.config.query_num
347
+ + tokenizer.im_end
348
+ + "\n"
349
+ + content
350
+ )
351
+ prompt += "<用户>" if role == "user" else "<AI>"
352
+ prompt += content
353
+ prompt += "<AI>"
354
+ final_input = prompt
355
+
356
+ if sampling:
357
+ generation_config = {
358
+ "top_p": 0.8,
359
+ "top_k": 100,
360
+ "temperature": 0.7,
361
+ "do_sample": True,
362
+ "repetition_penalty": 1.05
363
+ }
364
+ else:
365
+ generation_config = {
366
+ "num_beams": 3,
367
+ "repetition_penalty": 1.2,
368
+ }
369
+
370
+ generation_config.update(
371
+ (k, kwargs[k]) for k in generation_config.keys() & kwargs.keys()
372
+ )
373
+
374
+ with torch.inference_mode():
375
+ res, vision_hidden_states = self.generate(
376
+ data_list=[final_input],
377
+ max_inp_length=max_inp_length,
378
+ img_list=[images],
379
+ tokenizer=tokenizer,
380
+ max_new_tokens=max_new_tokens,
381
+ vision_hidden_states=vision_hidden_states,
382
+ return_vision_hidden_states=True,
383
+ **generation_config
384
+ )
385
+ answer = res[0]
386
+ context = msgs.copy()
387
+ context.append({"role": "assistant", "content": answer})
388
+
389
+ return answer, context, generation_config
390
+
391
+
392
+
393
+
394
+ class LlamaTokenizerWrapper(LlamaTokenizer):
395
+ def __init__(self, **kwargs):
396
+ super().__init__(**kwargs)
397
+ self.im_start = "<image>"
398
+ self.im_end = "</image>"
399
+ self.ref_start = "<ref>"
400
+ self.ref_end = "</ref>"
401
+ self.box_start = "<box>"
402
+ self.box_end = "</box>"
403
+ self.quad_start = "<quad>"
404
+ self.quad_end = "</quad>"
405
+ self.point_start = "<point>"
406
+ self.point_end = "</point>"
407
+ self.slice_start = "<slice>"
408
+ self.slice_end = "</slice>"
409
+
410
+ @property
411
+ def eos_id(self):
412
+ return self.sp_model.eos_id()
413
+
414
+ @property
415
+ def bos_id(self):
416
+ return self.sp_model.bos_id()
417
+
418
+ @property
419
+ def unk_id(self):
420
+ return self.sp_model.unk_id()
421
+
422
+ @property
423
+ def im_start_id(self):
424
+ return self._convert_token_to_id(self.im_start)
425
+
426
+ @property
427
+ def im_end_id(self):
428
+ return self._convert_token_to_id(self.im_end)
429
+
430
+
431
+ def pad(orig_items, key, max_length=None, padding_value=0, padding_side="left"):
432
+ items = []
433
+ if isinstance(orig_items[0][key], list):
434
+ assert isinstance(orig_items[0][key][0], torch.Tensor)
435
+ for it in orig_items:
436
+ for tr in it[key]:
437
+ items.append({key: tr})
438
+ else:
439
+ assert isinstance(orig_items[0][key], torch.Tensor)
440
+ items = orig_items
441
+
442
+ batch_size = len(items)
443
+ shape = items[0][key].shape
444
+ dim = len(shape)
445
+ assert dim <= 3
446
+ if max_length is None:
447
+ max_length = 0
448
+ max_length = max(max_length, max(item[key].shape[-1] for item in items))
449
+ min_length = min(item[key].shape[-1] for item in items)
450
+ dtype = items[0][key].dtype
451
+
452
+ if dim == 1:
453
+ return torch.cat([item[key] for item in items], dim=0)
454
+ elif dim == 2:
455
+ if max_length == min_length:
456
+ return torch.cat([item[key] for item in items], dim=0)
457
+ tensor = torch.zeros((batch_size, max_length), dtype=dtype) + padding_value
458
+ else:
459
+ tensor = (
460
+ torch.zeros((batch_size, max_length, shape[-1]), dtype=dtype)
461
+ + padding_value
462
+ )
463
+
464
+ for i, item in enumerate(items):
465
+ if dim == 2:
466
+ if padding_side == "left":
467
+ tensor[i, -len(item[key][0]) :] = item[key][0].clone()
468
+ else:
469
+ tensor[i, : len(item[key][0])] = item[key][0].clone()
470
+ elif dim == 3:
471
+ if padding_side == "left":
472
+ tensor[i, -len(item[key][0]) :, :] = item[key][0].clone()
473
+ else:
474
+ tensor[i, : len(item[key][0]), :] = item[key][0].clone()
475
+
476
+ return tensor
477
+
478
+
479
+ def slice_image(
480
+ image, max_slice_nums=9, scale_resolution=448, patch_size=14, never_split=False
481
+ ):
482
+ original_size = image.size
483
+ original_width, original_height = original_size
484
+ log_ratio = math.log(original_width / original_height)
485
+ ratio = original_width * original_height / (scale_resolution * scale_resolution)
486
+ multiple = min(math.ceil(ratio), max_slice_nums)
487
+
488
+ source_image = None
489
+ best_grid = None
490
+ patches = []
491
+
492
+ if multiple <= 1 or never_split:
493
+ # dont need to slice, upsample
494
+ best_size = find_best_resize(
495
+ original_size, scale_resolution, patch_size, allow_upscale=True
496
+ )
497
+ source_image = image.resize(best_size, Image.Resampling.BICUBIC)
498
+ else:
499
+ candidate_split_grids_nums = []
500
+ for i in [multiple - 1, multiple, multiple + 1]:
501
+ if i == 1 or i > max_slice_nums:
502
+ continue
503
+ candidate_split_grids_nums.append(i)
504
+
505
+ # source image, down-sampling and ensure divided by patch_size
506
+ best_resize = find_best_resize(original_size, scale_resolution, patch_size)
507
+ source_image = image.copy().resize(best_resize, Image.Resampling.BICUBIC)
508
+ candidate_grids = []
509
+
510
+ # find best grid
511
+ for split_grids_nums in candidate_split_grids_nums:
512
+ m = 1
513
+ while m <= split_grids_nums:
514
+ if split_grids_nums % m == 0:
515
+ candidate_grids.append([m, split_grids_nums // m])
516
+ m += 1
517
+
518
+ best_grid = [1, 1]
519
+ min_error = float("inf")
520
+ for grid in candidate_grids:
521
+ error = abs(log_ratio - math.log(grid[0] / grid[1]))
522
+ if error < min_error:
523
+ best_grid = grid
524
+ min_error = error
525
+
526
+ refine_size = get_refine_size(
527
+ original_size, best_grid, scale_resolution, patch_size, allow_upscale=True
528
+ )
529
+
530
+ refine_image = image.resize(refine_size, Image.Resampling.BICUBIC)
531
+ patches = split_to_patches(refine_image, best_grid)
532
+
533
+ return source_image, patches, best_grid
534
+
535
+
536
+ def ensure_divide(length, patch_size):
537
+ return max(round(length / patch_size) * patch_size, patch_size)
538
+
539
+
540
+ def find_best_resize(original_size, scale_resolution, patch_size, allow_upscale=False):
541
+ width, height = original_size
542
+ if (width * height > scale_resolution * scale_resolution) or allow_upscale:
543
+ r = width / height
544
+ height = int(scale_resolution / math.sqrt(r))
545
+ width = int(height * r)
546
+ best_width = ensure_divide(width, patch_size)
547
+ best_height = ensure_divide(height, patch_size)
548
+ return (best_width, best_height)
549
+
550
+
551
+ def get_refine_size(
552
+ original_size, grid, scale_resolution, patch_size, allow_upscale=False
553
+ ):
554
+ width, height = original_size
555
+ grid_x, grid_y = grid
556
+
557
+ refine_width = ensure_divide(width, grid_x)
558
+ refine_height = ensure_divide(height, grid_y)
559
+
560
+ grid_width = refine_width / grid_x
561
+ grid_height = refine_height / grid_y
562
+
563
+ best_grid_size = find_best_resize(
564
+ (grid_width, grid_height),
565
+ scale_resolution,
566
+ patch_size,
567
+ allow_upscale=allow_upscale,
568
+ )
569
+
570
+ refine_size = (best_grid_size[0] * grid_x, best_grid_size[1] * grid_y)
571
+
572
+ return refine_size
573
+
574
+
575
+ def split_to_patches(image, grid):
576
+ patches = []
577
+ width, height = image.size
578
+ grid_x = int(width / grid[0])
579
+ grid_y = int(height / grid[1])
580
+
581
+ for i in range(0, height, grid_y):
582
+ images = []
583
+ for j in range(0, width, grid_x):
584
+ box = (j, i, j + grid_x, i + grid_y)
585
+ patch = image.crop(box)
586
+ images.append(patch)
587
+ patches.append(images)
588
+
589
+ return patches
590
+
591
+
592
+ def get_grid_placeholder(tokenizer, grid, query_num):
593
+ image_placeholder = (
594
+ tokenizer.im_start + tokenizer.unk_token * query_num + tokenizer.im_end
595
+ )
596
+
597
+ cols = grid[0]
598
+ rows = grid[1]
599
+ slices = []
600
+ for i in range(rows):
601
+ lines = []
602
+ for j in range(cols):
603
+ lines.append(image_placeholder)
604
+ slices.append("".join(lines))
605
+ slice_placeholder = tokenizer.slice_start + "\n".join(slices) + tokenizer.slice_end
606
+ return slice_placeholder
resampler.py ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from functools import partial
23
+ import numpy as np
24
+ import warnings
25
+ from typing import Optional, Tuple
26
+ import torch
27
+ from torch import nn
28
+ from torch import Tensor
29
+ import torch.nn.functional as F
30
+ from torch.nn.functional import *
31
+ from torch.nn.modules.activation import *
32
+ from torch.nn.init import trunc_normal_
33
+ from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
34
+ from transformers import PreTrainedModel
35
+ from transformers.integrations import is_deepspeed_zero3_enabled
36
+ def get_abs_pos(abs_pos, tgt_size):
37
+ # abs_pos: L, C
38
+ # tgt_size: (H, W)
39
+ # return: M, C
40
+ src_size = int(math.sqrt(abs_pos.size(0)))
41
+ # tgt_size = int(math.sqrt(tgt_size))
42
+ dtype = abs_pos.dtype
43
+
44
+ return F.interpolate(
45
+ abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2),
46
+ size=(tgt_size[0], tgt_size[1]),
47
+ mode="bicubic",
48
+ align_corners=False,
49
+ ).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype)
50
+
51
+
52
+ # https://github.com/facebookresearch/mae/blob/efb2a8062c206524e35e47d04501ed4f544c0ae8/util/pos_embed.py#L20
53
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
54
+ """
55
+ grid_size: int of the grid height and width
56
+ return:
57
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
58
+ """
59
+ if isinstance(grid_size, int):
60
+ grid_h_size, grid_w_size = grid_size, grid_size
61
+ else:
62
+ grid_h_size, grid_w_size = grid_size[0], grid_size[1]
63
+
64
+ grid_h = np.arange(grid_h_size, dtype=np.float32)
65
+ grid_w = np.arange(grid_w_size, dtype=np.float32)
66
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
67
+ grid = np.stack(grid, axis=0)
68
+
69
+ grid = grid.reshape([2, 1, grid_h_size, grid_w_size])
70
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
71
+ if cls_token:
72
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
73
+ return pos_embed
74
+
75
+
76
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
77
+ assert embed_dim % 2 == 0
78
+
79
+ # use half of dimensions to encode grid_h
80
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
81
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
82
+
83
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
84
+ return emb
85
+
86
+
87
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
88
+ """
89
+ embed_dim: output dimension for each position
90
+ pos: a list of positions to be encoded: size (M,)
91
+ out: (M, D)
92
+ """
93
+ assert embed_dim % 2 == 0
94
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
95
+ omega /= embed_dim / 2.
96
+ omega = 1. / 10000 ** omega # (D/2,)
97
+
98
+ pos = pos.reshape(-1) # (M,)
99
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
100
+
101
+ emb_sin = np.sin(out) # (M, D/2)
102
+ emb_cos = np.cos(out) # (M, D/2)
103
+
104
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
105
+ return emb
106
+
107
+
108
+ class Resampler(nn.Module):
109
+ """
110
+ A 2D perceiver-resampler network with one cross attention layers by
111
+ (grid_size**2) learnable queries and 2d sincos pos_emb
112
+ Outputs:
113
+ A tensor with the shape of (grid_size**2, embed_dim)
114
+ """
115
+
116
+ def __init__(
117
+ self,
118
+ grid_size,
119
+ embed_dim,
120
+ num_heads,
121
+ kv_dim=None,
122
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
123
+ adaptive=False
124
+ ):
125
+ super().__init__()
126
+ self.num_queries = grid_size ** 2
127
+ self.embed_dim = embed_dim
128
+ self.num_heads = num_heads
129
+ self.adaptive = adaptive
130
+
131
+ self.pos_embed = nn.Parameter(
132
+ torch.from_numpy(get_2d_sincos_pos_embed(embed_dim, grid_size)).float()
133
+ ).requires_grad_(False)
134
+ self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
135
+
136
+ if kv_dim is not None and kv_dim != embed_dim:
137
+ self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
138
+ else:
139
+ self.kv_proj = nn.Identity()
140
+
141
+ self.attn = MultiheadAttention(embed_dim, num_heads)
142
+ self.ln_q = norm_layer(embed_dim)
143
+ self.ln_kv = norm_layer(embed_dim)
144
+
145
+ self.ln_post = norm_layer(embed_dim)
146
+ self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
147
+
148
+ def _init_weights(self, m):
149
+ if isinstance(m, nn.Linear):
150
+ trunc_normal_(m.weight, std=.02)
151
+ if isinstance(m, nn.Linear) and m.bias is not None:
152
+ nn.init.constant_(m.bias, 0)
153
+ elif isinstance(m, nn.LayerNorm):
154
+ nn.init.constant_(m.bias, 0)
155
+ nn.init.constant_(m.weight, 1.0)
156
+
157
+ def forward(self, x, tgt_size=None, attn_mask=None):
158
+ if self.adaptive:
159
+ pos_embed = torch.Tensor(get_2d_sincos_pos_embed(self.embed_dim, tgt_size)).float().to(device=x.device, dtype=x.dtype)
160
+ else:
161
+ pos_embed = get_abs_pos(self.pos_embed, tgt_size)
162
+
163
+ x = self.kv_proj(x)
164
+ x = self.ln_kv(x).permute(1, 0, 2)
165
+
166
+ N = x.shape[1]
167
+ q = self.ln_q(self.query)
168
+
169
+ out = self.attn(
170
+ self._repeat(q, N) + self.pos_embed.unsqueeze(1),
171
+ x + pos_embed.unsqueeze(1),
172
+ x,
173
+ attn_mask=attn_mask)[0]
174
+ x = out.permute(1, 0, 2)
175
+ x = self.ln_post(x)
176
+ x = x @ self.proj
177
+ return x
178
+
179
+ def _repeat(self, query, N: int):
180
+ return query.unsqueeze(1).repeat(1, N, 1)
181
+
182
+
183
+
184
+ class MultiheadAttention(nn.MultiheadAttention):
185
+ def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False,
186
+ add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None):
187
+ super().__init__(embed_dim, num_heads, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first, device, dtype)
188
+
189
+ # rewrite out_proj layer,with nn.Linear
190
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias,)
191
+
192
+ def forward(
193
+ self,
194
+ query: Tensor,
195
+ key: Tensor,
196
+ value: Tensor,
197
+ key_padding_mask: Optional[Tensor] = None,
198
+ need_weights: bool = True,
199
+ attn_mask: Optional[Tensor] = None,
200
+ average_attn_weights: bool = True,
201
+ is_causal : bool = False) -> Tuple[Tensor, Optional[Tensor]]:
202
+ why_not_fast_path = ''
203
+ if ((attn_mask is not None and torch.is_floating_point(attn_mask))
204
+ or (key_padding_mask is not None) and torch.is_floating_point(key_padding_mask)):
205
+ why_not_fast_path = "floating-point masks are not supported for fast path."
206
+
207
+ is_batched = query.dim() == 3
208
+
209
+ key_padding_mask = F._canonical_mask(
210
+ mask=key_padding_mask,
211
+ mask_name="key_padding_mask",
212
+ other_type=F._none_or_dtype(attn_mask),
213
+ other_name="attn_mask",
214
+ target_type=query.dtype
215
+ )
216
+ # _canonical_mask
217
+ attn_mask = F._canonical_mask(
218
+ mask=attn_mask,
219
+ mask_name="attn_mask",
220
+ other_type=None,
221
+ other_name="",
222
+ target_type=query.dtype,
223
+ check_other=False,
224
+ )
225
+
226
+
227
+ if not is_batched:
228
+ why_not_fast_path = f"input not batched; expected query.dim() of 3 but got {query.dim()}"
229
+ elif query is not key or key is not value:
230
+ # When lifting this restriction, don't forget to either
231
+ # enforce that the dtypes all match or test cases where
232
+ # they don't!
233
+ why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
234
+ elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
235
+ why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
236
+ elif self.in_proj_weight is None:
237
+ why_not_fast_path = "in_proj_weight was None"
238
+ elif query.dtype != self.in_proj_weight.dtype:
239
+ # this case will fail anyway, but at least they'll get a useful error message.
240
+ why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
241
+ elif self.training:
242
+ why_not_fast_path = "training is enabled"
243
+ elif (self.num_heads % 2) != 0:
244
+ why_not_fast_path = "self.num_heads is not even"
245
+ elif not self.batch_first:
246
+ why_not_fast_path = "batch_first was not True"
247
+ elif self.bias_k is not None:
248
+ why_not_fast_path = "self.bias_k was not None"
249
+ elif self.bias_v is not None:
250
+ why_not_fast_path = "self.bias_v was not None"
251
+ elif self.add_zero_attn:
252
+ why_not_fast_path = "add_zero_attn was enabled"
253
+ elif not self._qkv_same_embed_dim:
254
+ why_not_fast_path = "_qkv_same_embed_dim was not True"
255
+ elif query.is_nested and (key_padding_mask is not None or attn_mask is not None):
256
+ why_not_fast_path = "supplying both src_key_padding_mask and src_mask at the same time \
257
+ is not supported with NestedTensor input"
258
+ elif torch.is_autocast_enabled():
259
+ why_not_fast_path = "autocast is enabled"
260
+
261
+ if not why_not_fast_path:
262
+ tensor_args = (
263
+ query,
264
+ key,
265
+ value,
266
+ self.in_proj_weight,
267
+ self.in_proj_bias,
268
+ self.out_proj.weight,
269
+ self.out_proj.bias,
270
+ )
271
+ # We have to use list comprehensions below because TorchScript does not support
272
+ # generator expressions.
273
+ if torch.overrides.has_torch_function(tensor_args):
274
+ why_not_fast_path = "some Tensor argument has_torch_function"
275
+ elif _is_make_fx_tracing():
276
+ why_not_fast_path = "we are running make_fx tracing"
277
+ elif not all(_check_arg_device(x) for x in tensor_args):
278
+ why_not_fast_path = ("some Tensor argument's device is neither one of "
279
+ f"cpu, cuda or {torch.utils.backend_registration._privateuse1_backend_name}")
280
+ elif torch.is_grad_enabled() and any(_arg_requires_grad(x) for x in tensor_args):
281
+ why_not_fast_path = ("grad is enabled and at least one of query or the "
282
+ "input/output projection weights or biases requires_grad")
283
+ if not why_not_fast_path:
284
+ merged_mask, mask_type = self.merge_masks(attn_mask, key_padding_mask, query)
285
+
286
+ if self.in_proj_bias is not None and self.in_proj_weight is not None:
287
+ return torch._native_multi_head_attention(
288
+ query,
289
+ key,
290
+ value,
291
+ self.embed_dim,
292
+ self.num_heads,
293
+ self.in_proj_weight,
294
+ self.in_proj_bias,
295
+ self.out_proj.weight,
296
+ self.out_proj.bias,
297
+ merged_mask,
298
+ need_weights,
299
+ average_attn_weights,
300
+ mask_type)
301
+
302
+ any_nested = query.is_nested or key.is_nested or value.is_nested
303
+ assert not any_nested, ("MultiheadAttention does not support NestedTensor outside of its fast path. " +
304
+ f"The fast path was not hit because {why_not_fast_path}")
305
+
306
+ if self.batch_first and is_batched:
307
+ # make sure that the transpose op does not affect the "is" property
308
+ if key is value:
309
+ if query is key:
310
+ query = key = value = query.transpose(1, 0)
311
+ else:
312
+ query, key = (x.transpose(1, 0) for x in (query, key))
313
+ value = key
314
+ else:
315
+ query, key, value = (x.transpose(1, 0) for x in (query, key, value))
316
+
317
+ if not self._qkv_same_embed_dim:
318
+ attn_output, attn_output_weights = self.multi_head_attention_forward(
319
+ query, key, value, self.embed_dim, self.num_heads,
320
+ self.in_proj_weight, self.in_proj_bias,
321
+ self.bias_k, self.bias_v, self.add_zero_attn,
322
+ self.dropout, self.out_proj.weight, self.out_proj.bias,
323
+ training=self.training,
324
+ key_padding_mask=key_padding_mask, need_weights=need_weights,
325
+ attn_mask=attn_mask,
326
+ use_separate_proj_weight=True,
327
+ q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight,
328
+ v_proj_weight=self.v_proj_weight,
329
+ average_attn_weights=average_attn_weights,
330
+ is_causal=is_causal)
331
+ else:
332
+ attn_output, attn_output_weights = self.multi_head_attention_forward(
333
+ query, key, value, self.embed_dim, self.num_heads,
334
+ self.in_proj_weight, self.in_proj_bias,
335
+ self.bias_k, self.bias_v, self.add_zero_attn,
336
+ self.dropout, self.out_proj.weight, self.out_proj.bias,
337
+ training=self.training,
338
+ key_padding_mask=key_padding_mask,
339
+ need_weights=need_weights,
340
+ attn_mask=attn_mask,
341
+ average_attn_weights=average_attn_weights,
342
+ is_causal=is_causal)
343
+ if self.batch_first and is_batched:
344
+ return attn_output.transpose(1, 0), attn_output_weights
345
+ else:
346
+ return attn_output, attn_output_weights
347
+
348
+ def multi_head_attention_forward(
349
+ self,
350
+ query: Tensor,
351
+ key: Tensor,
352
+ value: Tensor,
353
+ embed_dim_to_check: int,
354
+ num_heads: int,
355
+ in_proj_weight: Optional[Tensor],
356
+ in_proj_bias: Optional[Tensor],
357
+ bias_k: Optional[Tensor],
358
+ bias_v: Optional[Tensor],
359
+ add_zero_attn: bool,
360
+ dropout_p: float,
361
+ out_proj_weight: Tensor,
362
+ out_proj_bias: Optional[Tensor],
363
+ training: bool = True,
364
+ key_padding_mask: Optional[Tensor] = None,
365
+ need_weights: bool = True,
366
+ attn_mask: Optional[Tensor] = None,
367
+ use_separate_proj_weight: bool = False,
368
+ q_proj_weight: Optional[Tensor] = None,
369
+ k_proj_weight: Optional[Tensor] = None,
370
+ v_proj_weight: Optional[Tensor] = None,
371
+ static_k: Optional[Tensor] = None,
372
+ static_v: Optional[Tensor] = None,
373
+ average_attn_weights: bool = True,
374
+ is_causal: bool = False,
375
+ ) -> Tuple[Tensor, Optional[Tensor]]:
376
+ tens_ops = (query, key, value, in_proj_weight, in_proj_bias, bias_k, bias_v, out_proj_weight, out_proj_bias)
377
+ if has_torch_function(tens_ops):
378
+ return handle_torch_function(
379
+ multi_head_attention_forward,
380
+ tens_ops,
381
+ query,
382
+ key,
383
+ value,
384
+ embed_dim_to_check,
385
+ num_heads,
386
+ in_proj_weight,
387
+ in_proj_bias,
388
+ bias_k,
389
+ bias_v,
390
+ add_zero_attn,
391
+ dropout_p,
392
+ out_proj_weight,
393
+ out_proj_bias,
394
+ training=training,
395
+ key_padding_mask=key_padding_mask,
396
+ need_weights=need_weights,
397
+ attn_mask=attn_mask,
398
+ is_causal=is_causal,
399
+ use_separate_proj_weight=use_separate_proj_weight,
400
+ q_proj_weight=q_proj_weight,
401
+ k_proj_weight=k_proj_weight,
402
+ v_proj_weight=v_proj_weight,
403
+ static_k=static_k,
404
+ static_v=static_v,
405
+ average_attn_weights=average_attn_weights,
406
+ )
407
+
408
+ is_batched = _mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
409
+
410
+ # For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
411
+ # is batched, run the computation and before returning squeeze the
412
+ # batch dimension so that the output doesn't carry this temporary batch dimension.
413
+ if not is_batched:
414
+ # unsqueeze if the input is unbatched
415
+ query = query.unsqueeze(1)
416
+ key = key.unsqueeze(1)
417
+ value = value.unsqueeze(1)
418
+ if key_padding_mask is not None:
419
+ key_padding_mask = key_padding_mask.unsqueeze(0)
420
+
421
+ # set up shape vars
422
+ tgt_len, bsz, embed_dim = query.shape
423
+ src_len, _, _ = key.shape
424
+
425
+ key_padding_mask = _canonical_mask(
426
+ mask=key_padding_mask,
427
+ mask_name="key_padding_mask",
428
+ other_type=_none_or_dtype(attn_mask),
429
+ other_name="attn_mask",
430
+ target_type=query.dtype
431
+ )
432
+
433
+ if is_causal and attn_mask is None:
434
+ raise RuntimeError(
435
+ "Need attn_mask if specifying the is_causal hint. "
436
+ "You may use the Transformer module method "
437
+ "`generate_square_subsequent_mask` to create this mask."
438
+ )
439
+
440
+ if is_causal and key_padding_mask is None and not need_weights:
441
+ # when we have a kpm or need weights, we need attn_mask
442
+ # Otherwise, we use the is_causal hint go as is_causal
443
+ # indicator to SDPA.
444
+ attn_mask = None
445
+ else:
446
+ attn_mask = _canonical_mask(
447
+ mask=attn_mask,
448
+ mask_name="attn_mask",
449
+ other_type=None,
450
+ other_name="",
451
+ target_type=query.dtype,
452
+ check_other=False,
453
+ )
454
+
455
+ if key_padding_mask is not None:
456
+ # We have the attn_mask, and use that to merge kpm into it.
457
+ # Turn off use of is_causal hint, as the merged mask is no
458
+ # longer causal.
459
+ is_causal = False
460
+
461
+ assert embed_dim == embed_dim_to_check, \
462
+ f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
463
+ if isinstance(embed_dim, torch.Tensor):
464
+ # embed_dim can be a tensor when JIT tracing
465
+ head_dim = embed_dim.div(num_heads, rounding_mode='trunc')
466
+ else:
467
+ head_dim = embed_dim // num_heads
468
+ assert head_dim * num_heads == embed_dim, f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
469
+ if use_separate_proj_weight:
470
+ # allow MHA to have different embedding dimensions when separate projection weights are used
471
+ assert key.shape[:2] == value.shape[:2], \
472
+ f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
473
+ else:
474
+ assert key.shape == value.shape, f"key shape {key.shape} does not match value shape {value.shape}"
475
+
476
+ #
477
+ # compute in-projection
478
+ #
479
+
480
+ if not use_separate_proj_weight:
481
+ assert in_proj_weight is not None, "use_separate_proj_weight is False but in_proj_weight is None"
482
+ q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
483
+ else:
484
+ assert q_proj_weight is not None, "use_separate_proj_weight is True but q_proj_weight is None"
485
+ assert k_proj_weight is not None, "use_separate_proj_weight is True but k_proj_weight is None"
486
+ assert v_proj_weight is not None, "use_separate_proj_weight is True but v_proj_weight is None"
487
+ if in_proj_bias is None:
488
+ b_q = b_k = b_v = None
489
+ else:
490
+ b_q, b_k, b_v = in_proj_bias.chunk(3)
491
+ q, k, v = _in_projection(query, key, value, q_proj_weight, k_proj_weight, v_proj_weight, b_q, b_k, b_v)
492
+
493
+ # prep attention mask
494
+
495
+ if attn_mask is not None:
496
+ # ensure attn_mask's dim is 3
497
+ if attn_mask.dim() == 2:
498
+ correct_2d_size = (tgt_len, src_len)
499
+ if attn_mask.shape != correct_2d_size:
500
+ raise RuntimeError(f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}.")
501
+ attn_mask = attn_mask.unsqueeze(0)
502
+ elif attn_mask.dim() == 3:
503
+ correct_3d_size = (bsz * num_heads, tgt_len, src_len)
504
+ if attn_mask.shape != correct_3d_size:
505
+ raise RuntimeError(f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}.")
506
+ else:
507
+ raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
508
+
509
+ # add bias along batch dimension (currently second)
510
+ if bias_k is not None and bias_v is not None:
511
+ assert static_k is None, "bias cannot be added to static key."
512
+ assert static_v is None, "bias cannot be added to static value."
513
+ k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
514
+ v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
515
+ if attn_mask is not None:
516
+ attn_mask = pad(attn_mask, (0, 1))
517
+ if key_padding_mask is not None:
518
+ key_padding_mask = pad(key_padding_mask, (0, 1))
519
+ else:
520
+ assert bias_k is None
521
+ assert bias_v is None
522
+
523
+ #
524
+ # reshape q, k, v for multihead attention and make em batch first
525
+ #
526
+ q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
527
+ if static_k is None:
528
+ k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
529
+ else:
530
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
531
+ assert static_k.size(0) == bsz * num_heads, \
532
+ f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
533
+ assert static_k.size(2) == head_dim, \
534
+ f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
535
+ k = static_k
536
+ if static_v is None:
537
+ v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
538
+ else:
539
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
540
+ assert static_v.size(0) == bsz * num_heads, \
541
+ f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
542
+ assert static_v.size(2) == head_dim, \
543
+ f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
544
+ v = static_v
545
+
546
+ # add zero attention along batch dimension (now first)
547
+ if add_zero_attn:
548
+ zero_attn_shape = (bsz * num_heads, 1, head_dim)
549
+ k = torch.cat([k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1)
550
+ v = torch.cat([v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1)
551
+ if attn_mask is not None:
552
+ attn_mask = pad(attn_mask, (0, 1))
553
+ if key_padding_mask is not None:
554
+ key_padding_mask = pad(key_padding_mask, (0, 1))
555
+
556
+ # update source sequence length after adjustments
557
+ src_len = k.size(1)
558
+
559
+ # merge key padding and attention masks
560
+ if key_padding_mask is not None:
561
+ assert key_padding_mask.shape == (bsz, src_len), \
562
+ f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
563
+ key_padding_mask = key_padding_mask.view(bsz, 1, 1, src_len). \
564
+ expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
565
+ if attn_mask is None:
566
+ attn_mask = key_padding_mask
567
+ else:
568
+ attn_mask = attn_mask + key_padding_mask
569
+
570
+ # adjust dropout probability
571
+ if not training:
572
+ dropout_p = 0.0
573
+
574
+ #
575
+ # (deep breath) calculate attention and out projection
576
+ #
577
+
578
+ if need_weights:
579
+ B, Nt, E = q.shape
580
+ q_scaled = q / math.sqrt(E)
581
+
582
+ assert not (is_causal and attn_mask is None), "FIXME: is_causal not implemented for need_weights"
583
+
584
+ if attn_mask is not None:
585
+ attn_output_weights = torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1))
586
+ else:
587
+ attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
588
+ attn_output_weights = softmax(attn_output_weights, dim=-1)
589
+ if dropout_p > 0.0:
590
+ attn_output_weights = dropout(attn_output_weights, p=dropout_p)
591
+
592
+ attn_output = torch.bmm(attn_output_weights, v)
593
+
594
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
595
+ attn_output = self.out_proj(attn_output)
596
+
597
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
598
+
599
+ # optionally average attention weights over heads
600
+ attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
601
+ if average_attn_weights:
602
+ attn_output_weights = attn_output_weights.mean(dim=1)
603
+
604
+ if not is_batched:
605
+ # squeeze the output if input was unbatched
606
+ attn_output = attn_output.squeeze(1)
607
+ attn_output_weights = attn_output_weights.squeeze(0)
608
+ return attn_output, attn_output_weights
609
+ else:
610
+ # attn_mask can be either (L,S) or (N*num_heads, L, S)
611
+ # if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
612
+ # in order to match the input for SDPA of (N, num_heads, L, S)
613
+ if attn_mask is not None:
614
+ if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
615
+ attn_mask = attn_mask.unsqueeze(0)
616
+ else:
617
+ attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
618
+
619
+ q = q.view(bsz, num_heads, tgt_len, head_dim)
620
+ k = k.view(bsz, num_heads, src_len, head_dim)
621
+ v = v.view(bsz, num_heads, src_len, head_dim)
622
+
623
+ attn_output = F.scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
624
+ attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
625
+
626
+ attn_output = self.out_proj(attn_output)
627
+
628
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
629
+ if not is_batched:
630
+ # squeeze the output if input was unbatched
631
+ attn_output = attn_output.squeeze(1)
632
+ return attn_output, None
633
+
634
+
635
+ def _mha_shape_check(query: Tensor, key: Tensor, value: Tensor,
636
+ key_padding_mask: Optional[Tensor], attn_mask: Optional[Tensor], num_heads: int):
637
+ # Verifies the expected shape for `query, `key`, `value`, `key_padding_mask` and `attn_mask`
638
+ # and returns if the input is batched or not.
639
+ # Raises an error if `query` is not 2-D (unbatched) or 3-D (batched) tensor.
640
+
641
+ # Shape check.
642
+ if query.dim() == 3:
643
+ # Batched Inputs
644
+ is_batched = True
645
+ assert key.dim() == 3 and value.dim() == 3, \
646
+ ("For batched (3-D) `query`, expected `key` and `value` to be 3-D"
647
+ f" but found {key.dim()}-D and {value.dim()}-D tensors respectively")
648
+ if key_padding_mask is not None:
649
+ assert key_padding_mask.dim() == 2, \
650
+ ("For batched (3-D) `query`, expected `key_padding_mask` to be `None` or 2-D"
651
+ f" but found {key_padding_mask.dim()}-D tensor instead")
652
+ if attn_mask is not None:
653
+ assert attn_mask.dim() in (2, 3), \
654
+ ("For batched (3-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
655
+ f" but found {attn_mask.dim()}-D tensor instead")
656
+ elif query.dim() == 2:
657
+ # Unbatched Inputs
658
+ is_batched = False
659
+ assert key.dim() == 2 and value.dim() == 2, \
660
+ ("For unbatched (2-D) `query`, expected `key` and `value` to be 2-D"
661
+ f" but found {key.dim()}-D and {value.dim()}-D tensors respectively")
662
+
663
+ if key_padding_mask is not None:
664
+ assert key_padding_mask.dim() == 1, \
665
+ ("For unbatched (2-D) `query`, expected `key_padding_mask` to be `None` or 1-D"
666
+ f" but found {key_padding_mask.dim()}-D tensor instead")
667
+
668
+ if attn_mask is not None:
669
+ assert attn_mask.dim() in (2, 3), \
670
+ ("For unbatched (2-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
671
+ f" but found {attn_mask.dim()}-D tensor instead")
672
+ if attn_mask.dim() == 3:
673
+ expected_shape = (num_heads, query.shape[0], key.shape[0])
674
+ assert attn_mask.shape == expected_shape, \
675
+ (f"Expected `attn_mask` shape to be {expected_shape} but got {attn_mask.shape}")
676
+ else:
677
+ raise AssertionError(
678
+ f"query should be unbatched 2D or batched 3D tensor but received {query.dim()}-D query tensor")
679
+
680
+ return is_batched
681
+
682
+
683
+ def _canonical_mask(
684
+ mask: Optional[Tensor],
685
+ mask_name: str,
686
+ other_type: Optional[DType],
687
+ other_name: str,
688
+ target_type: DType,
689
+ check_other: bool = True,
690
+ ) -> Optional[Tensor]:
691
+
692
+ if mask is not None:
693
+ _mask_dtype = mask.dtype
694
+ _mask_is_float = torch.is_floating_point(mask)
695
+ if _mask_dtype != torch.bool and not _mask_is_float:
696
+ raise AssertionError(
697
+ f"only bool and floating types of {mask_name} are supported")
698
+ if check_other and other_type is not None:
699
+ if _mask_dtype != other_type:
700
+ warnings.warn(
701
+ f"Support for mismatched {mask_name} and {other_name} "
702
+ "is deprecated. Use same type for both instead."
703
+ )
704
+ if not _mask_is_float:
705
+ mask = (
706
+ torch.zeros_like(mask, dtype=target_type)
707
+ .masked_fill_(mask, float("-inf"))
708
+ )
709
+ return mask
710
+
711
+
712
+ def _none_or_dtype(input: Optional[Tensor]) -> Optional[DType]:
713
+ if input is None:
714
+ return None
715
+ elif isinstance(input, torch.Tensor):
716
+ return input.dtype
717
+ raise RuntimeError("input to _none_or_dtype() must be None or torch.Tensor")
718
+
719
+ def _in_projection_packed(
720
+ q: Tensor,
721
+ k: Tensor,
722
+ v: Tensor,
723
+ w: Tensor,
724
+ b: Optional[Tensor] = None,
725
+ ) -> List[Tensor]:
726
+ r"""
727
+ Performs the in-projection step of the attention operation, using packed weights.
728
+ Output is a triple containing projection tensors for query, key and value.
729
+ Args:
730
+ q, k, v: query, key and value tensors to be projected. For self-attention,
731
+ these are typically the same tensor; for encoder-decoder attention,
732
+ k and v are typically the same tensor. (We take advantage of these
733
+ identities for performance if they are present.) Regardless, q, k and v
734
+ must share a common embedding dimension; otherwise their shapes may vary.
735
+ w: projection weights for q, k and v, packed into a single tensor. Weights
736
+ are packed along dimension 0, in q, k, v order.
737
+ b: optional projection biases for q, k and v, packed into a single tensor
738
+ in q, k, v order.
739
+ Shape:
740
+ Inputs:
741
+ - q: :math:`(..., E)` where E is the embedding dimension
742
+ - k: :math:`(..., E)` where E is the embedding dimension
743
+ - v: :math:`(..., E)` where E is the embedding dimension
744
+ - w: :math:`(E * 3, E)` where E is the embedding dimension
745
+ - b: :math:`E * 3` where E is the embedding dimension
746
+ Output:
747
+ - in output list :math:`[q', k', v']`, each output tensor will have the
748
+ same shape as the corresponding input tensor.
749
+ """
750
+ E = q.size(-1)
751
+ if k is v:
752
+ if q is k:
753
+ # self-attention
754
+ proj = linear(q, w, b)
755
+ # reshape to 3, E and not E, 3 is deliberate for better memory coalescing and keeping same order as chunk()
756
+ proj = proj.unflatten(-1, (3, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
757
+ return proj[0], proj[1], proj[2]
758
+ else:
759
+ # encoder-decoder attention
760
+ w_q, w_kv = w.split([E, E * 2])
761
+ if b is None:
762
+ b_q = b_kv = None
763
+ else:
764
+ b_q, b_kv = b.split([E, E * 2])
765
+ q_proj = linear(q, w_q, b_q)
766
+ kv_proj = linear(k, w_kv, b_kv)
767
+ # reshape to 2, E and not E, 2 is deliberate for better memory coalescing and keeping same order as chunk()
768
+ kv_proj = kv_proj.unflatten(-1, (2, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
769
+ return (q_proj, kv_proj[0], kv_proj[1])
770
+ else:
771
+ w_q, w_k, w_v = w.chunk(3)
772
+ if b is None:
773
+ b_q = b_k = b_v = None
774
+ else:
775
+ b_q, b_k, b_v = b.chunk(3)
776
+ return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
777
+
778
+
779
+ def _in_projection(
780
+ q: Tensor,
781
+ k: Tensor,
782
+ v: Tensor,
783
+ w_q: Tensor,
784
+ w_k: Tensor,
785
+ w_v: Tensor,
786
+ b_q: Optional[Tensor] = None,
787
+ b_k: Optional[Tensor] = None,
788
+ b_v: Optional[Tensor] = None,
789
+ ) -> Tuple[Tensor, Tensor, Tensor]:
790
+ r"""
791
+ Performs the in-projection step of the attention operation. This is simply
792
+ a triple of linear projections, with shape constraints on the weights which
793
+ ensure embedding dimension uniformity in the projected outputs.
794
+ Output is a triple containing projection tensors for query, key and value.
795
+ Args:
796
+ q, k, v: query, key and value tensors to be projected.
797
+ w_q, w_k, w_v: weights for q, k and v, respectively.
798
+ b_q, b_k, b_v: optional biases for q, k and v, respectively.
799
+ Shape:
800
+ Inputs:
801
+ - q: :math:`(Qdims..., Eq)` where Eq is the query embedding dimension and Qdims are any
802
+ number of leading dimensions.
803
+ - k: :math:`(Kdims..., Ek)` where Ek is the key embedding dimension and Kdims are any
804
+ number of leading dimensions.
805
+ - v: :math:`(Vdims..., Ev)` where Ev is the value embedding dimension and Vdims are any
806
+ number of leading dimensions.
807
+ - w_q: :math:`(Eq, Eq)`
808
+ - w_k: :math:`(Eq, Ek)`
809
+ - w_v: :math:`(Eq, Ev)`
810
+ - b_q: :math:`(Eq)`
811
+ - b_k: :math:`(Eq)`
812
+ - b_v: :math:`(Eq)`
813
+ Output: in output triple :math:`(q', k', v')`,
814
+ - q': :math:`[Qdims..., Eq]`
815
+ - k': :math:`[Kdims..., Eq]`
816
+ - v': :math:`[Vdims..., Eq]`
817
+ """
818
+ Eq, Ek, Ev = q.size(-1), k.size(-1), v.size(-1)
819
+ assert w_q.shape == (Eq, Eq), f"expecting query weights shape of {(Eq, Eq)}, but got {w_q.shape}"
820
+ assert w_k.shape == (Eq, Ek), f"expecting key weights shape of {(Eq, Ek)}, but got {w_k.shape}"
821
+ assert w_v.shape == (Eq, Ev), f"expecting value weights shape of {(Eq, Ev)}, but got {w_v.shape}"
822
+ assert b_q is None or b_q.shape == (Eq,), f"expecting query bias shape of {(Eq,)}, but got {b_q.shape}"
823
+ assert b_k is None or b_k.shape == (Eq,), f"expecting key bias shape of {(Eq,)}, but got {b_k.shape}"
824
+ assert b_v is None or b_v.shape == (Eq,), f"expecting value bias shape of {(Eq,)}, but got {b_v.shape}"
825
+ return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)