hyx21 commited on
Commit
c93ebc6
·
verified ·
1 Parent(s): 3bd9cc4

Upload 10 files

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