sudongpo commited on
Commit
6f355f7
·
verified ·
1 Parent(s): d50c6fc

Upload folder using huggingface_hub

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