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