RanchiZhao commited on
Commit
f6af4a8
1 Parent(s): d4caee6

Upload 10 files

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