enochlev commited on
Commit
30747ee
·
verified ·
1 Parent(s): 2e36271

Add safetensors conversion with transformers>=4.38 compatibility patch

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