Teaven commited on
Commit
219064e
·
verified ·
1 Parent(s): c3487cc

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/fs/archive/share/yulan/data/aa_mini/output/minicpm-2B-final-stage19-hyw/checkpoint-176750",
3
+ "architectures": [
4
+ "MiniCPMForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_minicpm.MiniCPMConfig",
8
+ "AutoModel": "modeling_minicpm.MiniCPMModel",
9
+ "AutoModelForCausalLM": "modeling_minicpm.MiniCPMForCausalLM",
10
+ "AutoModelForSeq2SeqLM": "modeling_minicpm.MiniCPMForCausalLM",
11
+ "AutoModelForSequenceClassification": "modeling_minicpm.MiniCPMForSequenceClassification"
12
+ },
13
+ "attention_bias": true,
14
+ "attention_dropout": 0.0,
15
+ "bos_token_id": 1,
16
+ "dim_model_base": 1920,
17
+ "dim_model_base_attn": 64,
18
+ "dim_model_base_init": null,
19
+ "dim_model_base_lmh": 1,
20
+ "dim_model_base_logits": 1920.0,
21
+ "dim_model_base_lr": 256.0,
22
+ "down_proj_alpha": 0.03450327796711771,
23
+ "embed_tokens_alpha": 1,
24
+ "embedding_ln": false,
25
+ "embedding_rmsln": false,
26
+ "eos_token_id": 2,
27
+ "gate_up_proj_alpha": 0.3651483716701107,
28
+ "gradient_checkpointing_step": 11,
29
+ "hidden_act": "silu",
30
+ "hidden_size": 1920,
31
+ "hidden_states_shrink": 0.18708286933869706,
32
+ "init_scale_o": 1,
33
+ "initializer_range": 5e-05,
34
+ "input_layernorm_alpha": 1.0,
35
+ "intermediate_size": 4800,
36
+ "k_proj_alpha": 0.3651483716701107,
37
+ "layer_norm_eps": 1e-06,
38
+ "lm_head_alpha": 1.0,
39
+ "ln_scale": 1,
40
+ "max_position_embeddings": 4096,
41
+ "model_reproduce": "transformer",
42
+ "model_type": "minicpm",
43
+ "norm_alpha": 1.0,
44
+ "num_attention_heads": 30,
45
+ "num_epochs_trained_before_this_epoch": 18,
46
+ "num_hidden_layers": 56,
47
+ "num_key_value_heads": 6,
48
+ "num_steps_trained_before_this_epoch": 175066,
49
+ "o_proj_alpha": 0.03450327796711771,
50
+ "post_attention_layernorm_alpha": 1.0,
51
+ "q_proj_alpha": 0.3651483716701107,
52
+ "qk_layernorm": false,
53
+ "rms_norm_eps": 1e-06,
54
+ "rms_type": "llama",
55
+ "rope_scaling": null,
56
+ "rope_theta": 10000.0,
57
+ "scale_emb": 10.0,
58
+ "shrink_alpha": 1,
59
+ "sliding_window": null,
60
+ "tie_word_embeddings": false,
61
+ "torch_dtype": "bfloat16",
62
+ "transformers_version": "4.44.2",
63
+ "use_cache": true,
64
+ "use_emb_alpha": true,
65
+ "use_liger": true,
66
+ "use_norm_alpha": false,
67
+ "use_sliding_window": false,
68
+ "v_proj_alpha": 0.3651483716701107,
69
+ "vocab_size": 99000,
70
+ "wesar_weights": false,
71
+ "z_loss": 0.0001
72
+ }
configuration_minicpm.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import math
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ MINICPM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class MiniCPMConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`MiniCPMModel`]. It is used to instantiate an MiniCPM
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the MiniCPM-7B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the MiniCPM model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`MiniCPMModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 11008):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
64
+ The maximum sequence length that this model might ever be used with. MiniCPM 1 supports up to 2048 tokens,
65
+ MiniCPM 2 up to 4096, CodeMiniCPM up to 16384.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ The epsilon used by the rms normalization layers.
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
72
+ relevant if `config.is_decoder=True`.
73
+ pad_token_id (`int`, *optional*):
74
+ Padding token id.
75
+ bos_token_id (`int`, *optional*, defaults to 1):
76
+ Beginning of stream token id.
77
+ eos_token_id (`int`, *optional*, defaults to 2):
78
+ End of stream token id.
79
+ pretraining_tp (`int`, *optional*, defaults to 1):
80
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
81
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
82
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
83
+ issue](https://github.com/pytorch/pytorch/issues/76232).
84
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
85
+ Whether to tie weight embeddings
86
+ rope_theta (`float`, *optional*, defaults to 10000.0):
87
+ The base period of the RoPE embeddings.
88
+ rope_scaling (`Dict`, *optional*):
89
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
90
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
91
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
92
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
93
+ these scaling strategies behave:
94
+ https://www.reddit.com/r/LocalMiniCPM/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
95
+ experimental feature, subject to breaking API changes in future versions.
96
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
97
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
98
+ attention_dropout (`float`, *optional*, defaults to 0.0):
99
+ The dropout ratio for the attention probabilities.
100
+
101
+ ```python
102
+ >>> from transformers import MiniCPMModel, MiniCPMConfig
103
+
104
+ >>> # Initializing a MiniCPM minicpm-7b style configuration
105
+ >>> configuration = MiniCPMConfig()
106
+
107
+ >>> # Initializing a model from the minicpm-7b style configuration
108
+ >>> model = MiniCPMModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "minicpm"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=99000,
120
+ hidden_size=1920,
121
+ intermediate_size=4800,
122
+ num_hidden_layers=56,
123
+ num_attention_heads=30,
124
+ num_key_value_heads=6,
125
+
126
+ # 不常用变量
127
+ hidden_act="silu",
128
+ max_position_embeddings=4096,
129
+ rms_norm_eps=1e-6,
130
+ use_cache=True,
131
+ pad_token_id=None, # /home/u20140041/pretrain-mini/preprocess/modify_tokenizer/1731
132
+ bos_token_id=1,
133
+ eos_token_id=2,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ use_sliding_window=False,
137
+ sliding_window=4096,
138
+ rope_scaling=None,
139
+ attention_bias=True, # qwen
140
+ attention_dropout=0.0,
141
+ # 放缩embedding grad
142
+ shrink_alpha=1,
143
+ shrink_alpha2=1,
144
+ use_liger=False,
145
+ # 初始化
146
+ initializer_range=0.014434,
147
+ init_scale_o=10.582218,
148
+ model_reproduce="minicpm",
149
+ # 下面是为了muparam设置的参数,需要保证:默认值是不使用任何muparam的部分
150
+ hidden_states_shrink=1,
151
+ dim_model_base=None,
152
+ dim_ffn_base_init=None, # 新版muparam没有使用了
153
+ dim_model_base_init=None,
154
+ dim_model_base_attn=None,
155
+ dim_model_base_lmh=None,
156
+ dim_model_base_logits=None,
157
+ dim_model_base_lr=None,
158
+ scale_emb=1,
159
+ # qk_layernorm
160
+ qk_layernorm=False,
161
+ layer_norm_eps=1e-6,
162
+ embedding_ln=False,
163
+ embedding_rmsln=False,
164
+ ln_scale=1.,
165
+ z_loss=0.0001,
166
+ # wesar
167
+ wesar_weights=True,
168
+ q_proj_alpha=1,
169
+ k_proj_alpha=1,
170
+ v_proj_alpha=1,
171
+ o_proj_alpha=1,
172
+ down_proj_alpha=1,
173
+ gate_up_proj_alpha=1,
174
+ input_layernorm_alpha=1,
175
+ post_attention_layernorm_alpha=1,
176
+ norm_alpha=1,
177
+ lm_head_alpha=1,
178
+ use_norm_alpha=False,
179
+ # 加速
180
+ gradient_checkpointing_step=7,
181
+ **kwargs,
182
+ ):
183
+ self.vocab_size = vocab_size
184
+ self.max_position_embeddings = max_position_embeddings
185
+ self.hidden_size = hidden_size
186
+ self.intermediate_size = intermediate_size
187
+ self.num_hidden_layers = num_hidden_layers
188
+ self.num_attention_heads = num_attention_heads
189
+ self.use_sliding_window = use_sliding_window
190
+ self.sliding_window = sliding_window if use_sliding_window else None
191
+
192
+ # for backward compatibility
193
+ if num_key_value_heads is None:
194
+ num_key_value_heads = num_attention_heads
195
+
196
+ self.num_key_value_heads = num_key_value_heads
197
+ self.hidden_act = hidden_act
198
+ self.initializer_range = initializer_range
199
+ self.rms_norm_eps = rms_norm_eps
200
+ self.use_cache = use_cache
201
+ self.rope_theta = rope_theta
202
+ self.rope_scaling = rope_scaling
203
+ self._rope_scaling_validation()
204
+ self.attention_bias = attention_bias
205
+ self.attention_dropout = attention_dropout
206
+ self.shrink_alpha = shrink_alpha
207
+ self.use_liger = use_liger
208
+ self.init_scale_o = init_scale_o
209
+ self.hidden_states_shrink = 1 / math.sqrt(num_hidden_layers) if hidden_states_shrink == "muparam" else hidden_states_shrink
210
+ self.dim_model_base = dim_model_base if dim_model_base is not None else hidden_size
211
+ self.dim_model_base_init = dim_model_base_init
212
+ self.dim_model_base_attn = dim_model_base_attn if dim_model_base_attn is not None else (hidden_size // num_attention_heads) # 初始化为1则是使用1/H_dim
213
+ self.dim_model_base_lmh = dim_model_base_lmh if dim_model_base_lmh is not None else 1 # 初始化为1则是不放缩lm_head的init
214
+ self.scale_emb = scale_emb if scale_emb is not None else 1
215
+ self.model_reproduce=model_reproduce if model_reproduce is not None else "minicpm"
216
+ self.dim_model_base_logits = dim_model_base_logits if dim_model_base_logits is not None else hidden_size
217
+ self.dim_model_base_lr = dim_model_base_lr if dim_model_base_lr is not None else hidden_size
218
+
219
+ self.qk_layernorm = qk_layernorm
220
+ self.layer_norm_eps = layer_norm_eps
221
+ self.embedding_ln = embedding_ln
222
+ self.embedding_rmsln = embedding_rmsln
223
+ self.ln_scale = ln_scale
224
+ self.z_loss = z_loss
225
+
226
+ if embedding_ln and embedding_rmsln:
227
+ raise ValueError("Only one of embedding_ln and embedding_rmsln should be True")
228
+
229
+ self.wesar_weights = wesar_weights
230
+ self.q_proj_alpha = q_proj_alpha
231
+ self.k_proj_alpha = k_proj_alpha
232
+ self.v_proj_alpha = v_proj_alpha
233
+ self.o_proj_alpha = o_proj_alpha
234
+ self.down_proj_alpha = down_proj_alpha
235
+ self.gate_up_proj_alpha = gate_up_proj_alpha
236
+ self.input_layernorm_alpha = input_layernorm_alpha
237
+ self.post_attention_layernorm_alpha = post_attention_layernorm_alpha
238
+ self.norm_alpha = norm_alpha
239
+ self.lm_head_alpha = lm_head_alpha
240
+ self.use_norm_alpha=use_norm_alpha
241
+
242
+ self.gradient_checkpointing_step = gradient_checkpointing_step
243
+
244
+
245
+ super().__init__(
246
+ pad_token_id=pad_token_id,
247
+ bos_token_id=bos_token_id,
248
+ eos_token_id=eos_token_id,
249
+ tie_word_embeddings=tie_word_embeddings,
250
+ **kwargs,
251
+ )
252
+ try:
253
+ import flash_attn
254
+ self._attn_implementation = "flash_attention_2"
255
+ except:
256
+ pass
257
+
258
+ def _rope_scaling_validation(self):
259
+ """
260
+ Validate the `rope_scaling` configuration.
261
+ """
262
+ if self.rope_scaling is None:
263
+ return
264
+
265
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
266
+ raise ValueError(
267
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
268
+ f"got {self.rope_scaling}"
269
+ )
270
+ rope_scaling_type = self.rope_scaling.get("type", None)
271
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
272
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
273
+ raise ValueError(
274
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
275
+ )
276
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
277
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:329dcec54cc96b9b2e737a3d4285e2762950d1849bd88dc5693e9877bdd776fd
3
+ size 4848612536
modeling_minicpm.py ADDED
@@ -0,0 +1,1489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 warnings
23
+ from typing import List, Optional, Tuple, Union, Dict
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
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 BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.utils.import_utils import is_torch_fx_available
51
+ from .configuration_minicpm import MiniCPMConfig
52
+ import re
53
+
54
+ try:
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+ except:
58
+ pass
59
+
60
+
61
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
62
+ # It means that the function will not be traced through and simply appear as a node in the graph.
63
+ if is_torch_fx_available():
64
+ if not is_torch_greater_or_equal_than_1_13:
65
+ import torch.fx
66
+
67
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
68
+
69
+
70
+ logger = logging.get_logger(__name__)
71
+
72
+ _CONFIG_FOR_DOC = "MiniCPMConfig"
73
+
74
+
75
+ def _get_unpad_data(attention_mask):
76
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
77
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
78
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
79
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
80
+ return (
81
+ indices,
82
+ cu_seqlens,
83
+ max_seqlen_in_batch,
84
+ )
85
+
86
+
87
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
88
+ warnings.warn(
89
+ "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"
90
+ )
91
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
92
+
93
+
94
+ def _make_causal_mask(
95
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
96
+ ):
97
+ warnings.warn(
98
+ "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"
99
+ )
100
+ return AttentionMaskConverter._make_causal_mask(
101
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
102
+ )
103
+
104
+ # @torch.jit.script # type: ignore
105
+ # def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
106
+ # old_dtype = hidden.dtype
107
+ # variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
108
+ # hidden = (hidden * torch.rsqrt(variance + eps))
109
+ # return (hidden * weight).to(old_dtype)
110
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
111
+ old_dtype = hidden.dtype
112
+ hidden_fp32 = hidden.to(torch.float32)
113
+ variance = hidden_fp32.square().mean(dim=-1, keepdim=True)
114
+ hidden = (hidden_fp32 * (variance + eps).rsqrt()).to(old_dtype)
115
+ hidden *= weight
116
+ return hidden
117
+
118
+
119
+ class MiniCPMRMSNorm(nn.Module):
120
+ def __init__(self, hidden_size, eps=1e-6, offset=1.0):
121
+ """
122
+ MiniCPMRMSNorm is equivalent to T5LayerNorm
123
+ """
124
+ super().__init__()
125
+ self.weight = nn.Parameter(torch.ones(hidden_size))
126
+ self.variance_epsilon = eps
127
+ self.offset = offset
128
+
129
+ def forward(self, hidden_states):
130
+ return rms_layernorm(hidden_states, self.weight.float() + self.offset, self.variance_epsilon)
131
+
132
+
133
+ ALL_LAYERNORM_LAYERS.append(MiniCPMRMSNorm)
134
+
135
+
136
+ class MiniCPMRotaryEmbedding(nn.Module):
137
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
138
+ super().__init__()
139
+
140
+ self.dim = dim
141
+ self.max_position_embeddings = max_position_embeddings
142
+ self.base = base
143
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
144
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
145
+
146
+ # Build here to make `torch.jit.trace` work.
147
+ self._set_cos_sin_cache(
148
+ # seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
149
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
150
+ )
151
+
152
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
153
+ self.max_seq_len_cached = seq_len
154
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
155
+ freqs = torch.outer(t, self.inv_freq)
156
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
157
+ emb = torch.cat((freqs, freqs), dim=-1)
158
+
159
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
160
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
161
+
162
+ def forward(self, x, seq_len=None):
163
+ # x: [bs, num_attention_heads, seq_len, head_size]
164
+ if seq_len > self.max_seq_len_cached:
165
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
166
+
167
+ return (
168
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
169
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
170
+ )
171
+
172
+
173
+ class MiniCPMLinearScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
174
+ """MiniCPMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
175
+
176
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
177
+ self.scaling_factor = scaling_factor
178
+ super().__init__(dim, max_position_embeddings, base, device)
179
+
180
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
181
+ self.max_seq_len_cached = seq_len
182
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
183
+ t = t / self.scaling_factor
184
+
185
+ freqs = torch.outer(t, self.inv_freq)
186
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
187
+ emb = torch.cat((freqs, freqs), dim=-1)
188
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
189
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
190
+
191
+
192
+ class MiniCPMDynamicNTKScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
193
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
194
+
195
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
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
+
202
+ if seq_len > self.max_position_embeddings:
203
+ base = self.base * (
204
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
205
+ ) ** (self.dim / (self.dim - 2))
206
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
207
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
208
+
209
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
210
+
211
+ freqs = torch.outer(t, self.inv_freq)
212
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
213
+ emb = torch.cat((freqs, freqs), dim=-1)
214
+
215
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
216
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
217
+
218
+
219
+ def rotate_half(x):
220
+ """Rotates half the hidden dims of the input."""
221
+ x1 = x[..., : x.shape[-1] // 2]
222
+ x2 = x[..., x.shape[-1] // 2 :]
223
+ return torch.cat((-x2, x1), dim=-1)
224
+
225
+
226
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
227
+ """Applies Rotary Position Embedding to the query and key tensors.
228
+
229
+ Args:
230
+ q (`torch.Tensor`): The query tensor.
231
+ k (`torch.Tensor`): The key tensor.
232
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
233
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
234
+ position_ids (`torch.Tensor`):
235
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
236
+ used to pass offsetted position ids when working with a KV-cache.
237
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
238
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
239
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
240
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
241
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
242
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
243
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
244
+ Returns:
245
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
246
+ """
247
+ # cos = cos[position_ids].unsqueeze(unsqueeze_dim)
248
+ # sin = sin[position_ids].unsqueeze(unsqueeze_dim)
249
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
250
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
251
+ orig_dtype = k.dtype
252
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
253
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
254
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
255
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
256
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
257
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
258
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
259
+
260
+ class MiniCPMMLP(nn.Module):
261
+ def __init__(self, config):
262
+ super().__init__()
263
+ self.config = config
264
+ self.hidden_size = config.hidden_size
265
+ self.intermediate_size = config.intermediate_size
266
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
267
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
268
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
269
+ self.act_fn = ACT2FN[config.hidden_act]
270
+
271
+ def forward(self, x):
272
+
273
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
274
+
275
+ return down_proj
276
+
277
+
278
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
279
+ """
280
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
281
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
282
+ """
283
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
284
+ if n_rep == 1:
285
+ return hidden_states
286
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
287
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
288
+
289
+ class StableLmLayerNormPerHead(nn.Module):
290
+ def __init__(self, dim, num_heads, eps=1e-5, bias=False, use_liger=False):
291
+ super().__init__()
292
+ self.dim = dim
293
+ self.num_heads = num_heads
294
+ if use_liger:
295
+ self.norms = nn.ModuleList([LigerLayerNorm(dim, eps=eps, bias=bias) for _ in range(self.num_heads)])
296
+ else:
297
+ self.norms = nn.ModuleList([nn.LayerNorm(dim, eps=eps, bias=bias) for _ in range(self.num_heads)])
298
+
299
+ def forward(self, hidden_states: torch.Tensor):
300
+ # Split along the num_heads axis to get per-head inputs
301
+ # [batch_size, num_heads, seq_len, head_dim] -> [batch_size, 1, seq_len, head_dim] * num_heads
302
+ states_per_heads = torch.split(hidden_states, 1, dim=1)
303
+ # Normalize and merge the heads back together
304
+ return torch.cat([norm(hidden_states) for norm, hidden_states in zip(self.norms, states_per_heads)], dim=1)
305
+
306
+
307
+ class MiniCPMAttention(nn.Module):
308
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
309
+
310
+ def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
311
+ super().__init__()
312
+ self.config = config
313
+ self.layer_idx = layer_idx
314
+ if layer_idx is None:
315
+ logger.warning_once(
316
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
317
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
318
+ "when creating this class."
319
+ )
320
+
321
+ self.attention_dropout = config.attention_dropout
322
+ self.hidden_size = config.hidden_size
323
+ self.num_heads = config.num_attention_heads
324
+ self.head_dim = self.hidden_size // self.num_heads
325
+ self.num_key_value_heads = config.num_key_value_heads
326
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
327
+ self.max_position_embeddings = config.max_position_embeddings
328
+ self.rope_theta = config.rope_theta
329
+ self.is_causal = True
330
+
331
+ if (self.head_dim * self.num_heads) != self.hidden_size:
332
+ raise ValueError(
333
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
334
+ f" and `num_heads`: {self.num_heads})."
335
+ )
336
+
337
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
338
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
339
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
340
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
341
+ self._init_rope()
342
+
343
+ self.qk_layernorm = config.qk_layernorm
344
+ if self.qk_layernorm:
345
+ self.q_layernorm = StableLmLayerNormPerHead(
346
+ self.head_dim, self.num_heads, eps=config.layer_norm_eps, use_liger=config.use_liger,
347
+ )
348
+ self.k_layernorm = StableLmLayerNormPerHead(
349
+ self.head_dim, self.num_key_value_heads, eps=config.layer_norm_eps, use_liger=config.use_liger,
350
+ )
351
+
352
+ def _init_rope(self):
353
+ if self.config.rope_scaling is None:
354
+ self.rotary_emb = MiniCPMRotaryEmbedding(
355
+ self.head_dim,
356
+ max_position_embeddings=self.max_position_embeddings,
357
+ base=self.rope_theta,
358
+ )
359
+ else:
360
+ scaling_type = self.config.rope_scaling["type"]
361
+ scaling_factor = self.config.rope_scaling["factor"]
362
+ if scaling_type == "linear":
363
+ self.rotary_emb = MiniCPMLinearScalingRotaryEmbedding(
364
+ self.head_dim,
365
+ max_position_embeddings=self.max_position_embeddings,
366
+ scaling_factor=scaling_factor,
367
+ base=self.rope_theta,
368
+ )
369
+ elif scaling_type == "dynamic":
370
+ self.rotary_emb = MiniCPMDynamicNTKScalingRotaryEmbedding(
371
+ self.head_dim,
372
+ max_position_embeddings=self.max_position_embeddings,
373
+ scaling_factor=scaling_factor,
374
+ base=self.rope_theta,
375
+ )
376
+ else:
377
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
378
+
379
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
380
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
381
+
382
+ def forward(
383
+ self,
384
+ hidden_states: torch.Tensor,
385
+ attention_mask: Optional[torch.Tensor] = None,
386
+ position_ids: Optional[torch.LongTensor] = None,
387
+ past_key_value: Optional[Cache] = None,
388
+ output_attentions: bool = False,
389
+ use_cache: bool = False,
390
+ **kwargs,
391
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
392
+ if "padding_mask" in kwargs:
393
+ warnings.warn(
394
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
395
+ )
396
+
397
+ bsz, q_len, _ = hidden_states.size()
398
+
399
+ query_states = self.q_proj(hidden_states)
400
+ key_states = self.k_proj(hidden_states)
401
+ value_states = self.v_proj(hidden_states)
402
+
403
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
404
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
405
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
406
+
407
+ if self.qk_layernorm:
408
+ query_states = self.q_layernorm(query_states)
409
+ key_states = self.k_layernorm(key_states)
410
+
411
+ kv_seq_len = key_states.shape[-2]
412
+ if past_key_value is not None:
413
+ if self.layer_idx is None:
414
+ raise ValueError(
415
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
416
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
417
+ "with a layer index."
418
+ )
419
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
420
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
421
+
422
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
423
+
424
+ if past_key_value is not None:
425
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
426
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
427
+
428
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
429
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
430
+
431
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
432
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
433
+ raise ValueError(
434
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
435
+ f" {attn_weights.size()}"
436
+ )
437
+
438
+ if attention_mask is not None:
439
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
440
+ raise ValueError(
441
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
442
+ )
443
+ attn_weights = attn_weights + attention_mask
444
+
445
+ # upcast attention to fp32
446
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
447
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
448
+ attn_output = torch.matmul(attn_weights, value_states)
449
+
450
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
451
+ raise ValueError(
452
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
453
+ f" {attn_output.size()}"
454
+ )
455
+
456
+ attn_output = attn_output.transpose(1, 2).contiguous()
457
+
458
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
459
+
460
+
461
+ attn_output = self.o_proj(attn_output)
462
+
463
+ if not output_attentions:
464
+ attn_weights = None
465
+
466
+ return attn_output, attn_weights, past_key_value
467
+
468
+
469
+ class MiniCPMFlashAttention2(MiniCPMAttention):
470
+ """
471
+ MiniCPM flash attention module. This module inherits from `MiniCPMAttention` as the weights of the module stays
472
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
473
+ flash attention and deal with padding tokens in case the input contains any of them.
474
+ """
475
+
476
+ def __init__(self, *args, **kwargs):
477
+ super().__init__(*args, **kwargs)
478
+
479
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
480
+ # 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.
481
+ # 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).
482
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
483
+
484
+ def forward(
485
+ self,
486
+ hidden_states: torch.Tensor,
487
+ attention_mask: Optional[torch.LongTensor] = None,
488
+ position_ids: Optional[torch.LongTensor] = None,
489
+ past_key_value: Optional[Cache] = None,
490
+ output_attentions: bool = False,
491
+ use_cache: bool = False,
492
+ **kwargs,
493
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
494
+ # MiniCPMFlashAttention2 attention does not support output_attentions
495
+ if "padding_mask" in kwargs:
496
+ warnings.warn(
497
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
498
+ )
499
+
500
+ # overwrite attention_mask with padding_mask
501
+ attention_mask = kwargs.pop("padding_mask")
502
+
503
+ output_attentions = False
504
+
505
+ bsz, q_len, _ = hidden_states.size()
506
+
507
+ query_states = self.q_proj(hidden_states)
508
+ key_states = self.k_proj(hidden_states)
509
+ value_states = self.v_proj(hidden_states)
510
+
511
+ # Flash attention requires the input to have the shape
512
+ # batch_size x seq_length x head_dim x hidden_dim
513
+ # therefore we just need to keep the original shape
514
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
515
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
516
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
517
+
518
+ if self.qk_layernorm:
519
+ query_states = self.q_layernorm(query_states)
520
+ key_states = self.k_layernorm(key_states)
521
+
522
+ kv_seq_len = key_states.shape[-2]
523
+ if past_key_value is not None:
524
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
525
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
526
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
527
+
528
+ if past_key_value is not None:
529
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
530
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
531
+
532
+ # 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
533
+ # to be able to avoid many of these transpose/reshape/view.
534
+ query_states = query_states.transpose(1, 2)
535
+ key_states = key_states.transpose(1, 2)
536
+ value_states = value_states.transpose(1, 2)
537
+
538
+ dropout_rate = self.attention_dropout if self.training else 0.0
539
+
540
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
541
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
542
+ # cast them back in the correct dtype just to be sure everything works as expected.
543
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
544
+ # in fp32. (MiniCPMRMSNorm handles it correctly)
545
+
546
+ input_dtype = query_states.dtype
547
+ if input_dtype == torch.float32:
548
+ # Handle the case where the model is quantized
549
+ if hasattr(self.config, "_pre_quantization_dtype"):
550
+ target_dtype = self.config._pre_quantization_dtype
551
+ else:
552
+ target_dtype = self.q_proj.weight.dtype
553
+
554
+ logger.warning_once(
555
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
556
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
557
+ f" {target_dtype}."
558
+ )
559
+
560
+ query_states = query_states.to(target_dtype)
561
+ key_states = key_states.to(target_dtype)
562
+ value_states = value_states.to(target_dtype)
563
+
564
+ attn_output = self._flash_attention_forward(
565
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate,
566
+ softmax_scale = math.sqrt(self.config.dim_model_base_attn) / self.head_dim,
567
+
568
+ )
569
+
570
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
571
+ attn_output = self.o_proj(attn_output)
572
+
573
+ if not output_attentions:
574
+ attn_weights = None
575
+
576
+ return attn_output, attn_weights, past_key_value
577
+
578
+ def _flash_attention_forward(
579
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
580
+ ):
581
+ """
582
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
583
+ first unpad the input, then computes the attention scores and pad the final attention scores.
584
+
585
+ Args:
586
+ query_states (`torch.Tensor`):
587
+ Input query states to be passed to Flash Attention API
588
+ key_states (`torch.Tensor`):
589
+ Input key states to be passed to Flash Attention API
590
+ value_states (`torch.Tensor`):
591
+ Input value states to be passed to Flash Attention API
592
+ attention_mask (`torch.Tensor`):
593
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
594
+ position of padding tokens and 1 for the position of non-padding tokens.
595
+ dropout (`int`, *optional*):
596
+ Attention dropout
597
+ softmax_scale (`float`, *optional*):
598
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
599
+ """
600
+ if not self._flash_attn_uses_top_left_mask:
601
+ causal = self.is_causal
602
+ else:
603
+ # 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__.
604
+ causal = self.is_causal and query_length != 1
605
+ # Contains at least one padding token in the sequence
606
+ if attention_mask is not None:
607
+ batch_size = query_states.shape[0]
608
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
609
+ query_states, key_states, value_states, attention_mask, query_length
610
+ )
611
+
612
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
613
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
614
+ attn_output_unpad = flash_attn_varlen_func(
615
+ query_states,
616
+ key_states,
617
+ value_states,
618
+ cu_seqlens_q=cu_seqlens_q,
619
+ cu_seqlens_k=cu_seqlens_k,
620
+ max_seqlen_q=max_seqlen_in_batch_q,
621
+ max_seqlen_k=max_seqlen_in_batch_k,
622
+ dropout_p=dropout,
623
+ softmax_scale=softmax_scale,
624
+ causal=causal,
625
+ )
626
+
627
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
628
+ else:
629
+ attn_output = flash_attn_func(
630
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
631
+ )
632
+
633
+ return attn_output
634
+
635
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
636
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
637
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
638
+
639
+ key_layer = index_first_axis(
640
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
641
+ )
642
+ value_layer = index_first_axis(
643
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
644
+ )
645
+ if query_length == kv_seq_len:
646
+ query_layer = index_first_axis(
647
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
648
+ )
649
+ cu_seqlens_q = cu_seqlens_k
650
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
651
+ indices_q = indices_k
652
+ elif query_length == 1:
653
+ max_seqlen_in_batch_q = 1
654
+ cu_seqlens_q = torch.arange(
655
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
656
+ ) # There is a memcpy here, that is very bad.
657
+ indices_q = cu_seqlens_q[:-1]
658
+ query_layer = query_layer.squeeze(1)
659
+ else:
660
+ # The -q_len: slice assumes left padding.
661
+ attention_mask = attention_mask[:, -query_length:]
662
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
663
+
664
+ return (
665
+ query_layer,
666
+ key_layer,
667
+ value_layer,
668
+ indices_q,
669
+ (cu_seqlens_q, cu_seqlens_k),
670
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
671
+ )
672
+
673
+
674
+ class MiniCPMSdpaAttention(MiniCPMAttention):
675
+ """
676
+ MiniCPM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
677
+ `MiniCPMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
678
+ SDPA API.
679
+ """
680
+
681
+ # Adapted from MiniCPMAttention.forward
682
+ def forward(
683
+ self,
684
+ hidden_states: torch.Tensor,
685
+ attention_mask: Optional[torch.Tensor] = None,
686
+ position_ids: Optional[torch.LongTensor] = None,
687
+ past_key_value: Optional[Cache] = None,
688
+ output_attentions: bool = False,
689
+ use_cache: bool = False,
690
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
691
+ if output_attentions:
692
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
693
+ logger.warning_once(
694
+ "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, "
695
+ '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.'
696
+ )
697
+ return super().forward(
698
+ hidden_states=hidden_states,
699
+ attention_mask=attention_mask,
700
+ position_ids=position_ids,
701
+ past_key_value=past_key_value,
702
+ output_attentions=output_attentions,
703
+ use_cache=use_cache,
704
+ )
705
+
706
+ bsz, q_len, _ = hidden_states.size()
707
+
708
+ query_states = self.q_proj(hidden_states)
709
+ key_states = self.k_proj(hidden_states)
710
+ value_states = self.v_proj(hidden_states)
711
+
712
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
713
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
714
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
715
+
716
+ kv_seq_len = key_states.shape[-2]
717
+ if past_key_value is not None:
718
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
719
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
720
+
721
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
722
+
723
+ if past_key_value is not None:
724
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
725
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
726
+
727
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
728
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
729
+
730
+ if attention_mask is not None:
731
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
732
+ raise ValueError(
733
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
734
+ )
735
+
736
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
737
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
738
+ if query_states.device.type == "cuda" and attention_mask is not None:
739
+ query_states = query_states.contiguous()
740
+ key_states = key_states.contiguous()
741
+ value_states = value_states.contiguous()
742
+
743
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
744
+ query_states,
745
+ key_states,
746
+ value_states,
747
+ attn_mask=attention_mask,
748
+ dropout_p=self.attention_dropout if self.training else 0.0,
749
+ # 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.
750
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
751
+ )
752
+
753
+ attn_output = attn_output.transpose(1, 2).contiguous()
754
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
755
+
756
+ attn_output = self.o_proj(attn_output)
757
+
758
+ return attn_output, None, past_key_value
759
+
760
+
761
+ MINICPM_ATTENTION_CLASSES = {
762
+ "eager": MiniCPMAttention,
763
+ "flash_attention_2": MiniCPMFlashAttention2,
764
+ "sdpa": MiniCPMSdpaAttention,
765
+ }
766
+
767
+
768
+ class MiniCPMDecoderLayer(nn.Module):
769
+ def __init__(self, config: MiniCPMConfig, layer_idx: int):
770
+ super().__init__()
771
+ self.hidden_size = config.hidden_size
772
+ self.self_attn = MINICPM_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
773
+ self.config = config
774
+ self.mlp = MiniCPMMLP(config)
775
+
776
+ if config.rms_type == "gemma":
777
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=1.0)
778
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=1.0)
779
+ elif config.rms_type == "llama":
780
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=0.0)
781
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=0.0)
782
+
783
+ # self.scale_depth = config.scale_depth
784
+ self.num_hidden_layers = config.num_hidden_layers
785
+
786
+ def forward(
787
+ self,
788
+ hidden_states: torch.Tensor,
789
+ attention_mask: Optional[torch.Tensor] = None,
790
+ position_ids: Optional[torch.LongTensor] = None,
791
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
792
+ output_attentions: Optional[bool] = False,
793
+ use_cache: Optional[bool] = False,
794
+ **kwargs,
795
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
796
+ """
797
+ Args:
798
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
799
+ attention_mask (`torch.FloatTensor`, *optional*):
800
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
801
+ query_sequence_length, key_sequence_length)` if default attention is used.
802
+ output_attentions (`bool`, *optional*):
803
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
804
+ returned tensors for more detail.
805
+ use_cache (`bool`, *optional*):
806
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
807
+ (see `past_key_values`).
808
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
809
+ """
810
+ if "padding_mask" in kwargs:
811
+ warnings.warn(
812
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
813
+ )
814
+
815
+ residual = hidden_states
816
+ hidden_states = self.input_layernorm(hidden_states) * self.config.ln_scale
817
+ # Self Attention
818
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
819
+ hidden_states=hidden_states,
820
+ attention_mask=attention_mask,
821
+ position_ids=position_ids,
822
+ past_key_value=past_key_value,
823
+ output_attentions=output_attentions,
824
+ use_cache=use_cache,
825
+ **kwargs,
826
+ )
827
+
828
+ # shrink = self.config.hidden_states_shrink
829
+ # hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
830
+ shrink = self.config.hidden_states_shrink
831
+ if 0 <= shrink < 1:
832
+ # hidden_states = hidden_states * shrink + hidden_states.detach() * (1 - shrink)
833
+ hidden_states = hidden_states * shrink
834
+ hidden_states = residual + hidden_states
835
+
836
+ # Fully Connected
837
+ residual = hidden_states
838
+ hidden_states = self.post_attention_layernorm(hidden_states) * self.config.ln_scale
839
+
840
+ hidden_states = self.mlp(hidden_states)
841
+ # hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
842
+ if 0 <= shrink < 1:
843
+ # hidden_states = hidden_states * shrink + hidden_states.detach() * (1 - shrink)
844
+ hidden_states = hidden_states * shrink
845
+ hidden_states = residual + hidden_states
846
+
847
+ outputs = (hidden_states,)
848
+
849
+ if output_attentions:
850
+ outputs += (self_attn_weights,)
851
+
852
+ if use_cache:
853
+ outputs += (present_key_value,)
854
+
855
+ return outputs
856
+
857
+
858
+ MINICPM_START_DOCSTRING = r"""
859
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
860
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
861
+ etc.)
862
+
863
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
864
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
865
+ and behavior.
866
+
867
+ Parameters:
868
+ config ([`MiniCPMConfig`]):
869
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
870
+ load the weights associated with the model, only the configuration. Check out the
871
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
872
+ """
873
+
874
+
875
+ @add_start_docstrings(
876
+ "The bare MiniCPM Model outputting raw hidden-states without any specific head on top.",
877
+ MINICPM_START_DOCSTRING,
878
+ )
879
+ class MiniCPMPreTrainedModel(PreTrainedModel):
880
+ config_class = MiniCPMConfig
881
+ base_model_prefix = "model"
882
+ supports_gradient_checkpointing = True
883
+ _no_split_modules = ["MiniCPMDecoderLayer"]
884
+ _skip_keys_device_placement = "past_key_values"
885
+ _supports_flash_attn_2 = True
886
+ _supports_sdpa = True
887
+ _supports_cache_class = True
888
+
889
+ def _init_weights(self, module):
890
+ std = self.config.initializer_range
891
+ if isinstance(module, nn.Linear):
892
+ module.weight.data.normal_(mean=0.0, std=std)
893
+ if module.bias is not None:
894
+ module.bias.data.zero_()
895
+ elif isinstance(module, nn.Embedding):
896
+ module.weight.data.normal_(mean=0.0, std=std)
897
+ if module.padding_idx is not None:
898
+ module.weight.data[module.padding_idx].zero_()
899
+
900
+
901
+ MINICPM_INPUTS_DOCSTRING = r"""
902
+ Args:
903
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
904
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
905
+ it.
906
+
907
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
908
+ [`PreTrainedTokenizer.__call__`] for details.
909
+
910
+ [What are input IDs?](../glossary#input-ids)
911
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
912
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
913
+
914
+ - 1 for tokens that are **not masked**,
915
+ - 0 for tokens that are **masked**.
916
+
917
+ [What are attention masks?](../glossary#attention-mask)
918
+
919
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
920
+ [`PreTrainedTokenizer.__call__`] for details.
921
+
922
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
923
+ `past_key_values`).
924
+
925
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
926
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
927
+ information on the default strategy.
928
+
929
+ - 1 indicates the head is **not masked**,
930
+ - 0 indicates the head is **masked**.
931
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
932
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
933
+ config.n_positions - 1]`.
934
+
935
+ [What are position IDs?](../glossary#position-ids)
936
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
937
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
938
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
939
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
940
+
941
+ Two formats are allowed:
942
+ - a [`~cache_utils.Cache`] instance;
943
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
944
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
945
+ cache format.
946
+
947
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
948
+ legacy cache format will be returned.
949
+
950
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
951
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
952
+ of shape `(batch_size, sequence_length)`.
953
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
954
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
955
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
956
+ model's internal embedding lookup matrix.
957
+ use_cache (`bool`, *optional*):
958
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
959
+ `past_key_values`).
960
+ output_attentions (`bool`, *optional*):
961
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
962
+ tensors for more detail.
963
+ output_hidden_states (`bool`, *optional*):
964
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
965
+ more detail.
966
+ return_dict (`bool`, *optional*):
967
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
968
+ """
969
+
970
+
971
+ @add_start_docstrings(
972
+ "The bare MiniCPM Model outputting raw hidden-states without any specific head on top.",
973
+ MINICPM_START_DOCSTRING,
974
+ )
975
+ class MiniCPMModel(MiniCPMPreTrainedModel):
976
+ """
977
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
978
+
979
+ Args:
980
+ config: MiniCPMConfig
981
+ """
982
+
983
+ def __init__(self, config: MiniCPMConfig):
984
+ super().__init__(config)
985
+ self.config = config
986
+ self.padding_idx = config.pad_token_id
987
+ self.vocab_size = config.vocab_size
988
+
989
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
990
+
991
+ if self.config.embedding_ln:
992
+ self.embedding_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, bias=False)
993
+ elif self.config.embedding_rmsln:
994
+ if config.rms_type == "gemma":
995
+ self.embedding_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps, casting_mode="gemma",offset=1.0)
996
+ elif config.rms_type == "llama":
997
+ self.embedding_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps, casting_mode="gemma",offset=0.0)
998
+
999
+
1000
+ self.layers = nn.ModuleList(
1001
+ [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1002
+ )
1003
+ self._use_sdpa = config._attn_implementation == "sdpa"
1004
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1005
+ if config.rms_type == "gemma":
1006
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps,offset=1.0)
1007
+ elif config.rms_type == "llama":
1008
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps,offset=0.0)
1009
+
1010
+ self.gradient_checkpointing = False
1011
+ # Initialize weights and apply final processing
1012
+ self.post_init()
1013
+
1014
+ def get_input_embeddings(self):
1015
+ return self.embed_tokens
1016
+
1017
+ def set_input_embeddings(self, value):
1018
+ self.embed_tokens = value
1019
+
1020
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1021
+ def forward(
1022
+ self,
1023
+ input_ids: torch.LongTensor = None,
1024
+ attention_mask: Optional[torch.Tensor] = None,
1025
+ position_ids: Optional[torch.LongTensor] = None,
1026
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1027
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1028
+ use_cache: Optional[bool] = None,
1029
+ output_attentions: Optional[bool] = None,
1030
+ output_hidden_states: Optional[bool] = None,
1031
+ return_dict: Optional[bool] = None,
1032
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1033
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1034
+ output_hidden_states = (
1035
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1036
+ )
1037
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1038
+
1039
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1040
+
1041
+ # retrieve input_ids and inputs_embeds
1042
+ if input_ids is not None and inputs_embeds is not None:
1043
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1044
+ elif input_ids is not None:
1045
+ batch_size, seq_length = input_ids.shape[:2]
1046
+ elif inputs_embeds is not None:
1047
+ batch_size, seq_length = inputs_embeds.shape[:2]
1048
+ else:
1049
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1050
+
1051
+ if self.gradient_checkpointing and self.training:
1052
+ if use_cache:
1053
+ logger.warning_once(
1054
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1055
+ )
1056
+ use_cache = False
1057
+
1058
+ past_key_values_length = 0
1059
+ if use_cache:
1060
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1061
+ if use_legacy_cache:
1062
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1063
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1064
+
1065
+ if position_ids is None:
1066
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1067
+ position_ids = torch.arange(
1068
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1069
+ )
1070
+ position_ids = position_ids.unsqueeze(0)
1071
+
1072
+ if inputs_embeds is None:
1073
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1074
+
1075
+ if self.config.embedding_ln:
1076
+ inputs_embeds = self.embedding_layernorm(inputs_embeds)
1077
+ elif self.config.embedding_rmsln:
1078
+ inputs_embeds = self.embedding_layernorm(inputs_embeds) * self.config.ln_scale
1079
+
1080
+ if self._use_flash_attention_2:
1081
+ # 2d mask is passed through the layers
1082
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1083
+ elif self._use_sdpa and not output_attentions:
1084
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1085
+ # the manual implementation that requires a 4D causal mask in all cases.
1086
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1087
+ attention_mask,
1088
+ (batch_size, seq_length),
1089
+ inputs_embeds,
1090
+ past_key_values_length,
1091
+ )
1092
+ else:
1093
+ # 4d mask is passed through the layers
1094
+ attention_mask = _prepare_4d_causal_attention_mask(
1095
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1096
+ )
1097
+
1098
+ # embed positions
1099
+ hidden_states = inputs_embeds
1100
+
1101
+ # decoder layers
1102
+ all_hidden_states = () if output_hidden_states else None
1103
+ all_self_attns = () if output_attentions else None
1104
+ next_decoder_cache = None
1105
+
1106
+ for decoder_layer in self.layers:
1107
+ if output_hidden_states:
1108
+ all_hidden_states += (hidden_states,)
1109
+
1110
+ if self.gradient_checkpointing and self.training:
1111
+ layer_outputs = self._gradient_checkpointing_func(
1112
+ decoder_layer.__call__,
1113
+ hidden_states,
1114
+ attention_mask,
1115
+ position_ids,
1116
+ past_key_values,
1117
+ output_attentions,
1118
+ use_cache,
1119
+ )
1120
+ else:
1121
+ layer_outputs = decoder_layer(
1122
+ hidden_states,
1123
+ attention_mask=attention_mask,
1124
+ position_ids=position_ids,
1125
+ past_key_value=past_key_values,
1126
+ output_attentions=output_attentions,
1127
+ use_cache=use_cache,
1128
+ )
1129
+
1130
+ hidden_states = layer_outputs[0]
1131
+
1132
+ if use_cache:
1133
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1134
+
1135
+ if output_attentions:
1136
+ all_self_attns += (layer_outputs[1],)
1137
+
1138
+ hidden_states = self.norm(hidden_states) * self.config.ln_scale
1139
+
1140
+ # add hidden states from the last decoder layer
1141
+ if output_hidden_states:
1142
+ all_hidden_states += (hidden_states,)
1143
+
1144
+ next_cache = None
1145
+ if use_cache:
1146
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1147
+ if not return_dict:
1148
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1149
+ return BaseModelOutputWithPast(
1150
+ last_hidden_state=hidden_states,
1151
+ past_key_values=next_cache,
1152
+ hidden_states=all_hidden_states,
1153
+ attentions=all_self_attns,
1154
+ )
1155
+
1156
+
1157
+ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
1158
+ _tied_weights_keys = ["lm_head.weight"]
1159
+
1160
+ def __init__(self, config):
1161
+ super().__init__(config)
1162
+ self.model = MiniCPMModel(config)
1163
+ self.vocab_size = config.vocab_size
1164
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1165
+
1166
+ # Initialize weights and apply final processing
1167
+ self.post_init()
1168
+
1169
+ def get_input_embeddings(self):
1170
+ return self.model.embed_tokens
1171
+
1172
+ def set_input_embeddings(self, value):
1173
+ self.model.embed_tokens = value
1174
+
1175
+ def get_output_embeddings(self):
1176
+ return self.lm_head
1177
+
1178
+ def set_output_embeddings(self, new_embeddings):
1179
+ self.lm_head = new_embeddings
1180
+
1181
+ def set_decoder(self, decoder):
1182
+ self.model = decoder
1183
+
1184
+ def get_decoder(self):
1185
+ return self.model
1186
+
1187
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1188
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1189
+ def forward(
1190
+ self,
1191
+ input_ids: torch.LongTensor = None,
1192
+ attention_mask: Optional[torch.Tensor] = None,
1193
+ position_ids: Optional[torch.LongTensor] = None,
1194
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1195
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1196
+ labels: Optional[torch.LongTensor] = None,
1197
+ use_cache: Optional[bool] = None,
1198
+ output_attentions: Optional[bool] = None,
1199
+ output_hidden_states: Optional[bool] = None,
1200
+ return_dict: Optional[bool] = None,
1201
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1202
+ r"""
1203
+ Args:
1204
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1205
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1206
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1207
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1208
+
1209
+ Returns:
1210
+
1211
+ Example:
1212
+
1213
+ ```python
1214
+ >>> from transformers import AutoTokenizer, MiniCPMForCausalLM
1215
+
1216
+ >>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1217
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1218
+
1219
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1220
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1221
+
1222
+ >>> # Generate
1223
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1224
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1225
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1226
+ ```"""
1227
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1228
+ output_hidden_states = (
1229
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1230
+ )
1231
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1232
+
1233
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1234
+ outputs = self.model(
1235
+ input_ids=input_ids,
1236
+ attention_mask=attention_mask,
1237
+ position_ids=position_ids,
1238
+ past_key_values=past_key_values,
1239
+ inputs_embeds=inputs_embeds,
1240
+ use_cache=use_cache,
1241
+ output_attentions=output_attentions,
1242
+ output_hidden_states=output_hidden_states,
1243
+ return_dict=return_dict,
1244
+ )
1245
+
1246
+ hidden_states = outputs[0]
1247
+ try:
1248
+ logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base_logits))
1249
+ except:
1250
+ logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))
1251
+ logits = logits.float()
1252
+
1253
+ loss = None
1254
+ if labels is not None:
1255
+ # Shift so that tokens < n predict n
1256
+ shift_logits = logits[..., :-1, :].contiguous()
1257
+ shift_labels = labels[..., 1:].contiguous()
1258
+ # Flatten the tokens
1259
+ loss_fct = CrossEntropyLoss()
1260
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1261
+ shift_labels = shift_labels.view(-1)
1262
+ # Enable model parallelism
1263
+ shift_labels = shift_labels.to(shift_logits.device)
1264
+ loss = loss_fct(shift_logits, shift_labels)
1265
+
1266
+ if not return_dict:
1267
+ output = (logits,) + outputs[1:]
1268
+ return (loss,) + output if loss is not None else output
1269
+
1270
+ return CausalLMOutputWithPast(
1271
+ loss=loss,
1272
+ logits=logits,
1273
+ past_key_values=outputs.past_key_values,
1274
+ hidden_states=outputs.hidden_states,
1275
+ attentions=outputs.attentions,
1276
+ )
1277
+
1278
+ def prepare_inputs_for_generation(
1279
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1280
+ ):
1281
+ if past_key_values is not None:
1282
+ if isinstance(past_key_values, Cache):
1283
+ cache_length = past_key_values.get_seq_length()
1284
+ past_length = past_key_values.seen_tokens
1285
+ max_cache_length = past_key_values.get_max_length()
1286
+ else:
1287
+ cache_length = past_length = past_key_values[0][0].shape[2]
1288
+ max_cache_length = None
1289
+
1290
+ # Keep only the unprocessed tokens:
1291
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1292
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1293
+ # input)
1294
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1295
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1296
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1297
+ # input_ids based on the past_length.
1298
+ elif past_length < input_ids.shape[1]:
1299
+ input_ids = input_ids[:, past_length:]
1300
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1301
+
1302
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1303
+ if (
1304
+ max_cache_length is not None
1305
+ and attention_mask is not None
1306
+ and cache_length + input_ids.shape[1] > max_cache_length
1307
+ ):
1308
+ attention_mask = attention_mask[:, -max_cache_length:]
1309
+
1310
+ position_ids = kwargs.get("position_ids", None)
1311
+ if attention_mask is not None and position_ids is None:
1312
+ # create position_ids on the fly for batch generation
1313
+ position_ids = attention_mask.long().cumsum(-1) - 1
1314
+ position_ids.masked_fill_(attention_mask == 0, 1)
1315
+ if past_key_values:
1316
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1317
+
1318
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1319
+ if inputs_embeds is not None and past_key_values is None:
1320
+ model_inputs = {"inputs_embeds": inputs_embeds}
1321
+ else:
1322
+ model_inputs = {"input_ids": input_ids}
1323
+
1324
+ model_inputs.update(
1325
+ {
1326
+ "position_ids": position_ids,
1327
+ "past_key_values": past_key_values,
1328
+ "use_cache": kwargs.get("use_cache"),
1329
+ "attention_mask": attention_mask,
1330
+ }
1331
+ )
1332
+ return model_inputs
1333
+
1334
+ @staticmethod
1335
+ def _reorder_cache(past_key_values, beam_idx):
1336
+ reordered_past = ()
1337
+ for layer_past in past_key_values:
1338
+ reordered_past += (
1339
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1340
+ )
1341
+ return reordered_past
1342
+
1343
+ @torch.inference_mode()
1344
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user",
1345
+ max_length: int = 4096, num_beams=1, do_sample=True, top_p=0.8, temperature=0.3, logits_processor=None,
1346
+ **kwargs):
1347
+ if history is None:
1348
+ history = []
1349
+ if logits_processor:
1350
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1351
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1352
+ else:
1353
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1354
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1355
+
1356
+ history.append({"role": role, "content": query})
1357
+ history_str = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=False)
1358
+ inputs = tokenizer(history_str, return_tensors='pt').to(self.device)
1359
+ outputs = self.generate(**inputs, **gen_kwargs)
1360
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1361
+ response = tokenizer.decode(outputs)
1362
+ pattern = re.compile(r".*?(?=<AI>|<用户>)", re.DOTALL)
1363
+ matches = pattern.findall(response)
1364
+ if len(matches) > 0:
1365
+ response = matches[0]
1366
+ history.append({"role": "assistant", "content": response})
1367
+ return response, history
1368
+
1369
+
1370
+ @add_start_docstrings(
1371
+ """
1372
+ The MiniCPM Model transformer with a sequence classification head on top (linear layer).
1373
+
1374
+ [`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1375
+ (e.g. GPT-2) do.
1376
+
1377
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1378
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1379
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1380
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1381
+ each row of the batch).
1382
+ """,
1383
+ MINICPM_START_DOCSTRING,
1384
+ )
1385
+ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
1386
+ def __init__(self, config):
1387
+ super().__init__(config)
1388
+ self.num_labels = config.num_labels
1389
+ self.model = MiniCPMModel(config)
1390
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1391
+
1392
+ # Initialize weights and apply final processing
1393
+ self.post_init()
1394
+
1395
+ def get_input_embeddings(self):
1396
+ return self.model.embed_tokens
1397
+
1398
+ def set_input_embeddings(self, value):
1399
+ self.model.embed_tokens = value
1400
+
1401
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1402
+ def forward(
1403
+ self,
1404
+ input_ids: torch.LongTensor = None,
1405
+ attention_mask: Optional[torch.Tensor] = None,
1406
+ position_ids: Optional[torch.LongTensor] = None,
1407
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1408
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1409
+ labels: Optional[torch.LongTensor] = None,
1410
+ use_cache: Optional[bool] = None,
1411
+ output_attentions: Optional[bool] = None,
1412
+ output_hidden_states: Optional[bool] = None,
1413
+ return_dict: Optional[bool] = None,
1414
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1415
+ r"""
1416
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1417
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1418
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1419
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1420
+ """
1421
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1422
+
1423
+ transformer_outputs = self.model(
1424
+ input_ids,
1425
+ attention_mask=attention_mask,
1426
+ position_ids=position_ids,
1427
+ past_key_values=past_key_values,
1428
+ inputs_embeds=inputs_embeds,
1429
+ use_cache=use_cache,
1430
+ output_attentions=output_attentions,
1431
+ output_hidden_states=output_hidden_states,
1432
+ return_dict=return_dict,
1433
+ )
1434
+ hidden_states = transformer_outputs[0]
1435
+ logits = self.score(hidden_states)
1436
+
1437
+ if input_ids is not None:
1438
+ batch_size = input_ids.shape[0]
1439
+ else:
1440
+ batch_size = inputs_embeds.shape[0]
1441
+
1442
+ if self.config.pad_token_id is None and batch_size != 1:
1443
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1444
+ if self.config.pad_token_id is None:
1445
+ sequence_lengths = -1
1446
+ else:
1447
+ if input_ids is not None:
1448
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1449
+ logits.device
1450
+ )
1451
+ else:
1452
+ sequence_lengths = -1
1453
+
1454
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1455
+
1456
+ loss = None
1457
+ if labels is not None:
1458
+ labels = labels.to(logits.device)
1459
+ if self.config.problem_type is None:
1460
+ if self.num_labels == 1:
1461
+ self.config.problem_type = "regression"
1462
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1463
+ self.config.problem_type = "single_label_classification"
1464
+ else:
1465
+ self.config.problem_type = "multi_label_classification"
1466
+
1467
+ if self.config.problem_type == "regression":
1468
+ loss_fct = MSELoss()
1469
+ if self.num_labels == 1:
1470
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1471
+ else:
1472
+ loss = loss_fct(pooled_logits, labels)
1473
+ elif self.config.problem_type == "single_label_classification":
1474
+ loss_fct = CrossEntropyLoss()
1475
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1476
+ elif self.config.problem_type == "multi_label_classification":
1477
+ loss_fct = BCEWithLogitsLoss()
1478
+ loss = loss_fct(pooled_logits, labels)
1479
+ if not return_dict:
1480
+ output = (pooled_logits,) + transformer_outputs[1:]
1481
+ return ((loss,) + output) if loss is not None else output
1482
+
1483
+ return SequenceClassifierOutputWithPast(
1484
+ loss=loss,
1485
+ logits=pooled_logits,
1486
+ past_key_values=transformer_outputs.past_key_values,
1487
+ hidden_states=transformer_outputs.hidden_states,
1488
+ attentions=transformer_outputs.attentions,
1489
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<pad>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "102": {
31
+ "content": "<pad>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ }
38
+ },
39
+ "bos_token": "<s>",
40
+ "chat_template": "{% for message in messages %}{% if message['role'] == 'user' %}{{'<用户>' + message['content'].strip() + '<AI>'}}{% else %}{{message['content'].strip()}}{% endif %}{% endfor %}",
41
+ "clean_up_tokenization_spaces": false,
42
+ "eos_token": "</s>",
43
+ "legacy": true,
44
+ "model_max_length": 1000000000000000019884624838656,
45
+ "pad_token": "<pad>",
46
+ "padding_side": "right",
47
+ "sp_model_kwargs": {},
48
+ "spaces_between_special_tokens": false,
49
+ "tokenizer_class": "LlamaTokenizer",
50
+ "unk_token": "<unk>",
51
+ "use_default_system_prompt": false
52
+ }
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff