Kaguya-19 commited on
Commit
7243e76
1 Parent(s): 36a173e
README.md CHANGED
@@ -1,3 +1,173 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## MiniCPM-RR
2
+
3
+ **MiniCPM-RR** 是面壁智能与清华大学自然语言处理实验室(THUNLP)共同开发的中英双语言文本重排序模型,有如下特点:
4
+ - 出色的中文、英文重排序能力。
5
+ - 出色的中英跨语言重排序能力。
6
+
7
+ MiniCPM-RR 基于 [MiniCPM-2B-sft-bf16](https://huggingface.co/openbmb/MiniCPM-2B-sft-bf16) 训练,结构上采取双向注意力。采取多阶段训练方式,共使用包括开源数据、机造数据、闭源数据在内的约 600 万条训练数据。
8
+
9
+ 欢迎关注 RAG 套件系列:
10
+
11
+ - 检索模型:[MiniCPM-R](https://huggingface.co/openbmb/MiniCPM-R)
12
+ - 重排模型:[MiniCPM-RR](https://huggingface.co/openbmb/MiniCPM-RR)
13
+ - 面向 RAG 场景的 LoRA 插件:[MiniCPM3-RAG-LoRA](https://huggingface.co/openbmb/MiniCPM3-RAG-LoRA)
14
+
15
+ **MiniCPM-RR** is a bilingual & cross-lingual text re-ranking model developed by ModelBest Inc. and THUNLP, featuring:
16
+
17
+ - Exceptional Chinese and English re-ranking capabilities.
18
+ - Outstanding cross-lingual re-ranking capabilities between Chinese and English.
19
+
20
+ MiniCPM-RR is trained based on [MiniCPM-2B-sft-bf16](https://huggingface.co/openbmb/MiniCPM-2B-sft-bf16) and incorporates bidirectional attention in its architecture. The model underwent multi-stage training using approximately 6 million training examples, including open-source, synthetic, and proprietary data.
21
+
22
+ We also invite you to explore the RAG toolkit series:
23
+
24
+ - Retrieval Model: [MiniCPM-R](https://huggingface.co/openbmb/MiniCPM-R)
25
+ - Re-ranking Model: [MiniCPM-RR](https://huggingface.co/openbmb/MiniCPM-RR)
26
+ - LoRA Plugin for RAG scenarios: [MiniCPM3-RAG-LoRA](https://huggingface.co/openbmb/MiniCPM3-RAG-LoRA)
27
+
28
+ ## 模型信息 Model Information
29
+
30
+ - 模型大小:2.4B
31
+ - 最大输入token数:1024
32
+
33
+ - Model Size: 2.4B
34
+ - Max Input Tokens: 1024
35
+
36
+ ## 使用方法 Usage
37
+
38
+ ### 输入格式 Input Format
39
+
40
+ 本模型支持指令,输入格式如下:
41
+
42
+ MiniCPM-RR supports instructions in the following format:
43
+
44
+ ```
45
+ <s>Instruction: {{ instruction }} Query: {{ query }}</s>{{ document }}
46
+ ```
47
+
48
+ 例如:
49
+
50
+ For example:
51
+
52
+ ```
53
+ <s>Instruction: 为这个医学问题检索相关回答。Query: 咽喉癌的成因是什么?</s>(文档省略)
54
+ ```
55
+
56
+ ```
57
+ <s>Instruction: Given a claim about climate change, retrieve documents that support or refute the claim. Query: However the warming trend is slower than most climate models have forecast.</s>(document omitted)
58
+ ```
59
+
60
+ 也可以不提供指令,即采取如下格式:
61
+
62
+ MiniCPM-RR also works in instruction-free mode in the following format:
63
+
64
+ ```
65
+ <s>Query: {{ query }}</s>{{ document }}
66
+ ```
67
+
68
+ 我们在BEIR与C-MTEB/Retrieval上测试时使用的指令见 `instructions.json`,其他测试不使用指令。
69
+
70
+ When running evaluation on BEIR and C-MTEB/Retrieval, we use instructions in `instructions.json`. For other evaluations, we do not use instructions.
71
+
72
+ ### 环境要求 Requirements
73
+
74
+ ```
75
+ transformers==4.37.2
76
+ flash-attn>2.3.5
77
+ ```
78
+
79
+ ### 示例脚本 Demo
80
+
81
+ ```python
82
+ from transformers import AutoModel, AutoTokenizer, AutoModelForSequenceClassification
83
+ import torch
84
+ import numpy as np
85
+
86
+ model_name = "openbmb/MiniCPM-RR"
87
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
88
+ tokenizer.padding_side = "right"
89
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, trust_remote_code=True,attn_implementation="flash_attention_2", torch_dtype=torch.float16).to("cuda")
90
+ model.eval()
91
+ max_len_q, max_len_d = 512, 512
92
+
93
+ def tokenize_our(query,doc):
94
+ input_id_query = tokenizer.encode(query, add_special_tokens=False, max_length=max_len_q, truncation=True)
95
+ input_id_doc = tokenizer.encode(doc, add_special_tokens=False, max_length=max_len_d, truncation=True)
96
+ pad_input = {"input_ids": [tokenizer.bos_token_id] + input_id_query + [tokenizer.eos_token_id] + input_id_doc}
97
+ return tokenizer.pad(
98
+ pad_input,
99
+ padding="max_length",
100
+ max_length=max_len_q + max_len_d + 2,
101
+ return_tensors="pt",
102
+ )
103
+
104
+ @torch.no_grad()
105
+ def rerank(input_query, input_docs):
106
+ tokenized_inputs = [tokenize_our(input_query, input_doc).to("cuda") for input_doc in input_docs]
107
+ input_ids = {
108
+ "input_ids": [tokenized_input["input_ids"] for tokenized_input in tokenized_inputs],
109
+ "attention_mask": [tokenized_input["attention_mask"] for tokenized_input in tokenized_inputs]
110
+ }
111
+
112
+ for k in input_ids:
113
+ input_ids[k] = torch.stack(input_ids[k]).to("cuda")
114
+ outputs = model(**input_ids)
115
+ score = outputs.logits
116
+ return score.float().detach().cpu().numpy()
117
+
118
+ queries = ["中国的首都是哪里?"]
119
+ passages = [["beijing", "shanghai"]]
120
+
121
+ INSTRUCTION = "Query: "
122
+ queries = [INSTRUCTION + query for query in queries]
123
+
124
+ scores = []
125
+ for i in range(len(queries)):
126
+ print(queries[i])
127
+ scores.append(rerank(queries[i],passages[i]))
128
+
129
+ print(np.array(scores)) # [[[-4.7421875][-8.8515625]]]
130
+ ```
131
+
132
+ ## 实验结果 Evaluation Results
133
+
134
+ ### 中文���英文重排序结果 CN/EN Re-ranking Results
135
+
136
+ 中文对`bge-large-zh-v1.5`检索的top-100进行重排,英文对`bge-large-en-v1.5`检索的top-100进行重排。
137
+
138
+ We re-rank top-100 docments from `bge-large-zh-v1.5` in C-MTEB/Retrieval and from `bge-large-en-v1.5` in BEIR.
139
+
140
+
141
+ | 模型 Model | C-MTEB/Retrieval (NDCG@10) | BEIR (NDCG@10) |
142
+ |----------------------------|-------------------|---------------|
143
+ | bge-large-zh-v1.5(Retriever for Chinese) | 70.46 | - |
144
+ | bge-large-en-v1.5(Retriever for English) | - | 54.29 |
145
+ | bge-reranker-v2-m3 | 71.82 | 55.36 |
146
+ | bge-reranker-v2-minicpm-28 | 73.51 | 59.86 |
147
+ | bge-reranker-v2-gemma | 71.74 | 60.71 |
148
+ | bge-reranker-v2.5-gemma2 | - | **63.67** |
149
+ | MiniCPM-RR | **76.79** | 61.32 |
150
+
151
+ ### 中英跨语言重排序结果 CN-EN Cross-lingual Re-ranking Results
152
+
153
+ 对bge-m3(Dense)检索的top100进行重排。
154
+
155
+ We re-rank top-100 documents from `bge-m3` (Dense).
156
+
157
+ | 模型 Model | MKQA EN-CN (Recall@20) | NeuCLIR22 (NDCG@10) | NeuCLIR23 (NDCG@10) |
158
+ |------------------------------------|--------------------|--------------------|--------------------|
159
+ | bge-m3 (Dense)(Retriever) | 66.4 | 30.49 | 41.09 |
160
+ | jina-reranker-v2-base-multilingual | 69.33 | 36.66 | 50.03 |
161
+ | bge-reranker-v2-m3 | 69.75 | 40.98 | 49.67 |
162
+ | gte-multilingual-reranker-base | 68.51 | 38.74 | 45.3 |
163
+ | MiniCPM-RR | **71.73** | **43.65** | **50.59** |
164
+
165
+ ## 许可证 License
166
+
167
+ - 本仓库中代码依照 [Apache-2.0 协议](https://github.com/OpenBMB/MiniCPM/blob/main/LICENSE)开源。
168
+ - MiniCPM-RR 模型权重的使用则需要遵循 [MiniCPM 模型协议](https://github.com/OpenBMB/MiniCPM/blob/main/MiniCPM%20Model%20License.md)。
169
+ - MiniCPM-RR 模型权重对学术研究完全开放。如需将模型用于商业用途,请填写[此问卷](https://modelbest.feishu.cn/share/base/form/shrcnpV5ZT9EJ6xYjh3Kx0J6v8g)。
170
+
171
+ * The code in this repo is released under the [Apache-2.0](https://github.com/OpenBMB/MiniCPM/blob/main/LICENSE) License.
172
+ * The usage of MiniCPM-RR model weights must strictly follow [MiniCPM Model License.md](https://github.com/OpenBMB/MiniCPM/blob/main/MiniCPM%20Model%20License.md).
173
+ * The models and weights of MiniCPM-RR are completely free for academic research. After filling out a ["questionnaire"](https://modelbest.feishu.cn/share/base/form/shrcnpV5ZT9EJ6xYjh3Kx0J6v8g) for registration, MiniCPM-RR weights are also available for free commercial use.
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "openbmb/MiniCPM-RR",
3
+ "architectures": [
4
+ "MiniCPM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_minicpm.MiniCPMConfig",
8
+ "AutoModel": "modeling_minicpm.MiniCPMModel",
9
+ "AutoModelForCausalLM": "modeling_minicpm.MiniCPMForCausalLM",
10
+ "AutoModelForSeq2SeqLM": "modeling_minicpm.MiniCPMForCausalLM",
11
+ "AutoModelForSequenceClassification": "modeling_minicpm.MiniCPMForSequenceClassification"
12
+ },
13
+ "bos_token_id": 1,
14
+ "eos_token_id": 2,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 2304,
17
+ "initializer_range": 0.1,
18
+ "intermediate_size": 5760,
19
+ "is_causal": false,
20
+ "max_position_embeddings": 2048,
21
+ "num_attention_heads": 36,
22
+ "num_hidden_layers": 40,
23
+ "num_key_value_heads": 36,
24
+ "rms_norm_eps": 1e-05,
25
+ "rope_scaling": null,
26
+ "torch_dtype": "bfloat16",
27
+ "transformers_version": "4.36.0",
28
+ "use_cache": true,
29
+ "vocab_size": 122753,
30
+ "scale_emb": 12,
31
+ "dim_model_base": 256,
32
+ "scale_depth": 1.4,
33
+ "num_labels": 1
34
+ }
configuration_minicpm.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ **kwargs,
144
+ ):
145
+ self.vocab_size = vocab_size
146
+ self.max_position_embeddings = max_position_embeddings
147
+ self.hidden_size = hidden_size
148
+ self.intermediate_size = intermediate_size
149
+ self.num_hidden_layers = num_hidden_layers
150
+ self.num_attention_heads = num_attention_heads
151
+
152
+ # for backward compatibility
153
+ if num_key_value_heads is None:
154
+ num_key_value_heads = num_attention_heads
155
+
156
+ self.num_key_value_heads = num_key_value_heads
157
+ self.hidden_act = hidden_act
158
+ self.initializer_range = initializer_range
159
+ self.rms_norm_eps = rms_norm_eps
160
+ self.pretraining_tp = pretraining_tp
161
+ self.use_cache = use_cache
162
+ self.rope_theta = rope_theta
163
+ self.rope_scaling = rope_scaling
164
+ self._rope_scaling_validation()
165
+ self.attention_bias = attention_bias
166
+ self.attention_dropout = attention_dropout
167
+ self.scale_emb = scale_emb
168
+ self.dim_model_base = dim_model_base
169
+ self.scale_depth = scale_depth
170
+ self.is_causal = is_causal
171
+
172
+ super().__init__(
173
+ pad_token_id=pad_token_id,
174
+ bos_token_id=bos_token_id,
175
+ eos_token_id=eos_token_id,
176
+ tie_word_embeddings=tie_word_embeddings,
177
+ **kwargs,
178
+ )
179
+ try:
180
+ import flash_attn
181
+ self._attn_implementation = "flash_attention_2"
182
+ except:
183
+ pass
184
+
185
+ def _rope_scaling_validation(self):
186
+ """
187
+ Validate the `rope_scaling` configuration.
188
+ """
189
+ if self.rope_scaling is None:
190
+ return
191
+
192
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
193
+ raise ValueError(
194
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
195
+ f"got {self.rope_scaling}"
196
+ )
197
+ rope_scaling_type = self.rope_scaling.get("type", None)
198
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
199
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
200
+ raise ValueError(
201
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
202
+ )
203
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
204
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
instruction.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fiqa": "Instruction: Given a financial question, retrieve user replies that best answer the question. Query: ",
3
+ "dbpedia": "Instruction: Given a query, retrieve relevant entity descriptions from DBPedia. Query: ",
4
+ "CmedqaRetrieval": "Instruction: 为这个医疗问题检索相关回答。 Query: ",
5
+ "nfcorpus": "Instruction: Given a question, retrieve relevant documents that best answer the question. Query: ",
6
+ "touche2020": "Instruction: Given a question, retrieve detailed and persuasive arguments that answer the question. Query: ",
7
+ "CovidRetrieval": "Instruction: 为这个问题检索相关政策回答。 Query: ",
8
+ "scifact": "Instruction: Given a scientific claim, retrieve documents that support or refute the claim. Query: ",
9
+ "scidocs": "Instruction: Given a scientific paper title, retrieve paper abstracts that are cited by the given paper. Query: ",
10
+ "nq": "Instruction: Given a question, retrieve Wikipedia passages that answer the question. Query: ",
11
+ "T2Retrieval": "Instruction: 为这个问题检索相关段落。 Query: ",
12
+ "VideoRetrieval": "Instruction: 为这个电影标题检索相关段落。 Query: ",
13
+ "DuRetrieval": "Instruction: 为这个问题检索相关百度知道回答。 Query: ",
14
+ "MMarcoRetrieval": "Instruction: 为这个查询检索相关段落。 Query: ",
15
+ "hotpotqa": "Instruction: Given a multi-hop question, retrieve documents that can help answer the question. Query: ",
16
+ "quora": "Instruction: Given a question, retrieve questions that are semantically equivalent to the given question. Query: ",
17
+ "climate-fever": "Instruction: Given a claim about climate change, retrieve documents that support or refute the claim. Query: ",
18
+ "arguana": "Instruction: Given a claim, find documents that refute the claim. Query: ",
19
+ "fever": "Instruction: Given a claim, retrieve documents that support or refute the claim. Query: ",
20
+ "trec-covid": "Instruction: Given a query on COVID-19, retrieve documents that answer the query. Query: ",
21
+ "msmarco": "Instruction: Given a web search query, retrieve relevant passages that answer the query. Query: ",
22
+ "EcomRetrieval": "Instruction: 为这个查询检索相关商品标题。 Query: ",
23
+ "MedicalRetrieval": "Instruction: 为这个医学问题检索相关回答。 Query: "
24
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:652b0bf6777d4b03b63935abce72739d716a115c025ed15a810b8f61e077465b
3
+ size 4993234616
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2460f61d1cba7f0a980bcfb8711f24fea25f0a7a09dbbb689fb4c750dd1154f0
3
+ size 456578416
model.safetensors.index.json ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5449771008
4
+ },
5
+ "weight_map": {
6
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
7
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
88
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
89
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
90
+ "model.layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
91
+ "model.layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
92
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
93
+ "model.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
94
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
95
+ "model.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
96
+ "model.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
97
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
98
+ "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
99
+ "model.layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
100
+ "model.layers.18.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
101
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
102
+ "model.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
103
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
104
+ "model.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
105
+ "model.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
106
+ "model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
107
+ "model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
108
+ "model.layers.19.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
109
+ "model.layers.19.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
110
+ "model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
111
+ "model.layers.19.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
112
+ "model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
113
+ "model.layers.19.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
114
+ "model.layers.19.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
115
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
116
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
117
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
118
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
119
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
120
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
121
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
122
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
123
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
124
+ "model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
125
+ "model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
126
+ "model.layers.20.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
127
+ "model.layers.20.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
128
+ "model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
129
+ "model.layers.20.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
130
+ "model.layers.20.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
131
+ "model.layers.20.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
132
+ "model.layers.20.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
133
+ "model.layers.21.input_layernorm.weight": "model-00001-of-00002.safetensors",
134
+ "model.layers.21.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
135
+ "model.layers.21.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
136
+ "model.layers.21.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
137
+ "model.layers.21.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
138
+ "model.layers.21.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
139
+ "model.layers.21.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
140
+ "model.layers.21.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
141
+ "model.layers.21.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
142
+ "model.layers.22.input_layernorm.weight": "model-00001-of-00002.safetensors",
143
+ "model.layers.22.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
144
+ "model.layers.22.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
145
+ "model.layers.22.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
146
+ "model.layers.22.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.22.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.22.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.22.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.22.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.23.input_layernorm.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.23.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
153
+ "model.layers.23.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
154
+ "model.layers.23.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
155
+ "model.layers.23.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
156
+ "model.layers.23.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
157
+ "model.layers.23.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
158
+ "model.layers.23.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
159
+ "model.layers.23.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
160
+ "model.layers.24.input_layernorm.weight": "model-00001-of-00002.safetensors",
161
+ "model.layers.24.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
162
+ "model.layers.24.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
163
+ "model.layers.24.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
164
+ "model.layers.24.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
165
+ "model.layers.24.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
166
+ "model.layers.24.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
167
+ "model.layers.24.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
168
+ "model.layers.24.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
169
+ "model.layers.25.input_layernorm.weight": "model-00001-of-00002.safetensors",
170
+ "model.layers.25.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
171
+ "model.layers.25.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
172
+ "model.layers.25.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
173
+ "model.layers.25.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
174
+ "model.layers.25.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
175
+ "model.layers.25.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
176
+ "model.layers.25.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
177
+ "model.layers.25.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
178
+ "model.layers.26.input_layernorm.weight": "model-00001-of-00002.safetensors",
179
+ "model.layers.26.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
180
+ "model.layers.26.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
181
+ "model.layers.26.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
182
+ "model.layers.26.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
183
+ "model.layers.26.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
184
+ "model.layers.26.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
185
+ "model.layers.26.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
186
+ "model.layers.26.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
187
+ "model.layers.27.input_layernorm.weight": "model-00001-of-00002.safetensors",
188
+ "model.layers.27.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
189
+ "model.layers.27.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
190
+ "model.layers.27.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.27.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.27.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
193
+ "model.layers.27.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.27.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
195
+ "model.layers.27.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.28.input_layernorm.weight": "model-00001-of-00002.safetensors",
197
+ "model.layers.28.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
198
+ "model.layers.28.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
199
+ "model.layers.28.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
200
+ "model.layers.28.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
201
+ "model.layers.28.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
202
+ "model.layers.28.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
203
+ "model.layers.28.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
204
+ "model.layers.28.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
205
+ "model.layers.29.input_layernorm.weight": "model-00001-of-00002.safetensors",
206
+ "model.layers.29.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
207
+ "model.layers.29.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
208
+ "model.layers.29.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
209
+ "model.layers.29.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
210
+ "model.layers.29.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
211
+ "model.layers.29.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
212
+ "model.layers.29.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
213
+ "model.layers.29.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
214
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
215
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
216
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
217
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
218
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
219
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
220
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
221
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
222
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
223
+ "model.layers.30.input_layernorm.weight": "model-00001-of-00002.safetensors",
224
+ "model.layers.30.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
225
+ "model.layers.30.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
226
+ "model.layers.30.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
227
+ "model.layers.30.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
228
+ "model.layers.30.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
229
+ "model.layers.30.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
230
+ "model.layers.30.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
231
+ "model.layers.30.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
232
+ "model.layers.31.input_layernorm.weight": "model-00001-of-00002.safetensors",
233
+ "model.layers.31.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
234
+ "model.layers.31.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
235
+ "model.layers.31.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
236
+ "model.layers.31.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
237
+ "model.layers.31.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
238
+ "model.layers.31.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
239
+ "model.layers.31.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
240
+ "model.layers.31.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
241
+ "model.layers.32.input_layernorm.weight": "model-00001-of-00002.safetensors",
242
+ "model.layers.32.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
243
+ "model.layers.32.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
244
+ "model.layers.32.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
245
+ "model.layers.32.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
246
+ "model.layers.32.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
247
+ "model.layers.32.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
248
+ "model.layers.32.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
249
+ "model.layers.32.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
250
+ "model.layers.33.input_layernorm.weight": "model-00001-of-00002.safetensors",
251
+ "model.layers.33.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
252
+ "model.layers.33.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
253
+ "model.layers.33.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
254
+ "model.layers.33.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
255
+ "model.layers.33.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
256
+ "model.layers.33.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
257
+ "model.layers.33.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
258
+ "model.layers.33.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
259
+ "model.layers.34.input_layernorm.weight": "model-00001-of-00002.safetensors",
260
+ "model.layers.34.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
261
+ "model.layers.34.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
262
+ "model.layers.34.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
263
+ "model.layers.34.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
264
+ "model.layers.34.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
265
+ "model.layers.34.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
266
+ "model.layers.34.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
267
+ "model.layers.34.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
268
+ "model.layers.35.input_layernorm.weight": "model-00001-of-00002.safetensors",
269
+ "model.layers.35.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
270
+ "model.layers.35.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
271
+ "model.layers.35.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
272
+ "model.layers.35.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
273
+ "model.layers.35.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
274
+ "model.layers.35.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
275
+ "model.layers.35.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
276
+ "model.layers.35.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
277
+ "model.layers.36.input_layernorm.weight": "model-00002-of-00002.safetensors",
278
+ "model.layers.36.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
279
+ "model.layers.36.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
280
+ "model.layers.36.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
281
+ "model.layers.36.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
282
+ "model.layers.36.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
283
+ "model.layers.36.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
284
+ "model.layers.36.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
285
+ "model.layers.36.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
286
+ "model.layers.37.input_layernorm.weight": "model-00002-of-00002.safetensors",
287
+ "model.layers.37.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
288
+ "model.layers.37.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
289
+ "model.layers.37.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
290
+ "model.layers.37.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
291
+ "model.layers.37.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
292
+ "model.layers.37.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
293
+ "model.layers.37.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
294
+ "model.layers.37.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
295
+ "model.layers.38.input_layernorm.weight": "model-00002-of-00002.safetensors",
296
+ "model.layers.38.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
297
+ "model.layers.38.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
298
+ "model.layers.38.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
299
+ "model.layers.38.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
300
+ "model.layers.38.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
301
+ "model.layers.38.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
302
+ "model.layers.38.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
303
+ "model.layers.38.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
304
+ "model.layers.39.input_layernorm.weight": "model-00002-of-00002.safetensors",
305
+ "model.layers.39.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
306
+ "model.layers.39.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
307
+ "model.layers.39.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
308
+ "model.layers.39.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
309
+ "model.layers.39.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
310
+ "model.layers.39.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
311
+ "model.layers.39.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
312
+ "model.layers.39.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
313
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
314
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
315
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
316
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
317
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
318
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
319
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
320
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
321
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
322
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
323
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
324
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
325
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
326
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
327
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
328
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
329
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
330
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
331
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
332
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
333
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
334
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
335
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
336
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
337
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
338
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
339
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
340
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
341
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
342
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
343
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
344
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
345
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
346
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
347
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
348
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
349
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
350
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
351
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
352
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
353
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
354
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
355
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
356
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
357
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
358
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
359
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
360
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
361
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
362
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
363
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
364
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
365
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
366
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
367
+ "model.norm.weight": "model-00002-of-00002.safetensors",
368
+ "score.weight": "model-00002-of-00002.safetensors"
369
+ }
370
+ }
modeling_minicpm.py ADDED
@@ -0,0 +1,1453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch MiniCPM model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union, Dict
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.utils.import_utils import is_torch_fx_available
51
+ from .configuration_minicpm import MiniCPMConfig
52
+ import re
53
+
54
+ try:
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+ except:
58
+ pass
59
+
60
+
61
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
62
+ # It means that the function will not be traced through and simply appear as a node in the graph.
63
+ if is_torch_fx_available():
64
+ if not is_torch_greater_or_equal_than_1_13:
65
+ import torch.fx
66
+
67
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
68
+
69
+
70
+ logger = logging.get_logger(__name__)
71
+
72
+ _CONFIG_FOR_DOC = "MiniCPMConfig"
73
+
74
+
75
+ def _get_unpad_data(attention_mask):
76
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
77
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
78
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
79
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
80
+ return (
81
+ indices,
82
+ cu_seqlens,
83
+ max_seqlen_in_batch,
84
+ )
85
+
86
+
87
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
88
+ warnings.warn(
89
+ "Calling `transformers.models.minicpm.modeling_minicpm._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
90
+ )
91
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
92
+
93
+
94
+ def _make_causal_mask(
95
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
96
+ ):
97
+ warnings.warn(
98
+ "Calling `transformers.models.minicpm.modeling_minicpm._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.minicpm.modeling_minicpm.AttentionMaskConverter._make_causal_mask"
99
+ )
100
+ return AttentionMaskConverter._make_causal_mask(
101
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
102
+ )
103
+
104
+ # @torch.jit.script # type: ignore
105
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
106
+ old_dtype = hidden.dtype
107
+ variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
108
+ hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
109
+ return hidden * weight
110
+
111
+
112
+ class MiniCPMRMSNorm(nn.Module):
113
+ def __init__(self, hidden_size, eps=1e-6):
114
+ """
115
+ MiniCPMRMSNorm is equivalent to T5LayerNorm
116
+ """
117
+ super().__init__()
118
+ self.weight = nn.Parameter(torch.ones(hidden_size))
119
+ self.variance_epsilon = eps
120
+
121
+ def forward(self, hidden_states):
122
+ return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
123
+
124
+
125
+ ALL_LAYERNORM_LAYERS.append(MiniCPMRMSNorm)
126
+
127
+
128
+ class MiniCPMRotaryEmbedding(nn.Module):
129
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
130
+ super().__init__()
131
+
132
+ self.dim = dim
133
+ self.max_position_embeddings = max_position_embeddings
134
+ self.base = base
135
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
136
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
137
+
138
+ # Build here to make `torch.jit.trace` work.
139
+ self._set_cos_sin_cache(
140
+ # seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
141
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
142
+ )
143
+
144
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
145
+ self.max_seq_len_cached = seq_len
146
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
147
+ freqs = torch.outer(t, self.inv_freq)
148
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
149
+ emb = torch.cat((freqs, freqs), dim=-1)
150
+
151
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
152
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
153
+
154
+ def forward(self, x, seq_len=None):
155
+ # x: [bs, num_attention_heads, seq_len, head_size]
156
+ if seq_len > self.max_seq_len_cached:
157
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
158
+
159
+ return (
160
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
161
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
162
+ )
163
+
164
+
165
+ class MiniCPMLinearScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
166
+ """MiniCPMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
167
+
168
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
169
+ self.scaling_factor = scaling_factor
170
+ super().__init__(dim, max_position_embeddings, base, device)
171
+
172
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
173
+ self.max_seq_len_cached = seq_len
174
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
175
+ t = t / self.scaling_factor
176
+
177
+ freqs = torch.outer(t, self.inv_freq)
178
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
179
+ emb = torch.cat((freqs, freqs), dim=-1)
180
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
181
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
182
+
183
+
184
+ class MiniCPMDynamicNTKScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
185
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
186
+
187
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
188
+ self.scaling_factor = scaling_factor
189
+ super().__init__(dim, max_position_embeddings, base, device)
190
+
191
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
192
+ self.max_seq_len_cached = seq_len
193
+
194
+ if seq_len > self.max_position_embeddings:
195
+ base = self.base * (
196
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
197
+ ) ** (self.dim / (self.dim - 2))
198
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
199
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
200
+
201
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
202
+
203
+ freqs = torch.outer(t, self.inv_freq)
204
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
205
+ emb = torch.cat((freqs, freqs), dim=-1)
206
+
207
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
208
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
209
+
210
+
211
+ def rotate_half(x):
212
+ """Rotates half the hidden dims of the input."""
213
+ x1 = x[..., : x.shape[-1] // 2]
214
+ x2 = x[..., x.shape[-1] // 2 :]
215
+ return torch.cat((-x2, x1), dim=-1)
216
+
217
+
218
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
219
+ """Applies Rotary Position Embedding to the query and key tensors.
220
+
221
+ Args:
222
+ q (`torch.Tensor`): The query tensor.
223
+ k (`torch.Tensor`): The key tensor.
224
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
225
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
226
+ position_ids (`torch.Tensor`):
227
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
228
+ used to pass offsetted position ids when working with a KV-cache.
229
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
230
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
231
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
232
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
233
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
234
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
235
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
236
+ Returns:
237
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
238
+ """
239
+ # cos = cos[position_ids].unsqueeze(unsqueeze_dim)
240
+ # sin = sin[position_ids].unsqueeze(unsqueeze_dim)
241
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
242
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
243
+ orig_dtype = k.dtype
244
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
245
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
246
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
247
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
248
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
249
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
250
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
251
+
252
+ class MiniCPMMLP(nn.Module):
253
+ def __init__(self, config):
254
+ super().__init__()
255
+ self.config = config
256
+ self.hidden_size = config.hidden_size
257
+ self.intermediate_size = config.intermediate_size
258
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
259
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
260
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
261
+ self.act_fn = ACT2FN[config.hidden_act]
262
+
263
+ def forward(self, x):
264
+ if self.config.pretraining_tp > 1:
265
+ slice = self.intermediate_size // self.config.pretraining_tp
266
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
267
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
268
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
269
+
270
+ gate_proj = torch.cat(
271
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
272
+ )
273
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
274
+
275
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
276
+ down_proj = [
277
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
278
+ ]
279
+ down_proj = sum(down_proj)
280
+ else:
281
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
282
+
283
+ return down_proj
284
+
285
+
286
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
287
+ """
288
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
289
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
290
+ """
291
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
292
+ if n_rep == 1:
293
+ return hidden_states
294
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
295
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
296
+
297
+
298
+
299
+ class MiniCPMAttention(nn.Module):
300
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
301
+
302
+ def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
303
+ super().__init__()
304
+ self.config = config
305
+ self.layer_idx = layer_idx
306
+ if layer_idx is None:
307
+ logger.warning_once(
308
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
309
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
310
+ "when creating this class."
311
+ )
312
+
313
+ self.attention_dropout = config.attention_dropout
314
+ self.hidden_size = config.hidden_size
315
+ self.num_heads = config.num_attention_heads
316
+ self.head_dim = self.hidden_size // self.num_heads
317
+ self.num_key_value_heads = config.num_key_value_heads
318
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
319
+ self.max_position_embeddings = config.max_position_embeddings
320
+ self.rope_theta = config.rope_theta
321
+
322
+ self.is_causal = config.is_causal
323
+
324
+ logger.info(f"self.is_causal = {self.is_causal}")
325
+
326
+
327
+ if (self.head_dim * self.num_heads) != self.hidden_size:
328
+ raise ValueError(
329
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
330
+ f" and `num_heads`: {self.num_heads})."
331
+ )
332
+
333
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
334
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
335
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
336
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
337
+ self._init_rope()
338
+
339
+ def _init_rope(self):
340
+ if self.config.rope_scaling is None:
341
+ self.rotary_emb = MiniCPMRotaryEmbedding(
342
+ self.head_dim,
343
+ max_position_embeddings=self.max_position_embeddings,
344
+ base=self.rope_theta,
345
+ )
346
+ else:
347
+ scaling_type = self.config.rope_scaling["type"]
348
+ scaling_factor = self.config.rope_scaling["factor"]
349
+ if scaling_type == "linear":
350
+ self.rotary_emb = MiniCPMLinearScalingRotaryEmbedding(
351
+ self.head_dim,
352
+ max_position_embeddings=self.max_position_embeddings,
353
+ scaling_factor=scaling_factor,
354
+ base=self.rope_theta,
355
+ )
356
+ elif scaling_type == "dynamic":
357
+ self.rotary_emb = MiniCPMDynamicNTKScalingRotaryEmbedding(
358
+ self.head_dim,
359
+ max_position_embeddings=self.max_position_embeddings,
360
+ scaling_factor=scaling_factor,
361
+ base=self.rope_theta,
362
+ )
363
+ else:
364
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
365
+
366
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
367
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
368
+
369
+ def forward(
370
+ self,
371
+ hidden_states: torch.Tensor,
372
+ attention_mask: Optional[torch.Tensor] = None,
373
+ position_ids: Optional[torch.LongTensor] = None,
374
+ past_key_value: Optional[Cache] = None,
375
+ output_attentions: bool = False,
376
+ use_cache: bool = False,
377
+ **kwargs,
378
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
379
+ if "padding_mask" in kwargs:
380
+ warnings.warn(
381
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
382
+ )
383
+
384
+ bsz, q_len, _ = hidden_states.size()
385
+
386
+ if self.config.pretraining_tp > 1:
387
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
388
+ query_slices = self.q_proj.weight.split(
389
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
390
+ )
391
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
392
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
393
+
394
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
395
+ query_states = torch.cat(query_states, dim=-1)
396
+
397
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
398
+ key_states = torch.cat(key_states, dim=-1)
399
+
400
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
401
+ value_states = torch.cat(value_states, dim=-1)
402
+
403
+ else:
404
+ query_states = self.q_proj(hidden_states)
405
+ key_states = self.k_proj(hidden_states)
406
+ value_states = self.v_proj(hidden_states)
407
+
408
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
409
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
410
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
411
+
412
+ kv_seq_len = key_states.shape[-2]
413
+ if past_key_value is not None:
414
+ if self.layer_idx is None:
415
+ raise ValueError(
416
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
417
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
418
+ "with a layer index."
419
+ )
420
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
421
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
422
+
423
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
424
+
425
+ if past_key_value is not None:
426
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
427
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
428
+
429
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
430
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
431
+
432
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
433
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
434
+ raise ValueError(
435
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
436
+ f" {attn_weights.size()}"
437
+ )
438
+
439
+ if attention_mask is not None:
440
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
441
+ raise ValueError(
442
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
443
+ )
444
+ attn_weights = attn_weights + attention_mask
445
+
446
+ # upcast attention to fp32
447
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
448
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
449
+ attn_output = torch.matmul(attn_weights, value_states)
450
+
451
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
452
+ raise ValueError(
453
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
454
+ f" {attn_output.size()}"
455
+ )
456
+
457
+ attn_output = attn_output.transpose(1, 2).contiguous()
458
+
459
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
460
+
461
+ if self.config.pretraining_tp > 1:
462
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
463
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
464
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
465
+ else:
466
+ attn_output = self.o_proj(attn_output)
467
+
468
+ if not output_attentions:
469
+ attn_weights = None
470
+
471
+ return attn_output, attn_weights, past_key_value
472
+
473
+
474
+ class MiniCPMFlashAttention2(MiniCPMAttention):
475
+ """
476
+ MiniCPM flash attention module. This module inherits from `MiniCPMAttention` as the weights of the module stays
477
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
478
+ flash attention and deal with padding tokens in case the input contains any of them.
479
+ """
480
+
481
+ def __init__(self, *args, **kwargs):
482
+ super().__init__(*args, **kwargs)
483
+
484
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
485
+ # 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.
486
+ # 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).
487
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
488
+
489
+ def forward(
490
+ self,
491
+ hidden_states: torch.Tensor,
492
+ attention_mask: Optional[torch.LongTensor] = None,
493
+ position_ids: Optional[torch.LongTensor] = None,
494
+ past_key_value: Optional[Cache] = None,
495
+ output_attentions: bool = False,
496
+ use_cache: bool = False,
497
+ **kwargs,
498
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
499
+ # MiniCPMFlashAttention2 attention does not support output_attentions
500
+ if "padding_mask" in kwargs:
501
+ warnings.warn(
502
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
503
+ )
504
+
505
+ # overwrite attention_mask with padding_mask
506
+ attention_mask = kwargs.pop("padding_mask")
507
+
508
+ output_attentions = False
509
+
510
+ bsz, q_len, _ = hidden_states.size()
511
+
512
+ query_states = self.q_proj(hidden_states)
513
+ key_states = self.k_proj(hidden_states)
514
+ value_states = self.v_proj(hidden_states)
515
+
516
+ # Flash attention requires the input to have the shape
517
+ # batch_size x seq_length x head_dim x hidden_dim
518
+ # therefore we just need to keep the original shape
519
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
520
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
521
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
522
+
523
+ kv_seq_len = key_states.shape[-2]
524
+ if past_key_value is not None:
525
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
526
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
527
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
528
+
529
+ if past_key_value is not None:
530
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
531
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
532
+
533
+ # 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
534
+ # to be able to avoid many of these transpose/reshape/view.
535
+ query_states = query_states.transpose(1, 2)
536
+ key_states = key_states.transpose(1, 2)
537
+ value_states = value_states.transpose(1, 2)
538
+
539
+ dropout_rate = self.attention_dropout if self.training else 0.0
540
+
541
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
542
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
543
+ # cast them back in the correct dtype just to be sure everything works as expected.
544
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
545
+ # in fp32. (MiniCPMRMSNorm handles it correctly)
546
+
547
+ input_dtype = query_states.dtype
548
+ if input_dtype == torch.float32:
549
+ # Handle the case where the model is quantized
550
+ if hasattr(self.config, "_pre_quantization_dtype"):
551
+ target_dtype = self.config._pre_quantization_dtype
552
+ else:
553
+ target_dtype = self.q_proj.weight.dtype
554
+
555
+ logger.warning_once(
556
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
557
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
558
+ f" {target_dtype}."
559
+ )
560
+
561
+ query_states = query_states.to(target_dtype)
562
+ key_states = key_states.to(target_dtype)
563
+ value_states = value_states.to(target_dtype)
564
+
565
+ attn_output = self._flash_attention_forward(
566
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
567
+ )
568
+
569
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
570
+ attn_output = self.o_proj(attn_output)
571
+
572
+ if not output_attentions:
573
+ attn_weights = None
574
+
575
+ return attn_output, attn_weights, past_key_value
576
+
577
+ def _flash_attention_forward(
578
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
579
+ ):
580
+ """
581
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
582
+ first unpad the input, then computes the attention scores and pad the final attention scores.
583
+
584
+ Args:
585
+ query_states (`torch.Tensor`):
586
+ Input query states to be passed to Flash Attention API
587
+ key_states (`torch.Tensor`):
588
+ Input key states to be passed to Flash Attention API
589
+ value_states (`torch.Tensor`):
590
+ Input value states to be passed to Flash Attention API
591
+ attention_mask (`torch.Tensor`):
592
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
593
+ position of padding tokens and 1 for the position of non-padding tokens.
594
+ dropout (`int`, *optional*):
595
+ Attention dropout
596
+ softmax_scale (`float`, *optional*):
597
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
598
+ """
599
+ if not self._flash_attn_uses_top_left_mask:
600
+ causal = self.is_causal
601
+ else:
602
+ # 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__.
603
+ causal = self.is_causal and query_length != 1
604
+ # Contains at least one padding token in the sequence
605
+ if attention_mask is not None:
606
+ batch_size = query_states.shape[0]
607
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
608
+ query_states, key_states, value_states, attention_mask, query_length
609
+ )
610
+
611
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
612
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
613
+ attn_output_unpad = flash_attn_varlen_func(
614
+ query_states,
615
+ key_states,
616
+ value_states,
617
+ cu_seqlens_q=cu_seqlens_q,
618
+ cu_seqlens_k=cu_seqlens_k,
619
+ max_seqlen_q=max_seqlen_in_batch_q,
620
+ max_seqlen_k=max_seqlen_in_batch_k,
621
+ dropout_p=dropout,
622
+ softmax_scale=softmax_scale,
623
+ causal=causal,
624
+ )
625
+
626
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
627
+ else:
628
+ attn_output = flash_attn_func(
629
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
630
+ )
631
+
632
+ return attn_output
633
+
634
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
635
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
636
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
637
+
638
+ key_layer = index_first_axis(
639
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
640
+ )
641
+ value_layer = index_first_axis(
642
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
643
+ )
644
+ if query_length == kv_seq_len:
645
+ query_layer = index_first_axis(
646
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
647
+ )
648
+ cu_seqlens_q = cu_seqlens_k
649
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
650
+ indices_q = indices_k
651
+ elif query_length == 1:
652
+ max_seqlen_in_batch_q = 1
653
+ cu_seqlens_q = torch.arange(
654
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
655
+ ) # There is a memcpy here, that is very bad.
656
+ indices_q = cu_seqlens_q[:-1]
657
+ query_layer = query_layer.squeeze(1)
658
+ else:
659
+ # The -q_len: slice assumes left padding.
660
+ attention_mask = attention_mask[:, -query_length:]
661
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
662
+
663
+ return (
664
+ query_layer,
665
+ key_layer,
666
+ value_layer,
667
+ indices_q,
668
+ (cu_seqlens_q, cu_seqlens_k),
669
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
670
+ )
671
+
672
+
673
+ class MiniCPMSdpaAttention(MiniCPMAttention):
674
+ """
675
+ MiniCPM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
676
+ `MiniCPMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
677
+ SDPA API.
678
+ """
679
+
680
+ # Adapted from MiniCPMAttention.forward
681
+ def forward(
682
+ self,
683
+ hidden_states: torch.Tensor,
684
+ attention_mask: Optional[torch.Tensor] = None,
685
+ position_ids: Optional[torch.LongTensor] = None,
686
+ past_key_value: Optional[Cache] = None,
687
+ output_attentions: bool = False,
688
+ use_cache: bool = False,
689
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
690
+ if output_attentions:
691
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
692
+ logger.warning_once(
693
+ "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, "
694
+ '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.'
695
+ )
696
+ return super().forward(
697
+ hidden_states=hidden_states,
698
+ attention_mask=attention_mask,
699
+ position_ids=position_ids,
700
+ past_key_value=past_key_value,
701
+ output_attentions=output_attentions,
702
+ use_cache=use_cache,
703
+ )
704
+
705
+ bsz, q_len, _ = hidden_states.size()
706
+
707
+ query_states = self.q_proj(hidden_states)
708
+ key_states = self.k_proj(hidden_states)
709
+ value_states = self.v_proj(hidden_states)
710
+
711
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
712
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
713
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
714
+
715
+ kv_seq_len = key_states.shape[-2]
716
+ if past_key_value is not None:
717
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
718
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
719
+
720
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
721
+
722
+ if past_key_value is not None:
723
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
724
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
725
+
726
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
727
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
728
+
729
+ if attention_mask is not None:
730
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
731
+ raise ValueError(
732
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
733
+ )
734
+
735
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
736
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
737
+ if query_states.device.type == "cuda" and attention_mask is not None:
738
+ query_states = query_states.contiguous()
739
+ key_states = key_states.contiguous()
740
+ value_states = value_states.contiguous()
741
+
742
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
743
+ query_states,
744
+ key_states,
745
+ value_states,
746
+ attn_mask=attention_mask,
747
+ dropout_p=self.attention_dropout if self.training else 0.0,
748
+ # 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.
749
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
750
+ )
751
+
752
+ attn_output = attn_output.transpose(1, 2).contiguous()
753
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
754
+
755
+ attn_output = self.o_proj(attn_output)
756
+
757
+ return attn_output, None, past_key_value
758
+
759
+
760
+ MINICPM_ATTENTION_CLASSES = {
761
+ "eager": MiniCPMAttention,
762
+ "flash_attention_2": MiniCPMFlashAttention2,
763
+ "sdpa": MiniCPMSdpaAttention,
764
+ }
765
+
766
+
767
+ class MiniCPMDecoderLayer(nn.Module):
768
+ def __init__(self, config: MiniCPMConfig, layer_idx: int):
769
+ super().__init__()
770
+ self.hidden_size = config.hidden_size
771
+ self.self_attn = MINICPM_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
772
+
773
+ self.mlp = MiniCPMMLP(config)
774
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
775
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
776
+
777
+ self.scale_depth = config.scale_depth
778
+ self.num_hidden_layers = config.num_hidden_layers
779
+
780
+ def forward(
781
+ self,
782
+ hidden_states: torch.Tensor,
783
+ attention_mask: Optional[torch.Tensor] = None,
784
+ position_ids: Optional[torch.LongTensor] = None,
785
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
786
+ output_attentions: Optional[bool] = False,
787
+ use_cache: Optional[bool] = False,
788
+ **kwargs,
789
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
790
+ """
791
+ Args:
792
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
793
+ attention_mask (`torch.FloatTensor`, *optional*):
794
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
795
+ query_sequence_length, key_sequence_length)` if default attention is used.
796
+ output_attentions (`bool`, *optional*):
797
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
798
+ returned tensors for more detail.
799
+ use_cache (`bool`, *optional*):
800
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
801
+ (see `past_key_values`).
802
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
803
+ """
804
+ if "padding_mask" in kwargs:
805
+ warnings.warn(
806
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
807
+ )
808
+
809
+ residual = hidden_states
810
+ hidden_states = self.input_layernorm(hidden_states)
811
+ # Self Attention
812
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
813
+ hidden_states=hidden_states,
814
+ attention_mask=attention_mask,
815
+ position_ids=position_ids,
816
+ past_key_value=past_key_value,
817
+ output_attentions=output_attentions,
818
+ use_cache=use_cache,
819
+ **kwargs,
820
+ )
821
+
822
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
823
+
824
+ # Fully Connected
825
+ residual = hidden_states
826
+ hidden_states = self.post_attention_layernorm(hidden_states)
827
+
828
+ hidden_states = self.mlp(hidden_states)
829
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
830
+
831
+ outputs = (hidden_states,)
832
+
833
+ if output_attentions:
834
+ outputs += (self_attn_weights,)
835
+
836
+ if use_cache:
837
+ outputs += (present_key_value,)
838
+
839
+ return outputs
840
+
841
+
842
+ MINICPM_START_DOCSTRING = r"""
843
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
844
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
845
+ etc.)
846
+
847
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
848
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
849
+ and behavior.
850
+
851
+ Parameters:
852
+ config ([`MiniCPMConfig`]):
853
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
854
+ load the weights associated with the model, only the configuration. Check out the
855
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
856
+ """
857
+
858
+
859
+ @add_start_docstrings(
860
+ "The bare MiniCPM Model outputting raw hidden-states without any specific head on top.",
861
+ MINICPM_START_DOCSTRING,
862
+ )
863
+ class MiniCPMPreTrainedModel(PreTrainedModel):
864
+ config_class = MiniCPMConfig
865
+ base_model_prefix = "model"
866
+ supports_gradient_checkpointing = True
867
+ _no_split_modules = ["MiniCPMDecoderLayer"]
868
+ _skip_keys_device_placement = "past_key_values"
869
+ _supports_flash_attn_2 = True
870
+ _supports_sdpa = True
871
+ _supports_cache_class = True
872
+
873
+ def _init_weights(self, module):
874
+ std = self.config.initializer_range
875
+ if isinstance(module, nn.Linear):
876
+ module.weight.data.normal_(mean=0.0, std=std)
877
+ if module.bias is not None:
878
+ module.bias.data.zero_()
879
+ elif isinstance(module, nn.Embedding):
880
+ module.weight.data.normal_(mean=0.0, std=std)
881
+ if module.padding_idx is not None:
882
+ module.weight.data[module.padding_idx].zero_()
883
+
884
+
885
+ MINICPM_INPUTS_DOCSTRING = r"""
886
+ Args:
887
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
888
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
889
+ it.
890
+
891
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
892
+ [`PreTrainedTokenizer.__call__`] for details.
893
+
894
+ [What are input IDs?](../glossary#input-ids)
895
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
896
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
897
+
898
+ - 1 for tokens that are **not masked**,
899
+ - 0 for tokens that are **masked**.
900
+
901
+ [What are attention masks?](../glossary#attention-mask)
902
+
903
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
904
+ [`PreTrainedTokenizer.__call__`] for details.
905
+
906
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
907
+ `past_key_values`).
908
+
909
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
910
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
911
+ information on the default strategy.
912
+
913
+ - 1 indicates the head is **not masked**,
914
+ - 0 indicates the head is **masked**.
915
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
916
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
917
+ config.n_positions - 1]`.
918
+
919
+ [What are position IDs?](../glossary#position-ids)
920
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
921
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
922
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
923
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
924
+
925
+ Two formats are allowed:
926
+ - a [`~cache_utils.Cache`] instance;
927
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
928
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
929
+ cache format.
930
+
931
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
932
+ legacy cache format will be returned.
933
+
934
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
935
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
936
+ of shape `(batch_size, sequence_length)`.
937
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
938
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
939
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
940
+ model's internal embedding lookup matrix.
941
+ use_cache (`bool`, *optional*):
942
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
943
+ `past_key_values`).
944
+ output_attentions (`bool`, *optional*):
945
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
946
+ tensors for more detail.
947
+ output_hidden_states (`bool`, *optional*):
948
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
949
+ more detail.
950
+ return_dict (`bool`, *optional*):
951
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
952
+ """
953
+
954
+
955
+ @add_start_docstrings(
956
+ "The bare MiniCPM Model outputting raw hidden-states without any specific head on top.",
957
+ MINICPM_START_DOCSTRING,
958
+ )
959
+ class MiniCPMModel(MiniCPMPreTrainedModel):
960
+ """
961
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
962
+
963
+ Args:
964
+ config: MiniCPMConfig
965
+ """
966
+
967
+ def __init__(self, config: MiniCPMConfig):
968
+ super().__init__(config)
969
+ self.padding_idx = config.pad_token_id
970
+ self.vocab_size = config.vocab_size
971
+
972
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
973
+ self.layers = nn.ModuleList(
974
+ [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
975
+ )
976
+ self._use_sdpa = config._attn_implementation == "sdpa"
977
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
978
+
979
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
980
+
981
+ self.gradient_checkpointing = False
982
+ # Initialize weights and apply final processing
983
+ self.post_init()
984
+
985
+ def get_input_embeddings(self):
986
+ return self.embed_tokens
987
+
988
+ def set_input_embeddings(self, value):
989
+ self.embed_tokens = value
990
+
991
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
992
+ def forward(
993
+ self,
994
+ input_ids: torch.LongTensor = None,
995
+ attention_mask: Optional[torch.Tensor] = None,
996
+ position_ids: Optional[torch.LongTensor] = None,
997
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
998
+ inputs_embeds: Optional[torch.FloatTensor] = None,
999
+ use_cache: Optional[bool] = None,
1000
+ output_attentions: Optional[bool] = None,
1001
+ output_hidden_states: Optional[bool] = None,
1002
+ return_dict: Optional[bool] = None,
1003
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1004
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1005
+ output_hidden_states = (
1006
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1007
+ )
1008
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1009
+
1010
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1011
+
1012
+ # retrieve input_ids and inputs_embeds
1013
+ if input_ids is not None and inputs_embeds is not None:
1014
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1015
+ elif input_ids is not None:
1016
+ batch_size, seq_length = input_ids.shape[:2]
1017
+ elif inputs_embeds is not None:
1018
+ batch_size, seq_length = inputs_embeds.shape[:2]
1019
+ else:
1020
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1021
+
1022
+ if self.gradient_checkpointing and self.training:
1023
+ if use_cache:
1024
+ logger.warning_once(
1025
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1026
+ )
1027
+ use_cache = False
1028
+
1029
+ past_key_values_length = 0
1030
+ if use_cache:
1031
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1032
+ if use_legacy_cache:
1033
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1034
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1035
+
1036
+ if position_ids is None:
1037
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1038
+ position_ids = torch.arange(
1039
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1040
+ )
1041
+ position_ids = position_ids.unsqueeze(0)
1042
+
1043
+ if inputs_embeds is None:
1044
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1045
+
1046
+ if self._use_flash_attention_2:
1047
+ # 2d mask is passed through the layers
1048
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1049
+ elif self._use_sdpa and not output_attentions:
1050
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1051
+ # the manual implementation that requires a 4D causal mask in all cases.
1052
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1053
+ attention_mask,
1054
+ (batch_size, seq_length),
1055
+ inputs_embeds,
1056
+ past_key_values_length,
1057
+ )
1058
+ else:
1059
+ # 4d mask is passed through the layers
1060
+ attention_mask = _prepare_4d_causal_attention_mask(
1061
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1062
+ )
1063
+
1064
+ # embed positions
1065
+ hidden_states = inputs_embeds
1066
+
1067
+ # decoder layers
1068
+ all_hidden_states = () if output_hidden_states else None
1069
+ all_self_attns = () if output_attentions else None
1070
+ next_decoder_cache = None
1071
+
1072
+ for decoder_layer in self.layers:
1073
+ if output_hidden_states:
1074
+ all_hidden_states += (hidden_states,)
1075
+
1076
+ if self.gradient_checkpointing and self.training:
1077
+ layer_outputs = self._gradient_checkpointing_func(
1078
+ decoder_layer.__call__,
1079
+ hidden_states,
1080
+ attention_mask,
1081
+ position_ids,
1082
+ past_key_values,
1083
+ output_attentions,
1084
+ use_cache,
1085
+ )
1086
+ else:
1087
+ layer_outputs = decoder_layer(
1088
+ hidden_states,
1089
+ attention_mask=attention_mask,
1090
+ position_ids=position_ids,
1091
+ past_key_value=past_key_values,
1092
+ output_attentions=output_attentions,
1093
+ use_cache=use_cache,
1094
+ )
1095
+
1096
+ hidden_states = layer_outputs[0]
1097
+
1098
+ if use_cache:
1099
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1100
+
1101
+ if output_attentions:
1102
+ all_self_attns += (layer_outputs[1],)
1103
+
1104
+ hidden_states = self.norm(hidden_states)
1105
+
1106
+ # add hidden states from the last decoder layer
1107
+ if output_hidden_states:
1108
+ all_hidden_states += (hidden_states,)
1109
+
1110
+ next_cache = None
1111
+ if use_cache:
1112
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1113
+ if not return_dict:
1114
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1115
+ return BaseModelOutputWithPast(
1116
+ last_hidden_state=hidden_states,
1117
+ past_key_values=next_cache,
1118
+ hidden_states=all_hidden_states,
1119
+ attentions=all_self_attns,
1120
+ )
1121
+
1122
+
1123
+ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
1124
+ _tied_weights_keys = ["lm_head.weight"]
1125
+
1126
+ def __init__(self, config):
1127
+ super().__init__(config)
1128
+ self.model = MiniCPMModel(config)
1129
+ self.vocab_size = config.vocab_size
1130
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1131
+
1132
+ # Initialize weights and apply final processing
1133
+ self.post_init()
1134
+
1135
+ def get_input_embeddings(self):
1136
+ return self.model.embed_tokens
1137
+
1138
+ def set_input_embeddings(self, value):
1139
+ self.model.embed_tokens = value
1140
+
1141
+ def get_output_embeddings(self):
1142
+ return self.lm_head
1143
+
1144
+ def set_output_embeddings(self, new_embeddings):
1145
+ self.lm_head = new_embeddings
1146
+
1147
+ def set_decoder(self, decoder):
1148
+ self.model = decoder
1149
+
1150
+ def get_decoder(self):
1151
+ return self.model
1152
+
1153
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1154
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1155
+ def forward(
1156
+ self,
1157
+ input_ids: torch.LongTensor = None,
1158
+ attention_mask: Optional[torch.Tensor] = None,
1159
+ position_ids: Optional[torch.LongTensor] = None,
1160
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1161
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1162
+ labels: Optional[torch.LongTensor] = None,
1163
+ use_cache: Optional[bool] = None,
1164
+ output_attentions: Optional[bool] = None,
1165
+ output_hidden_states: Optional[bool] = None,
1166
+ return_dict: Optional[bool] = None,
1167
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1168
+ r"""
1169
+ Args:
1170
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1171
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1172
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1173
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1174
+
1175
+ Returns:
1176
+
1177
+ Example:
1178
+
1179
+ ```python
1180
+ >>> from transformers import AutoTokenizer, MiniCPMForCausalLM
1181
+
1182
+ >>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1183
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1184
+
1185
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1186
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1187
+
1188
+ >>> # Generate
1189
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1190
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1191
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1192
+ ```"""
1193
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1194
+ output_hidden_states = (
1195
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1196
+ )
1197
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1198
+
1199
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1200
+ outputs = self.model(
1201
+ input_ids=input_ids,
1202
+ attention_mask=attention_mask,
1203
+ position_ids=position_ids,
1204
+ past_key_values=past_key_values,
1205
+ inputs_embeds=inputs_embeds,
1206
+ use_cache=use_cache,
1207
+ output_attentions=output_attentions,
1208
+ output_hidden_states=output_hidden_states,
1209
+ return_dict=return_dict,
1210
+ )
1211
+
1212
+ hidden_states = outputs[0]
1213
+ if self.config.pretraining_tp > 1:
1214
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1215
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1216
+ logits = torch.cat(logits, dim=-1)
1217
+ else:
1218
+ logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))
1219
+ logits = logits.float()
1220
+
1221
+ loss = None
1222
+ if labels is not None:
1223
+ # Shift so that tokens < n predict n
1224
+ shift_logits = logits[..., :-1, :].contiguous()
1225
+ shift_labels = labels[..., 1:].contiguous()
1226
+ # Flatten the tokens
1227
+ loss_fct = CrossEntropyLoss()
1228
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1229
+ shift_labels = shift_labels.view(-1)
1230
+ # Enable model parallelism
1231
+ shift_labels = shift_labels.to(shift_logits.device)
1232
+ loss = loss_fct(shift_logits, shift_labels)
1233
+
1234
+ if not return_dict:
1235
+ output = (logits,) + outputs[1:]
1236
+ return (loss,) + output if loss is not None else output
1237
+
1238
+ return CausalLMOutputWithPast(
1239
+ loss=loss,
1240
+ logits=logits,
1241
+ past_key_values=outputs.past_key_values,
1242
+ hidden_states=outputs.hidden_states,
1243
+ attentions=outputs.attentions,
1244
+ )
1245
+
1246
+ def prepare_inputs_for_generation(
1247
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1248
+ ):
1249
+ if past_key_values is not None:
1250
+ if isinstance(past_key_values, Cache):
1251
+ cache_length = past_key_values.get_seq_length()
1252
+ past_length = past_key_values.seen_tokens
1253
+ max_cache_length = past_key_values.get_max_length()
1254
+ else:
1255
+ cache_length = past_length = past_key_values[0][0].shape[2]
1256
+ max_cache_length = None
1257
+
1258
+ # Keep only the unprocessed tokens:
1259
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1260
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1261
+ # input)
1262
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1263
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1264
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1265
+ # input_ids based on the past_length.
1266
+ elif past_length < input_ids.shape[1]:
1267
+ input_ids = input_ids[:, past_length:]
1268
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1269
+
1270
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1271
+ if (
1272
+ max_cache_length is not None
1273
+ and attention_mask is not None
1274
+ and cache_length + input_ids.shape[1] > max_cache_length
1275
+ ):
1276
+ attention_mask = attention_mask[:, -max_cache_length:]
1277
+
1278
+ position_ids = kwargs.get("position_ids", None)
1279
+ if attention_mask is not None and position_ids is None:
1280
+ # create position_ids on the fly for batch generation
1281
+ position_ids = attention_mask.long().cumsum(-1) - 1
1282
+ position_ids.masked_fill_(attention_mask == 0, 1)
1283
+ if past_key_values:
1284
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1285
+
1286
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1287
+ if inputs_embeds is not None and past_key_values is None:
1288
+ model_inputs = {"inputs_embeds": inputs_embeds}
1289
+ else:
1290
+ model_inputs = {"input_ids": input_ids}
1291
+
1292
+ model_inputs.update(
1293
+ {
1294
+ "position_ids": position_ids,
1295
+ "past_key_values": past_key_values,
1296
+ "use_cache": kwargs.get("use_cache"),
1297
+ "attention_mask": attention_mask,
1298
+ }
1299
+ )
1300
+ return model_inputs
1301
+
1302
+ @staticmethod
1303
+ def _reorder_cache(past_key_values, beam_idx):
1304
+ reordered_past = ()
1305
+ for layer_past in past_key_values:
1306
+ reordered_past += (
1307
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1308
+ )
1309
+ return reordered_past
1310
+
1311
+ @torch.inference_mode()
1312
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user",
1313
+ max_length: int = 4096, num_beams=1, do_sample=True, top_p=0.8, temperature=0.3, logits_processor=None,
1314
+ **kwargs):
1315
+ if history is None:
1316
+ history = []
1317
+ if logits_processor:
1318
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1319
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1320
+ else:
1321
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1322
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1323
+
1324
+ history.append({"role": role, "content": query})
1325
+ history_str = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=False)
1326
+ inputs = tokenizer(history_str, return_tensors='pt').to(self.device)
1327
+ outputs = self.generate(**inputs, **gen_kwargs)
1328
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1329
+ response = tokenizer.decode(outputs)
1330
+ pattern = re.compile(r".*?(?=<AI>|<用户>)", re.DOTALL)
1331
+ matches = pattern.findall(response)
1332
+ if len(matches) > 0:
1333
+ response = matches[0]
1334
+ history.append({"role": "assistant", "content": response})
1335
+ return response, history
1336
+
1337
+
1338
+ @add_start_docstrings(
1339
+ """
1340
+ The MiniCPM Model transformer with a sequence classification head on top (linear layer).
1341
+
1342
+ [`MiniCPMForSequenceClassification`] uses the first token in order to do the classification, as other models
1343
+ (e.g. Roberta) do.
1344
+ """,
1345
+ MINICPM_START_DOCSTRING,
1346
+ )
1347
+ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
1348
+ def __init__(self, config):
1349
+ super().__init__(config)
1350
+ self.num_labels = config.num_labels
1351
+ self.model = MiniCPMModel(config)
1352
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1353
+
1354
+ # Initialize weights and apply final processing
1355
+ self.post_init()
1356
+
1357
+ def get_input_embeddings(self):
1358
+ return self.model.embed_tokens
1359
+
1360
+ def set_input_embeddings(self, value):
1361
+ self.model.embed_tokens = value
1362
+
1363
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1364
+ def forward(
1365
+ self,
1366
+ input_ids: torch.LongTensor = None,
1367
+ attention_mask: Optional[torch.Tensor] = None,
1368
+ position_ids: Optional[torch.LongTensor] = None,
1369
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1370
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1371
+ labels: Optional[torch.LongTensor] = None,
1372
+ use_cache: Optional[bool] = None,
1373
+ output_attentions: Optional[bool] = None,
1374
+ output_hidden_states: Optional[bool] = None,
1375
+ return_dict: Optional[bool] = None,
1376
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1377
+ r"""
1378
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1379
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1380
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1381
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1382
+ """
1383
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1384
+
1385
+ transformer_outputs = self.model(
1386
+ input_ids,
1387
+ attention_mask=attention_mask,
1388
+ position_ids=position_ids,
1389
+ past_key_values=past_key_values,
1390
+ inputs_embeds=inputs_embeds,
1391
+ use_cache=use_cache,
1392
+ output_attentions=output_attentions,
1393
+ output_hidden_states=output_hidden_states,
1394
+ return_dict=return_dict,
1395
+ )
1396
+ hidden_states = transformer_outputs[0]
1397
+ # logits = self.score(hidden_states)
1398
+ logits = self.score(hidden_states[:,0,:])
1399
+ pooled_logits = logits
1400
+
1401
+ # if input_ids is not None:
1402
+ # batch_size = input_ids.shape[0]
1403
+ # else:
1404
+ # batch_size = inputs_embeds.shape[0]
1405
+
1406
+ # if self.config.pad_token_id is None and batch_size != 1:
1407
+ # raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1408
+ # if self.config.pad_token_id is None:
1409
+ # sequence_lengths = -1
1410
+ # else:
1411
+ # if input_ids is not None:
1412
+ # sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1413
+ # logits.device
1414
+ # )
1415
+ # else:
1416
+ # sequence_lengths = -1
1417
+
1418
+ # pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1419
+
1420
+ loss = None
1421
+ # if labels is not None:
1422
+ # labels = labels.to(logits.device)
1423
+ # if self.config.problem_type is None:
1424
+ # if self.num_labels == 1:
1425
+ # self.config.problem_type = "regression"
1426
+ # elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1427
+ # self.config.problem_type = "single_label_classification"
1428
+ # else:
1429
+ # self.config.problem_type = "multi_label_classification"
1430
+
1431
+ # if self.config.problem_type == "regression":
1432
+ # loss_fct = MSELoss()
1433
+ # if self.num_labels == 1:
1434
+ # loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1435
+ # else:
1436
+ # loss = loss_fct(pooled_logits, labels)
1437
+ # elif self.config.problem_type == "single_label_classification":
1438
+ # loss_fct = CrossEntropyLoss()
1439
+ # loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1440
+ # elif self.config.problem_type == "multi_label_classification":
1441
+ # loss_fct = BCEWithLogitsLoss()
1442
+ # loss = loss_fct(pooled_logits, labels)
1443
+ # if not return_dict:
1444
+ # output = (pooled_logits,) + transformer_outputs[1:]
1445
+ # return ((loss,) + output) if loss is not None else output
1446
+
1447
+ return SequenceClassifierOutputWithPast(
1448
+ loss=loss,
1449
+ logits=pooled_logits,
1450
+ past_key_values=transformer_outputs.past_key_values,
1451
+ hidden_states=transformer_outputs.hidden_states,
1452
+ attentions=transformer_outputs.attentions,
1453
+ )
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.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9aafcd7da1f5611dab6be545db74d5552a2ccc9c2a12c72ea7be63aac4a25d7
3
+ size 1994871
tokenizer_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ }
29
+ },
30
+ "bos_token": "<s>",
31
+ "clean_up_tokenization_spaces": false,
32
+ "eos_token": "</s>",
33
+ "legacy": true,
34
+ "model_max_length": 1000000000000000019884624838656,
35
+ "pad_token": "<unk>",
36
+ "sp_model_kwargs": {},
37
+ "spaces_between_special_tokens": false,
38
+ "tokenizer_class": "LlamaTokenizer",
39
+ "unk_token": "<unk>",
40
+ "use_default_system_prompt": false
41
+ }