liyadong commited on
Commit
b20e44e
·
1 Parent(s): 767d5dc

add model file and update readme

Browse files
README.md CHANGED
@@ -8,4 +8,243 @@ tags:
8
  - moe
9
  - conversational
10
  library_name: transformers
11
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  - moe
9
  - conversational
10
  library_name: transformers
11
+ ---
12
+
13
+ <div align="center">
14
+ <img src="./assets/megrez-logo.png" alt="Megrez Logo" width="400" />
15
+
16
+ <br>
17
+ <h1> Megrez2-3x7B-A3B </h1>
18
+
19
+ <a href="https://github.com/infinigence/Infini-Megrez">
20
+ <b>🔗 Github</b>
21
+ </a> &nbsp;|&nbsp;
22
+ <a href="https://github.com/infinigence/Infini-Megrez/blob/main/docs/tech_report.pdf">
23
+ <b>📄 Tech Report</b>
24
+ </a> &nbsp;|&nbsp;
25
+ <a href="https://huggingface.co/spaces/Infinigence/Megrez2-3x7B-A3B">
26
+ <b>💻 Demo</b>
27
+ </a> &nbsp;|&nbsp;
28
+ <a href="https://huggingface.co/Infinigence/Megrez2-3x7B-A3B/blob/main/assets/wechat-official.jpg">
29
+ <b>💬 WeChat Official</b>
30
+ </a> &nbsp;
31
+
32
+ <br>
33
+
34
+ <strong>[中文](https://huggingface.co/Infinigence/Megrez2-3x7B-A3B/blob/main/README_ZH.md) | English</strong>
35
+
36
+ </div>
37
+
38
+ ## Introduction
39
+
40
+ Megrez2-3x7B-A3B is a device native large language model. Megrez2 takes advantages of both the accuracy of Mixture-of-Experts (MoE) architecture and the compact size of Dense models. This release model was trained on 8T Tokens of data. In the future, we plan to improve the model's reasoning and agent capabilities.
41
+
42
+ ## Model Card
43
+
44
+ <div align="center">
45
+
46
+ | | |
47
+ |:---:|:---:|
48
+ | **Architecture** | Mixture-of-Experts (MoE) |
49
+ | **Total Parameters** | 3x7B |
50
+ | **Activated Parameters** | 3B |
51
+ | **Experts Shared Frequency**| 3 |
52
+ | **Number of Layers** (Dense layer included) | 31 |
53
+ | **Number of Dense Layers** | 1 |
54
+ | **Attention Hidden Dimension** | 2048 |
55
+ | **MoE Hidden Dimension** (per Expert) | 1408 |
56
+ | **Number of Attention Heads** | 16 |
57
+ | **Number of Experts** | 64 |
58
+ | **Selected Experts per Token** | 6 |
59
+ | **Number of Shared Experts** | 4 |
60
+ | **Vocabulary Size** | 128,880 |
61
+ | **Context Length** | 32K |
62
+ | **Base Frequency of RoPE** | 5,000,000 |
63
+ | **Attention Mechanism** | GQA |
64
+ | **Activation Function** | SwiGLU |
65
+ </div>
66
+
67
+ ## Performance
68
+
69
+ We evaluated Megrez2-3x7B-A3B using the open-source evaluation tool [OpenCompass](https://github.com/open-compass/opencompass) on several important benchmarks. Some of the evaluation results are shown in the table below.
70
+
71
+ <div align="center">
72
+ <table>
73
+ <thead>
74
+ <tr>
75
+ <th align="center">Benchmark</th>
76
+ <th align="center">Metric</th>
77
+ <th align="center"><sup>Megrez2-3x7B<br>-A3B</sup></th>
78
+ <th align="center"><sup>Megrez2-3x7B<br>-A3B-Preview</sup></th>
79
+ <th align="center"><sup>SmallThinker-21B<br>-A3B-Instruct</sup></th>
80
+ <th align="center"><sup>Qwen3-30B-A3B</sup></th>
81
+ <th align="center"><sup>Qwen3-8B</sup></th>
82
+ <th align="center"><sup>Qwen3-4B<br>-Instruct-2507</sup></th>
83
+ <th align="center"><sup>Phi4-14B<br>(nothink)</sup></th>
84
+ <th align="center"><sup>Gemma3-12B</sup></th>
85
+ </tr>
86
+ </thead>
87
+ <tbody>
88
+ <tr>
89
+ <td align="center">Activate Params (B)</td>
90
+ <td align="center"></td>
91
+ <td align="center">3.0</td>
92
+ <td align="center">3.0</td>
93
+ <td align="center">3.0</td>
94
+ <td align="center">3.3</td>
95
+ <td align="center">8.2</td>
96
+ <td align="center">4.0</td>
97
+ <td align="center">14.7</td>
98
+ <td align="center">12.2</td>
99
+ </tr>
100
+ <tr>
101
+ <td align="center">Stored Params (B)</td>
102
+ <td align="center"></td>
103
+ <td align="center">7.5</td>
104
+ <td align="center">7.5</td>
105
+ <td align="center">21.5</td>
106
+ <td align="center">30.5</td>
107
+ <td align="center">8.2</td>
108
+ <td align="center">4.0</td>
109
+ <td align="center">14.7</td>
110
+ <td align="center">12.2</td>
111
+ </tr>
112
+ <tr>
113
+ <td align="center">MMLU</td>
114
+ <td align="center">EM</td>
115
+ <td align="center">85.4</td>
116
+ <td align="center"><strong>87.5</strong></td>
117
+ <td align="center">84.4</td>
118
+ <td align="center">85.1</td>
119
+ <td align="center">81.8</td>
120
+ <td align="center">-</td>
121
+ <td align="center">84.6</td>
122
+ <td align="center">78.5</td>
123
+ </tr>
124
+ <tr>
125
+ <td align="center">GPQA</td>
126
+ <td align="center">EM</td>
127
+ <td align="center"><strong>58.8</strong></td>
128
+ <td align="center">28.8</td>
129
+ <td align="center">55.0</td>
130
+ <td align="center">44.4</td>
131
+ <td align="center">38.9</td>
132
+ <td align="center">62</td>
133
+ <td align="center">55.5</td>
134
+ <td align="center">34.9</td>
135
+ </tr>
136
+ <tr>
137
+ <td align="center">IFEval</td>
138
+ <td align="center">Prompt<br>Strict</td>
139
+ <td align="center"><strong>87.7</strong></td>
140
+ <td align="center">80.2</td>
141
+ <td align="center">85.8</td>
142
+ <td align="center">84.3</td>
143
+ <td align="center">83.9</td>
144
+ <td align="center">83.4</td>
145
+ <td align="center">63.2</td>
146
+ <td align="center">74.7</td>
147
+ </tr>
148
+ <tr>
149
+ <td align="center">MATH-500</td>
150
+ <td align="center">EM</td>
151
+ <td align="center"><strong>87.2</strong></td>
152
+ <td align="center">81.6</td>
153
+ <td align="center">82.4</td>
154
+ <td align="center">84.4</td>
155
+ <td align="center">81.6</td>
156
+ <td align="center">-</td>
157
+ <td align="center">80.2</td>
158
+ <td align="center">82.4</td>
159
+ </tr>
160
+ </tbody>
161
+ </table>
162
+ </div>
163
+
164
+ ## How to Run
165
+
166
+ ### Transformers
167
+
168
+ The latest version of `transformers` is recommended or `transformers>=4.52.4` is required.
169
+ The following contains a code snippet illustrating how to use the model generate content based on given inputs.
170
+
171
+ ```python
172
+ from transformers import AutoModelForCausalLM, AutoTokenizer
173
+ import torch
174
+
175
+ path = "Infinigence/Megrez2-3x7B-A3B"
176
+ device = "cuda"
177
+
178
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
179
+ model = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch.bfloat16, device_map=device, trust_remote_code=True)
180
+
181
+ messages = [
182
+ {"role": "user", "content": "世界上最高的山峰是哪座?"},
183
+ ]
184
+ model_inputs = tokenizer.apply_chat_template(messages, return_tensors="pt", add_generation_prompt=True).to(device)
185
+
186
+ model_outputs = model.generate(
187
+ model_inputs,
188
+ do_sample=True,
189
+ max_new_tokens=1024
190
+ )
191
+
192
+ output_token_ids = [
193
+ model_outputs[i][len(model_inputs[i]):] for i in range(len(model_inputs))
194
+ ]
195
+
196
+ responses = tokenizer.batch_decode(output_token_ids, skip_special_tokens=True)[0]
197
+ print(responses)
198
+
199
+ # 世界上最高的山峰是珠穆朗玛峰(Mount Everest),位于喜马拉雅山脉的中尼边境。珠穆朗玛峰的海拔高度为8,848.86米(29,031.7英尺),这一数据是由中国和尼泊尔在2020年共同宣布的最新测量结果。珠穆朗玛峰不仅是登山爱好者的圣地,也是地理和科学研究的重要对象。
200
+ ```
201
+
202
+ ### ModelScope
203
+
204
+ `ModelScope` adopts Python API similar to (though not entirely identical to) `Transformers`. For basic usage, simply modify the first line of the above code as follows:
205
+
206
+ ```python
207
+ from modelscope import AutoModelForCausalLM, AutoTokenizer
208
+ ```
209
+
210
+ ### llama.cpp
211
+
212
+ Coming soon...
213
+
214
+ ## How to Deploy
215
+
216
+ Megrez2-3x7B-A3B support using `vLLM` and `SGLang` as inference backends. For more information, please visit the [gitHub repository](https://github.com/infinigence/Infini-Megrez).
217
+
218
+ ## Best Practice
219
+
220
+ To achieve optimal performance, we recommend the following settings:
221
+
222
+ 1. Sampling Parameters: we suggest using Temperature=0.7 and TopP=0.9 .
223
+
224
+ 2. Standardize Output Format: We recommend using prompts to standardize model outputs when benchmarking.
225
+ * Math Problems: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
226
+ * Multiple-Choice Questions: Add the following JSON structure to the prompt to standardize responses: "Please show your choice in the answer field with only the choice letter, e.g., "answer": "C"."
227
+
228
+ ## License Agreement
229
+
230
+ All our open-weight models are licensed under Apache 2.0.
231
+
232
+ ## Citation
233
+
234
+ If you find our work helpful, feel free to give us a cite.
235
+
236
+ ```bibtex
237
+ @misc{li2025megrez2technicalreport,
238
+ title={Megrez2 Technical Report},
239
+ author={Boxun Li and Yadong Li and Zhiyuan Li and Congyi Liu and Weilin Liu and Guowei Niu and Zheyue Tan and Haiyang Xu and Zhuyu Yao and Tao Yuan and Dong Zhou and Yueqing Zhuang and Bo Zhao and Guohao Dai and Yu Wang},
240
+ year={2025},
241
+ eprint={2507.17728},
242
+ archivePrefix={arXiv},
243
+ primaryClass={cs.CL},
244
+ url={https://arxiv.org/abs/2507.17728},
245
+ }
246
+ ```
247
+
248
+ ## Contact
249
+
250
+ If you have any questions, please feel free to submit a GitHub issue or contact [WeChat groups](https://huggingface.co/Infinigence/Megrez2-3x7B-A3B/blob/main/assets/wechat-group.jpg).
README_ZH.md ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <img src="./assets/megrez-logo.png" alt="Megrez Logo" width="400" />
3
+
4
+ <br>
5
+ <h1> Megrez2-3x7B-A3B </h1>
6
+
7
+ <a href="https://github.com/infinigence/Infini-Megrez">
8
+ <b>🔗 Github</b>
9
+ </a> &nbsp;|&nbsp;
10
+ <a href="https://github.com/infinigence/Infini-Megrez/blob/main/docs/tech_report.pdf">
11
+ <b>📄 Tech Report</b>
12
+ </a> &nbsp;|&nbsp;
13
+ <a href="https://huggingface.co/spaces/Infinigence/Megrez2-3x7B-A3B">
14
+ <b>💻 Demo</b>
15
+ </a> &nbsp;|&nbsp;
16
+ <a href="https://huggingface.co/Infinigence/Megrez2-3x7B-A3B/blob/main/assets/wechat-official.jpg">
17
+ <b>💬 WeChat Official</b>
18
+ </a> &nbsp;
19
+
20
+ <br>
21
+
22
+ <strong>中文 | [English](https://huggingface.co/Infinigence/Megrez2-3x7B-A3B/blob/main/README.md)</strong>
23
+
24
+ </div>
25
+
26
+ ## 模型简介
27
+
28
+ Megrez2-3x7B-A3B 是专为终端设备设计的大模型,兼顾MoE的精度杠杆与Dense的总参数量友好。本次发布的为Megrez 2.0正式版本,训练数据量8T Tokens,未来我们计划提高模型的推理和Agent能力。
29
+
30
+ ## 基础信息
31
+
32
+ <div align="center">
33
+
34
+ | | |
35
+ |:---:|:---:|
36
+ | **Architecture** | Mixture-of-Experts (MoE) |
37
+ | **Total Parameters** | 3x7B |
38
+ | **Activated Parameters** | 3B |
39
+ | **Experts Shared Frequency**| 3 |
40
+ | **Number of Layers** (Dense layer included) | 31 |
41
+ | **Number of Dense Layers** | 1 |
42
+ | **Attention Hidden Dimension** | 2048 |
43
+ | **MoE Hidden Dimension** (per Expert) | 1408 |
44
+ | **Number of Attention Heads** | 16 |
45
+ | **Number of Experts** | 64 |
46
+ | **Selected Experts per Token** | 6 |
47
+ | **Number of Shared Experts** | 4 |
48
+ | **Vocabulary Size** | 128,880 |
49
+ | **Context Length** | 32K |
50
+ | **Base Frequency of RoPE** | 5,000,000 |
51
+ | **Attention Mechanism** | GQA |
52
+ | **Activation Function** | SwiGLU |
53
+ </div>
54
+
55
+ ## 性能测试
56
+
57
+ 我们使用开源评测工具 [OpenCompass](https://github.com/open-compass/opencompass) 对 Megrez2-3x7B-A3B 进行了评测,部分评测结果如下表所示。
58
+
59
+ <div align="center">
60
+ <table>
61
+ <thead>
62
+ <tr>
63
+ <th align="center">Benchmark</th>
64
+ <th align="center">Metric</th>
65
+ <th align="center"><sup>Megrez2-3x7B<br>-A3B</sup></th>
66
+ <th align="center"><sup>Megrez2-3x7B<br>-A3B-Preview</sup></th>
67
+ <th align="center"><sup>SmallThinker-21B<br>-A3B-Instruct</sup></th>
68
+ <th align="center"><sup>Qwen3-30B-A3B</sup></th>
69
+ <th align="center"><sup>Qwen3-8B</sup></th>
70
+ <th align="center"><sup>Qwen3-4B<br>-Instruct-2507</sup></th>
71
+ <th align="center"><sup>Phi4-14B<br>(nothink)</sup></th>
72
+ <th align="center"><sup>Gemma3-12B</sup></th>
73
+ </tr>
74
+ </thead>
75
+ <tbody>
76
+ <tr>
77
+ <td align="center">Activate Params (B)</td>
78
+ <td align="center"></td>
79
+ <td align="center">3.0</td>
80
+ <td align="center">3.0</td>
81
+ <td align="center">3.0</td>
82
+ <td align="center">3.3</td>
83
+ <td align="center">8.2</td>
84
+ <td align="center">4.0</td>
85
+ <td align="center">14.7</td>
86
+ <td align="center">12.2</td>
87
+ </tr>
88
+ <tr>
89
+ <td align="center">Stored Params (B)</td>
90
+ <td align="center"></td>
91
+ <td align="center">7.5</td>
92
+ <td align="center">7.5</td>
93
+ <td align="center">21.5</td>
94
+ <td align="center">30.5</td>
95
+ <td align="center">8.2</td>
96
+ <td align="center">4.0</td>
97
+ <td align="center">14.7</td>
98
+ <td align="center">12.2</td>
99
+ </tr>
100
+ <tr>
101
+ <td align="center">MMLU</td>
102
+ <td align="center">EM</td>
103
+ <td align="center">85.4</td>
104
+ <td align="center"><strong>87.5</strong></td>
105
+ <td align="center">84.4</td>
106
+ <td align="center">85.1</td>
107
+ <td align="center">81.8</td>
108
+ <td align="center">-</td>
109
+ <td align="center">84.6</td>
110
+ <td align="center">78.5</td>
111
+ </tr>
112
+ <tr>
113
+ <td align="center">GPQA</td>
114
+ <td align="center">EM</td>
115
+ <td align="center"><strong>58.8</strong></td>
116
+ <td align="center">28.8</td>
117
+ <td align="center">55.0</td>
118
+ <td align="center">44.4</td>
119
+ <td align="center">38.9</td>
120
+ <td align="center">62</td>
121
+ <td align="center">55.5</td>
122
+ <td align="center">34.9</td>
123
+ </tr>
124
+ <tr>
125
+ <td align="center">IFEval</td>
126
+ <td align="center">Prompt<br>Strict</td>
127
+ <td align="center"><strong>87.7</strong></td>
128
+ <td align="center">80.2</td>
129
+ <td align="center">85.8</td>
130
+ <td align="center">84.3</td>
131
+ <td align="center">83.9</td>
132
+ <td align="center">83.4</td>
133
+ <td align="center">63.2</td>
134
+ <td align="center">74.7</td>
135
+ </tr>
136
+ <tr>
137
+ <td align="center">MATH-500</td>
138
+ <td align="center">EM</td>
139
+ <td align="center"><strong>87.2</strong></td>
140
+ <td align="center">81.6</td>
141
+ <td align="center">82.4</td>
142
+ <td align="center">84.4</td>
143
+ <td align="center">81.6</td>
144
+ <td align="center">-</td>
145
+ <td align="center">80.2</td>
146
+ <td align="center">82.4</td>
147
+ </tr>
148
+ </tbody>
149
+ </table>
150
+ </div>
151
+
152
+ ## 如何运行
153
+
154
+ ### Transformers
155
+
156
+ 推荐使用最新版本的 `transformers` 或者 `transformers>=4.52.4` 的版本。
157
+ 以下是一个非常简单的代码片段示例,展示如何运行 Megrez2-3x7B-A3B 模型:
158
+
159
+ ```python
160
+ from transformers import AutoModelForCausalLM, AutoTokenizer
161
+ import torch
162
+
163
+ path = "Infinigence/Megrez2-3x7B-A3B"
164
+ device = "cuda"
165
+
166
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
167
+ model = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch.bfloat16, device_map=device, trust_remote_code=True)
168
+
169
+ messages = [
170
+ {"role": "user", "content": "世界上最高的山峰是哪座?"},
171
+ ]
172
+ model_inputs = tokenizer.apply_chat_template(messages, return_tensors="pt", add_generation_prompt=True).to(device)
173
+
174
+ model_outputs = model.generate(
175
+ model_inputs,
176
+ do_sample=True,
177
+ max_new_tokens=1024
178
+ )
179
+
180
+ output_token_ids = [
181
+ model_outputs[i][len(model_inputs[i]):] for i in range(len(model_inputs))
182
+ ]
183
+
184
+ responses = tokenizer.batch_decode(output_token_ids, skip_special_tokens=True)[0]
185
+ print(responses)
186
+
187
+ # 世界上最高的山峰是珠穆朗玛峰(Mount Everest),位于喜马拉雅山脉的中尼边境。珠穆朗玛峰的海拔高度为8,848.86米(29,031.7英尺),这一数据是由中国和尼泊尔在2020年共同宣布的最新测量结果。珠穆朗玛峰不仅是登山爱好者的圣地,也是地理和科学研究的重要对象。
188
+ ```
189
+
190
+ ### ModelScope
191
+
192
+ `ModelScope` 采用了与 `Transformers` 类似(但不完全一致)的编程接口。对于基础使用,仅需将上面代码第一行做如下修改:
193
+
194
+ ```python
195
+ from modelscope import AutoModelForCausalLM, AutoTokenizer
196
+ ```
197
+
198
+ ### llama.cpp
199
+ 即将到来...
200
+
201
+ ## 如何部署
202
+
203
+ Megrez2-3x7B-A3B 支持使用 `vLLM` 和 `SGLang` 作为推理后端,更详细的信息请查看我们的[github仓库](https://github.com/infinigence/Infini-Megrez)。
204
+
205
+ ## 最佳实践
206
+
207
+ 为了获得最佳性能,建议以下设置:
208
+
209
+ 1. 采样参数:推荐使用 Temperature=0.7 和 TopP=0.9 。
210
+
211
+ 2. 标准化输出格式:在基准测试时,我们建议使用提示来标准化模型输出,比如:
212
+ * 数学问题:在提示中包含“请逐步推理,并将最终答案放在\boxed{}中。”
213
+ * 选择题:在提示中添加以下 JSON 结构以标准化响应:“请在 answer 字段中仅以选择字母的形式显示您的选择,例如 "answer": "C" 。”
214
+
215
+ ## 许可声明
216
+
217
+ 我们所有的开源模型均采用Apache 2.0协议授权。
218
+
219
+ ## 引用信息
220
+
221
+ 如果您觉得我们的代码和模型有用,请引用以下信息。
222
+
223
+ ```bibtex
224
+ @misc{li2025megrez2technicalreport,
225
+ title={Megrez2 Technical Report},
226
+ author={Boxun Li and Yadong Li and Zhiyuan Li and Congyi Liu and Weilin Liu and Guowei Niu and Zheyue Tan and Haiyang Xu and Zhuyu Yao and Tao Yuan and Dong Zhou and Yueqing Zhuang and Bo Zhao and Guohao Dai and Yu Wang},
227
+ year={2025},
228
+ eprint={2507.17728},
229
+ archivePrefix={arXiv},
230
+ primaryClass={cs.CL},
231
+ url={https://arxiv.org/abs/2507.17728},
232
+ }
233
+ ```
234
+
235
+ ## 联系我们
236
+
237
+ 如果您有任何问题,请随时提交GitHub issue或联系[微信群组](https://huggingface.co/Infinigence/Megrez2-3x7B-A3B/blob/main/assets/wechat-group.jpg)。
assets/megrez-logo.png ADDED

Git LFS Details

  • SHA256: 7f86436275de9a13647a108b187d4626be82ad6f3569d292a21358eeb1ff1dcd
  • Pointer size: 131 Bytes
  • Size of remote file: 646 kB
assets/wechat-group.jpg ADDED

Git LFS Details

  • SHA256: f82f681e76fad1de809011f8198b11ad8418a2fb1367e6d88b48fc3aefe74e90
  • Pointer size: 130 Bytes
  • Size of remote file: 93.8 kB
assets/wechat-official.jpg ADDED

Git LFS Details

  • SHA256: f48f493e3f5b1b2c627526cdcae1ae8109bc90dd2043381ec9b141f8d992d0b2
  • Pointer size: 131 Bytes
  • Size of remote file: 147 kB
config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MegrezMoeForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_megrez_moe.MegrezMoeConfig",
9
+ "AutoModel": "modeling_megrez_moe.MegrezMoeModel",
10
+ "AutoModelForCausalLM": "modeling_megrez_moe.MegrezMoeForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.001,
13
+ "bos_token_id": null,
14
+ "eos_token_id": 120005,
15
+ "ep_size": 1,
16
+ "experts_shared_frequency": 3,
17
+ "first_k_dense_replace": 1,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 2048,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 10944,
22
+ "max_position_embeddings": 163840,
23
+ "model_type": "megrez_moe",
24
+ "moe_intermediate_size": 1408,
25
+ "moe_layer_freq": 1,
26
+ "n_group": 1,
27
+ "n_routed_experts": 64,
28
+ "n_shared_experts": 4,
29
+ "norm_topk_prob": true,
30
+ "num_attention_heads": 16,
31
+ "num_experts_per_tok": 6,
32
+ "num_hidden_layers": 11,
33
+ "num_key_value_heads": 4,
34
+ "pad_token_id": 120002,
35
+ "pre_gate": true,
36
+ "pretraining_tp": 1,
37
+ "rms_norm_eps": 1e-06,
38
+ "rope_scaling": null,
39
+ "rope_theta": 5000000,
40
+ "routed_scaling_factor": 1.0,
41
+ "scoring_func": "sigmoid",
42
+ "seq_aux": true,
43
+ "tie_word_embeddings": false,
44
+ "topk_group": 1,
45
+ "topk_method": "noaux_tc",
46
+ "torch_dtype": "bfloat16",
47
+ "transformers_version": "4.52.4",
48
+ "use_cache": true,
49
+ "vocab_size": 122880
50
+ }
configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"framework":"Pytorch","task":"text-generation"}
configuration_megrez_moe.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ logger = logging.get_logger(__name__)
5
+
6
+ MegrezMoe_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
7
+ class MegrezMoeConfig(PretrainedConfig):
8
+ r"""
9
+ This is the configuration class to store the configuration of a [`MegrezMoeModel`]. It is used to instantiate an DeepSeek
10
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
11
+ defaults will yield a similar configuration to that of the DeepSeek-V2.
12
+
13
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
14
+ documentation from [`PretrainedConfig`] for more information.
15
+
16
+
17
+ Args:
18
+ vocab_size (`int`, *optional*, defaults to 102400):
19
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
20
+ `inputs_ids` passed when calling [`MegrezMoeModel`]
21
+ hidden_size (`int`, *optional*, defaults to 4096):
22
+ Dimension of the hidden representations.
23
+ intermediate_size (`int`, *optional*, defaults to 11008):
24
+ Dimension of the MLP representations.
25
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
26
+ Dimension of the MoE representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer decoder.
29
+ num_attention_heads (`int`, *optional*, defaults to 32):
30
+ Number of attention heads for each attention layer in the Transformer decoder.
31
+ n_shared_experts (`int`, *optional*, defaults to None):
32
+ Number of shared experts, None means dense model.
33
+ n_routed_experts (`int`, *optional*, defaults to None):
34
+ Number of routed experts, None means dense model.
35
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
36
+ Scaling factor or routed experts.
37
+ topk_method (`str`, *optional*, defaults to `gready`):
38
+ Topk method used in routed gate.
39
+ n_group (`int`, *optional*, defaults to None):
40
+ Number of groups for routed experts.
41
+ topk_group (`int`, *optional*, defaults to None):
42
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
43
+ num_experts_per_tok (`int`, *optional*, defaults to None):
44
+ Number of selected experts, None means dense model.
45
+ moe_layer_freq (`int`, *optional*, defaults to 1):
46
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
47
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
48
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
49
+ \--k dense layers--/
50
+ norm_topk_prob (`bool`, *optional*, defaults to False):
51
+ Whether to normalize the weights of the routed experts.
52
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
53
+ Method of computing expert weights.
54
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
55
+ Auxiliary loss weight coefficient.
56
+ seq_aux = (`bool`, *optional*, defaults to True):
57
+ Whether to compute the auxiliary loss for each individual sample.
58
+ num_key_value_heads (`int`, *optional*):
59
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
60
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
61
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
62
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
63
+ by meanpooling all the original heads within that group. For more details checkout [this
64
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
65
+ `num_attention_heads`.
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with.
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
73
+ The epsilon used by the rms normalization layers.
74
+ use_cache (`bool`, *optional*, defaults to `True`):
75
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
76
+ relevant if `config.is_decoder=True`.
77
+ pad_token_id (`int`, *optional*):
78
+ Padding token id.
79
+ bos_token_id (`int`, *optional*, defaults to 1):
80
+ Beginning of stream token id.
81
+ eos_token_id (`int`, *optional*, defaults to 2):
82
+ End of stream token id.
83
+ pretraining_tp (`int`, *optional*, defaults to 1):
84
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
85
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
86
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
87
+ issue](https://github.com/pytorch/pytorch/issues/76232).
88
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
89
+ Whether to tie weight embeddings
90
+ rope_theta (`float`, *optional*, defaults to 10000.0):
91
+ The base period of the RoPE embeddings.
92
+ rope_scaling (`Dict`, *optional*):
93
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
94
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
95
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
96
+ `max_position_embeddings` to the expected new maximum.
97
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
98
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
99
+ attention_dropout (`float`, *optional*, defaults to 0.0):
100
+ The dropout ratio for the attention probabilities.
101
+
102
+ ```python
103
+ >>> from transformers import MegrezMoeModel, MegrezMoeConfig
104
+
105
+ >>> # Initializing a Deepseek-V2 style configuration
106
+ >>> configuration = MegrezMoeConfig()
107
+
108
+ >>> # Accessing the model configuration
109
+ >>> configuration = model.config
110
+ ```"""
111
+
112
+ model_type = "megrez_moe"
113
+ keys_to_ignore_at_inference = ["past_key_values"]
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=102400,
118
+ hidden_size=4096,
119
+ intermediate_size=11008,
120
+ moe_intermediate_size = 1407,
121
+ num_hidden_layers=30,
122
+ num_attention_heads=32,
123
+ num_key_value_heads=32,
124
+ n_shared_experts = None,
125
+ n_routed_experts = None,
126
+ ep_size = 1,
127
+ routed_scaling_factor = 1.0,
128
+ topk_method = 'gready',
129
+ n_group = None,
130
+ topk_group = None,
131
+ num_experts_per_tok = None,
132
+ moe_layer_freq = 1,
133
+ first_k_dense_replace = 0,
134
+ norm_topk_prob = False,
135
+ scoring_func = 'softmax',
136
+ aux_loss_alpha = 0.001,
137
+ seq_aux = True,
138
+ hidden_act="silu",
139
+ max_position_embeddings=2048,
140
+ initializer_range=0.02,
141
+ rms_norm_eps=1e-6,
142
+ use_cache=True,
143
+ pad_token_id=None,
144
+ bos_token_id=100000,
145
+ eos_token_id=100001,
146
+ pretraining_tp=1,
147
+ tie_word_embeddings=False,
148
+ rope_theta=10000.0,
149
+ rope_scaling=None,
150
+ attention_bias=False,
151
+ attention_dropout=0.0,
152
+ experts_shared_frequency=1,
153
+ pre_gate=False,
154
+ **kwargs,
155
+ ):
156
+ self.vocab_size = vocab_size
157
+ self.max_position_embeddings = max_position_embeddings
158
+ self.hidden_size = hidden_size
159
+ self.intermediate_size = intermediate_size
160
+ self.moe_intermediate_size = moe_intermediate_size
161
+ self.num_hidden_layers = num_hidden_layers
162
+ self.num_attention_heads = num_attention_heads
163
+ self.n_shared_experts = n_shared_experts
164
+ self.n_routed_experts = n_routed_experts
165
+ self.ep_size = ep_size
166
+ self.routed_scaling_factor = routed_scaling_factor
167
+ self.topk_method = topk_method
168
+ self.n_group = n_group
169
+ self.topk_group = topk_group
170
+ self.num_experts_per_tok = num_experts_per_tok
171
+ self.moe_layer_freq = moe_layer_freq
172
+ self.first_k_dense_replace = first_k_dense_replace
173
+ self.norm_topk_prob = norm_topk_prob
174
+ self.scoring_func = scoring_func
175
+ self.aux_loss_alpha = aux_loss_alpha
176
+ self.seq_aux = seq_aux
177
+ # for backward compatibility
178
+ if num_key_value_heads is None:
179
+ num_key_value_heads = num_attention_heads
180
+
181
+ self.num_key_value_heads = num_key_value_heads
182
+ self.hidden_act = hidden_act
183
+ self.initializer_range = initializer_range
184
+ self.rms_norm_eps = rms_norm_eps
185
+ self.pretraining_tp = pretraining_tp
186
+ self.use_cache = use_cache
187
+ self.rope_theta = rope_theta
188
+ self.rope_scaling = rope_scaling
189
+ self.attention_bias = attention_bias
190
+ self.attention_dropout = attention_dropout
191
+
192
+ self.experts_shared_frequency = experts_shared_frequency
193
+ self.pre_gate = pre_gate
194
+
195
+ super().__init__(
196
+ pad_token_id=pad_token_id,
197
+ bos_token_id=bos_token_id,
198
+ eos_token_id=eos_token_id,
199
+ tie_word_embeddings=tie_word_embeddings,
200
+ **kwargs,
201
+ )
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": 120005,
4
+ "pad_token_id": 120002,
5
+ "transformers_version": "4.52.4"
6
+ }
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_megrez_moe.py ADDED
@@ -0,0 +1,1110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 DeepSeek-AI 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 DeepSeek model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ )
38
+ from transformers.modeling_outputs import (
39
+ BaseModelOutputWithPast,
40
+ CausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import (
45
+ ALL_LAYERNORM_LAYERS,
46
+ is_torch_greater_or_equal_than_1_13,
47
+ )
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from transformers.utils.import_utils import is_torch_fx_available
57
+ from .configuration_megrez_moe import MegrezMoeConfig
58
+ import torch.distributed as dist
59
+ import numpy as np
60
+
61
+ from transformers.models.llama.modeling_llama import LlamaAttention, LlamaRotaryEmbedding
62
+
63
+ if is_flash_attn_2_available():
64
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
65
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
66
+
67
+
68
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
69
+ # It means that the function will not be traced through and simply appear as a node in the graph.
70
+ if is_torch_fx_available():
71
+ if not is_torch_greater_or_equal_than_1_13:
72
+ import torch.fx
73
+
74
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
75
+
76
+
77
+ logger = logging.get_logger(__name__)
78
+
79
+ _CONFIG_FOR_DOC = "MegrezMoeConfig"
80
+
81
+
82
+ def _get_unpad_data(attention_mask):
83
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
84
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
85
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
86
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+
94
+ class MegrezMoeRMSNorm(nn.Module):
95
+ def __init__(self, hidden_size, eps=1e-6):
96
+ """
97
+ MegrezMoeRMSNorm is equivalent to T5LayerNorm
98
+ """
99
+ super().__init__()
100
+ self.weight = nn.Parameter(torch.ones(hidden_size))
101
+ self.variance_epsilon = eps
102
+
103
+ def forward(self, hidden_states):
104
+ input_dtype = hidden_states.dtype
105
+ hidden_states = hidden_states.to(torch.float32)
106
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
107
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
108
+ return self.weight * hidden_states.to(input_dtype)
109
+
110
+
111
+ ALL_LAYERNORM_LAYERS.append(MegrezMoeRMSNorm)
112
+
113
+
114
+ class MegrezMoeMLP(nn.Module):
115
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
116
+ super().__init__()
117
+ self.config = config
118
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
119
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
120
+
121
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
122
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
123
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
124
+ self.act_fn = ACT2FN[config.hidden_act]
125
+
126
+ def forward(self, x):
127
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
128
+ return down_proj
129
+
130
+
131
+ class MoEGate(nn.Module):
132
+ def __init__(self, config):
133
+ super().__init__()
134
+ self.config = config
135
+ self.top_k = config.num_experts_per_tok
136
+ self.n_routed_experts = config.n_routed_experts
137
+ self.routed_scaling_factor = config.routed_scaling_factor
138
+ self.scoring_func = config.scoring_func
139
+ self.topk_method = config.topk_method
140
+ self.n_group = config.n_group
141
+ self.topk_group = config.topk_group
142
+
143
+ # topk selection algorithm
144
+ self.norm_topk_prob = config.norm_topk_prob
145
+ self.gating_dim = config.hidden_size
146
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
147
+ if self.topk_method == "noaux_tc":
148
+ self.e_score_correction_bias = nn.Parameter(
149
+ torch.empty((self.n_routed_experts))
150
+ )
151
+ self.reset_parameters()
152
+
153
+ def reset_parameters(self) -> None:
154
+ import torch.nn.init as init
155
+
156
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
157
+
158
+ def forward(self, hidden_states):
159
+ bsz, seq_len, h = hidden_states.shape
160
+ ### compute gating score
161
+ hidden_states = hidden_states.view(-1, h)
162
+ logits = F.linear(
163
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
164
+ )
165
+ if self.scoring_func == "sigmoid":
166
+ scores = logits.sigmoid()
167
+ else:
168
+ raise NotImplementedError(
169
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
170
+ )
171
+
172
+ ### select top-k experts
173
+ if self.topk_method == "noaux_tc":
174
+ assert not self.training
175
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
176
+ group_scores = (
177
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
178
+ ) # [n, n_group]
179
+ group_idx = torch.topk(
180
+ group_scores, k=self.topk_group, dim=-1, sorted=False
181
+ )[
182
+ 1
183
+ ] # [n, top_k_group]
184
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
185
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
186
+ score_mask = (
187
+ group_mask.unsqueeze(-1)
188
+ .expand(
189
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
190
+ )
191
+ .reshape(bsz * seq_len, -1)
192
+ ) # [n, e]
193
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), float("-inf")) # [n, e]
194
+ _, topk_idx = torch.topk(
195
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
196
+ )
197
+ topk_weight = scores.gather(1, topk_idx)
198
+ else:
199
+ raise NotImplementedError(
200
+ f"insupportable TopK function for MoE gating: {self.topk_method}"
201
+ )
202
+
203
+ ### norm gate to sum 1
204
+ if self.top_k > 1 and self.norm_topk_prob:
205
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
206
+ topk_weight = topk_weight / denominator
207
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
208
+
209
+ return topk_idx, topk_weight
210
+
211
+
212
+ class MegrezMoeMoE(nn.Module):
213
+ """
214
+ A mixed expert module containing shared experts.
215
+ """
216
+
217
+ def __init__(self, config, init_experts: bool = True):
218
+ super().__init__()
219
+ self.config = config
220
+ self.num_experts_per_tok = config.num_experts_per_tok
221
+
222
+ if hasattr(config, "ep_size") and config.ep_size > 1:
223
+ assert config.ep_size == dist.get_world_size()
224
+ self.ep_size = config.ep_size
225
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
226
+ self.ep_rank = dist.get_rank()
227
+ if init_experts:
228
+ self.experts = nn.ModuleList(
229
+ [
230
+ (
231
+ MegrezMoeMLP(config, intermediate_size=config.moe_intermediate_size)
232
+ if i >= self.ep_rank * self.experts_per_rank
233
+ and i < (self.ep_rank + 1) * self.experts_per_rank
234
+ else None
235
+ )
236
+ for i in range(config.n_routed_experts)
237
+ ]
238
+ )
239
+ else:
240
+ self.experts = None
241
+ else:
242
+ self.ep_size = 1
243
+ self.experts_per_rank = config.n_routed_experts
244
+ self.ep_rank = 0
245
+ if init_experts:
246
+ self.experts = nn.ModuleList(
247
+ [
248
+ MegrezMoeMLP(config, intermediate_size=config.moe_intermediate_size)
249
+ for i in range(config.n_routed_experts)
250
+ ]
251
+ )
252
+ else:
253
+ self.experts = None
254
+
255
+ self.gate = MoEGate(config)
256
+ if config.n_shared_experts is not None:
257
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
258
+ self.shared_experts = MegrezMoeMLP(config=config, intermediate_size=intermediate_size)
259
+
260
+ def set_experts(self, experts):
261
+ self.experts = experts
262
+
263
+ def forward(self, hidden_states, pre_gate_hidden_states=None):
264
+ identity = hidden_states
265
+ orig_shape = hidden_states.shape
266
+ if pre_gate_hidden_states is not None:
267
+ topk_idx, topk_weight = self.gate(pre_gate_hidden_states)
268
+ else:
269
+ topk_idx, topk_weight = self.gate(hidden_states)
270
+
271
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
272
+ flat_topk_idx = topk_idx.view(-1)
273
+ if self.training:
274
+ hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0)
275
+ y = torch.empty_like(hidden_states)
276
+ for i, expert in enumerate(self.experts):
277
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
278
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
279
+ y = y.to(hidden_states.dtype).view(*orig_shape)
280
+ else:
281
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
282
+ if self.config.n_shared_experts is not None:
283
+ y = y + self.shared_experts(identity)
284
+ return y
285
+
286
+ @torch.no_grad()
287
+ def moe_infer(self, x, topk_ids, topk_weight):
288
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
289
+ cnts.scatter_(1, topk_ids, 1)
290
+ tokens_per_expert = cnts.sum(dim=0)
291
+ idxs = topk_ids.view(-1).argsort()
292
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
293
+ sorted_tokens_shape = sorted_tokens.shape
294
+ if self.ep_size > 1:
295
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
296
+ tokens_per_expert_group = tokens_per_expert.new_empty(tokens_per_expert.shape[0])
297
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
298
+ output_splits = tokens_per_expert_group.view(self.ep_size, -1).sum(1).cpu().numpy().tolist()
299
+ gathered_tokens = sorted_tokens.new_empty(
300
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
301
+ )
302
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
303
+ dist.all_to_all(
304
+ list(gathered_tokens.split(output_splits)),
305
+ list(sorted_tokens.split(input_split_sizes)),
306
+ )
307
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(self.ep_size, self.experts_per_rank).sum(dim=0)
308
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
309
+ s = 0
310
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
311
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
312
+ s += k
313
+ gatherd_idxs = gatherd_idxs.argsort()
314
+ sorted_tokens = gathered_tokens[gatherd_idxs]
315
+ tokens_per_expert = tokens_per_expert_post_gather
316
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
317
+
318
+ outputs = []
319
+ start_idx = 0
320
+ for i, num_tokens in enumerate(tokens_per_expert):
321
+ end_idx = start_idx + num_tokens
322
+ if num_tokens == 0:
323
+ continue
324
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
325
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
326
+ expert_out = expert(tokens_for_this_expert)
327
+ outputs.append(expert_out)
328
+ start_idx = end_idx
329
+
330
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
331
+ if self.ep_size > 1:
332
+ new_x = torch.empty_like(outs)
333
+ new_x[gatherd_idxs] = outs
334
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
335
+ dist.all_to_all(
336
+ list(gathered_tokens.split(input_split_sizes)),
337
+ list(new_x.split(output_splits)),
338
+ )
339
+ outs = gathered_tokens
340
+
341
+ new_x = torch.empty_like(outs)
342
+ new_x[idxs] = outs
343
+ final_out = (
344
+ new_x.view(*topk_ids.shape, -1)
345
+ .type(topk_weight.dtype)
346
+ .mul_(topk_weight.unsqueeze(dim=-1))
347
+ .sum(dim=1)
348
+ .type(new_x.dtype)
349
+ )
350
+ return final_out
351
+
352
+
353
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
354
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
355
+ """
356
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
357
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
358
+ """
359
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
360
+ if n_rep == 1:
361
+ return hidden_states
362
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
363
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
364
+
365
+
366
+ class MegrezMoeDecoderLayer(nn.Module):
367
+ def __init__(self, config: MegrezMoeConfig, layer_idx: int):
368
+ super().__init__()
369
+ self.config = config
370
+ self.layer_number = layer_idx
371
+
372
+ self.experts_shared = config.experts_shared_frequency is not None and layer_idx >= self.config.first_k_dense_replace
373
+
374
+ self.pre_gate = config.pre_gate
375
+
376
+ self.hidden_size = config.hidden_size
377
+
378
+ is_moe = (
379
+ config.n_routed_experts is not None
380
+ and layer_idx >= config.first_k_dense_replace
381
+ and layer_idx % config.moe_layer_freq == 0
382
+ )
383
+
384
+ if self.experts_shared:
385
+ assert config.moe_layer_freq == 1
386
+ self.self_attn = torch.nn.ModuleList(
387
+ [LlamaAttention(config=config, layer_idx=layer_idx) for _ in range(config.experts_shared_frequency)]
388
+ )
389
+ for idx in range(config.experts_shared_frequency):
390
+ attn_layer_idx = (
391
+ layer_idx - self.config.first_k_dense_replace
392
+ ) * self.config.experts_shared_frequency + self.config.first_k_dense_replace + idx
393
+ self.self_attn[idx].layer_idx = attn_layer_idx
394
+ self.input_layernorm = torch.nn.ModuleList(
395
+ [
396
+ MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
397
+ for _ in range(config.experts_shared_frequency)
398
+ ]
399
+ )
400
+ self.post_attention_layernorm = torch.nn.ModuleList(
401
+ [
402
+ MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
403
+ for _ in range(config.experts_shared_frequency)
404
+ ]
405
+ )
406
+
407
+ mlp = [MegrezMoeMoE(config, init_experts=True)]
408
+ for _ in range(1, config.experts_shared_frequency):
409
+ layer = MegrezMoeMoE(config, init_experts=False)
410
+ # layer.set_experts(mlp[0].experts)
411
+ mlp.append(layer)
412
+ self.mlp = torch.nn.ModuleList(mlp)
413
+
414
+ else:
415
+
416
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
417
+
418
+ self.mlp = MegrezMoeMoE(config) if is_moe else MegrezMoeMLP(config)
419
+ self.input_layernorm = MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
420
+ self.post_attention_layernorm = MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
421
+
422
+ def forward(
423
+ self,
424
+ hidden_states: torch.Tensor,
425
+ attention_mask: Optional[torch.Tensor] = None,
426
+ position_ids: Optional[torch.LongTensor] = None,
427
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
428
+ output_attentions: Optional[bool] = False,
429
+ use_cache: Optional[bool] = False,
430
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
431
+ **kwargs,
432
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
433
+ """
434
+ Args:
435
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
436
+ attention_mask (`torch.FloatTensor`, *optional*):
437
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
438
+ query_sequence_length, key_sequence_length)` if default attention is used.
439
+ output_attentions (`bool`, *optional*):
440
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
441
+ returned tensors for more detail.
442
+ use_cache (`bool`, *optional*):
443
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
444
+ (see `past_key_values`).
445
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
446
+ """
447
+
448
+ if self.pre_gate and self.layer_number >= self.config.first_k_dense_replace:
449
+ hidden_states = torch.split(hidden_states, hidden_states.shape[0] // 2, dim=0)
450
+ pre_gate_hidden_states = hidden_states[0]
451
+ hidden_states = hidden_states[1]
452
+ else:
453
+ pre_gate_hidden_states = None
454
+
455
+ if "padding_mask" in kwargs:
456
+ warnings.warn(
457
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
458
+ )
459
+
460
+ if self.experts_shared:
461
+
462
+ for idx in range(self.config.experts_shared_frequency):
463
+ residual = hidden_states
464
+
465
+ hidden_states = self.input_layernorm[idx](hidden_states)
466
+
467
+ # Self Attention
468
+ hidden_states, self_attn_weights = self.self_attn[idx](
469
+ hidden_states=hidden_states,
470
+ attention_mask=attention_mask,
471
+ position_ids=position_ids,
472
+ past_key_value=past_key_value,
473
+ output_attentions=output_attentions,
474
+ use_cache=use_cache,
475
+ position_embeddings=position_embeddings,
476
+ **kwargs,
477
+ )
478
+ hidden_states = residual + hidden_states
479
+
480
+ # Fully Connected
481
+ residual = hidden_states
482
+ hidden_states = self.post_attention_layernorm[idx](hidden_states)
483
+ post_attention_layernorm_hidden_states = hidden_states
484
+ if idx > 0:
485
+ self.mlp[idx].set_experts(self.mlp[0].experts)
486
+ hidden_states = self.mlp[idx](hidden_states, pre_gate_hidden_states=pre_gate_hidden_states)
487
+ if idx > 0:
488
+ self.mlp[idx].set_experts(None)
489
+ hidden_states = residual + hidden_states
490
+ pre_gate_hidden_states = post_attention_layernorm_hidden_states
491
+
492
+ else:
493
+ residual = hidden_states
494
+
495
+ hidden_states = self.input_layernorm(hidden_states)
496
+
497
+ # Self Attention
498
+ hidden_states, self_attn_weights = self.self_attn(
499
+ hidden_states=hidden_states,
500
+ attention_mask=attention_mask,
501
+ position_ids=position_ids,
502
+ past_key_value=past_key_value,
503
+ output_attentions=output_attentions,
504
+ use_cache=use_cache,
505
+ position_embeddings=position_embeddings,
506
+ **kwargs,
507
+ )
508
+ hidden_states = residual + hidden_states
509
+
510
+ # Fully Connected
511
+ residual = hidden_states
512
+ hidden_states = self.post_attention_layernorm(hidden_states)
513
+ post_attention_layernorm_hidden_states = hidden_states
514
+ hidden_states = self.mlp(hidden_states)
515
+ hidden_states = residual + hidden_states
516
+ pre_gate_hidden_states = post_attention_layernorm_hidden_states
517
+
518
+ if self.pre_gate and self.layer_number < self.config.num_hidden_layers - 1:
519
+ hidden_states = torch.cat([pre_gate_hidden_states, hidden_states], dim=0)
520
+
521
+ outputs = (hidden_states,)
522
+
523
+ if output_attentions:
524
+ outputs += (self_attn_weights,)
525
+
526
+ return outputs
527
+
528
+
529
+ MegrezMoe_START_DOCSTRING = r"""
530
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
531
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
532
+ etc.)
533
+
534
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
535
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
536
+ and behavior.
537
+
538
+ Parameters:
539
+ config ([`MegrezMoeConfig`]):
540
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
541
+ load the weights associated with the model, only the configuration. Check out the
542
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
543
+ """
544
+
545
+
546
+ @add_start_docstrings(
547
+ "The bare MegrezMoe Model outputting raw hidden-states without any specific head on top.",
548
+ MegrezMoe_START_DOCSTRING,
549
+ )
550
+ class MegrezMoePreTrainedModel(PreTrainedModel):
551
+ config_class = MegrezMoeConfig
552
+ base_model_prefix = "model"
553
+ supports_gradient_checkpointing = True
554
+ _no_split_modules = ["MegrezMoeDecoderLayer"]
555
+ _skip_keys_device_placement = "past_key_values"
556
+ _supports_flash_attn_2 = True
557
+ _supports_cache_class = True
558
+
559
+ def _init_weights(self, module):
560
+ std = self.config.initializer_range
561
+ if isinstance(module, nn.Linear):
562
+ module.weight.data.normal_(mean=0.0, std=std)
563
+ if module.bias is not None:
564
+ module.bias.data.zero_()
565
+ elif isinstance(module, nn.Embedding):
566
+ module.weight.data.normal_(mean=0.0, std=std)
567
+ if module.padding_idx is not None:
568
+ module.weight.data[module.padding_idx].zero_()
569
+
570
+
571
+ MegrezMoe_INPUTS_DOCSTRING = r"""
572
+ Args:
573
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
574
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
575
+ it.
576
+
577
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
578
+ [`PreTrainedTokenizer.__call__`] for details.
579
+
580
+ [What are input IDs?](../glossary#input-ids)
581
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
582
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
583
+
584
+ - 1 for tokens that are **not masked**,
585
+ - 0 for tokens that are **masked**.
586
+
587
+ [What are attention masks?](../glossary#attention-mask)
588
+
589
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
590
+ [`PreTrainedTokenizer.__call__`] for details.
591
+
592
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
593
+ `past_key_values`).
594
+
595
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
596
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
597
+ information on the default strategy.
598
+
599
+ - 1 indicates the head is **not masked**,
600
+ - 0 indicates the head is **masked**.
601
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
602
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
603
+ config.n_positions - 1]`.
604
+
605
+ [What are position IDs?](../glossary#position-ids)
606
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
607
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
608
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
609
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
610
+
611
+ Two formats are allowed:
612
+ - a [`~cache_utils.Cache`] instance;
613
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
614
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
615
+ cache format.
616
+
617
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
618
+ legacy cache format will be returned.
619
+
620
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
621
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
622
+ of shape `(batch_size, sequence_length)`.
623
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
624
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
625
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
626
+ model's internal embedding lookup matrix.
627
+ use_cache (`bool`, *optional*):
628
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
629
+ `past_key_values`).
630
+ output_attentions (`bool`, *optional*):
631
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
632
+ tensors for more detail.
633
+ output_hidden_states (`bool`, *optional*):
634
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
635
+ more detail.
636
+ return_dict (`bool`, *optional*):
637
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
638
+ """
639
+
640
+
641
+ @add_start_docstrings(
642
+ "The bare MegrezMoe Model outputting raw hidden-states without any specific head on top.",
643
+ MegrezMoe_START_DOCSTRING,
644
+ )
645
+ class MegrezMoeModel(MegrezMoePreTrainedModel):
646
+ """
647
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MegrezMoeDecoderLayer`]
648
+
649
+ Args:
650
+ config: MegrezMoeConfig
651
+ """
652
+
653
+ def __init__(self, config: MegrezMoeConfig):
654
+ super().__init__(config)
655
+ self.padding_idx = config.pad_token_id
656
+ self.vocab_size = config.vocab_size
657
+
658
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
659
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
660
+ self.layers = nn.ModuleList(
661
+ [MegrezMoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
662
+ )
663
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
664
+ self.norm = MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
665
+
666
+ self.gradient_checkpointing = False
667
+ # Initialize weights and apply final processing
668
+ self.post_init()
669
+
670
+ def get_input_embeddings(self):
671
+ return self.embed_tokens
672
+
673
+ def set_input_embeddings(self, value):
674
+ self.embed_tokens = value
675
+
676
+ @add_start_docstrings_to_model_forward(MegrezMoe_INPUTS_DOCSTRING)
677
+ def forward(
678
+ self,
679
+ input_ids: torch.LongTensor = None,
680
+ attention_mask: Optional[torch.Tensor] = None,
681
+ position_ids: Optional[torch.LongTensor] = None,
682
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
683
+ inputs_embeds: Optional[torch.FloatTensor] = None,
684
+ use_cache: Optional[bool] = None,
685
+ output_attentions: Optional[bool] = None,
686
+ output_hidden_states: Optional[bool] = None,
687
+ **flash_attn_kwargs,
688
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
689
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
690
+ output_hidden_states = (
691
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
692
+ )
693
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
694
+
695
+ # retrieve input_ids and inputs_embeds
696
+ if input_ids is not None and inputs_embeds is not None:
697
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
698
+ elif input_ids is not None:
699
+ batch_size, seq_length = input_ids.shape[:2]
700
+ elif inputs_embeds is not None:
701
+ batch_size, seq_length = inputs_embeds.shape[:2]
702
+ else:
703
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
704
+
705
+ if self.gradient_checkpointing and self.training:
706
+ if use_cache:
707
+ logger.warning_once(
708
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
709
+ )
710
+ use_cache = False
711
+
712
+ past_key_values_length = 0
713
+ if use_cache:
714
+ use_legacy_cache = not isinstance(past_key_values, Cache)
715
+ if use_legacy_cache:
716
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
717
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
718
+
719
+ if position_ids is None:
720
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
721
+ position_ids = torch.arange(
722
+ past_key_values_length,
723
+ seq_length + past_key_values_length,
724
+ dtype=torch.long,
725
+ device=device,
726
+ )
727
+ position_ids = position_ids.unsqueeze(0)
728
+
729
+ if inputs_embeds is None:
730
+ inputs_embeds = self.embed_tokens(input_ids)
731
+
732
+ if self._use_flash_attention_2:
733
+ # 2d mask is passed through the layers
734
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
735
+ else:
736
+ # 4d mask is passed through the layers
737
+ attention_mask = _prepare_4d_causal_attention_mask(
738
+ attention_mask,
739
+ (batch_size, seq_length),
740
+ inputs_embeds,
741
+ past_key_values_length,
742
+ )
743
+
744
+ # embed positions
745
+ hidden_states = inputs_embeds
746
+
747
+ # decoder layers
748
+ all_hidden_states = () if output_hidden_states else None
749
+ all_self_attns = () if output_attentions else None
750
+ next_decoder_cache = None
751
+
752
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
753
+
754
+ for decoder_layer in self.layers:
755
+ if output_hidden_states:
756
+ all_hidden_states += (hidden_states,)
757
+
758
+ if self.gradient_checkpointing and self.training:
759
+ layer_outputs = self._gradient_checkpointing_func(
760
+ decoder_layer.__call__,
761
+ hidden_states,
762
+ attention_mask,
763
+ position_ids,
764
+ past_key_values,
765
+ output_attentions,
766
+ use_cache,
767
+ position_embeddings,
768
+ **flash_attn_kwargs,
769
+ )
770
+ else:
771
+ layer_outputs = decoder_layer(
772
+ hidden_states,
773
+ attention_mask=attention_mask,
774
+ position_ids=position_ids,
775
+ past_key_value=past_key_values,
776
+ output_attentions=output_attentions,
777
+ use_cache=use_cache,
778
+ position_embeddings=position_embeddings,
779
+ **flash_attn_kwargs,
780
+ )
781
+
782
+ hidden_states = layer_outputs[0]
783
+
784
+ if output_attentions:
785
+ all_self_attns += (layer_outputs[1],)
786
+
787
+ hidden_states = self.norm(hidden_states)
788
+
789
+ # add hidden states from the last decoder layer
790
+ if output_hidden_states:
791
+ all_hidden_states += (hidden_states,)
792
+
793
+ return BaseModelOutputWithPast(
794
+ last_hidden_state=hidden_states,
795
+ past_key_values=past_key_values,
796
+ hidden_states=all_hidden_states,
797
+ attentions=all_self_attns,
798
+ )
799
+
800
+
801
+ class MegrezMoeForCausalLM(MegrezMoePreTrainedModel):
802
+ _tied_weights_keys = ["lm_head.weight"]
803
+
804
+ def __init__(self, config):
805
+ super().__init__(config)
806
+ self.model = MegrezMoeModel(config)
807
+ self.vocab_size = config.vocab_size
808
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
809
+
810
+ # Initialize weights and apply final processing
811
+ self.post_init()
812
+
813
+ def get_input_embeddings(self):
814
+ return self.model.embed_tokens
815
+
816
+ def set_input_embeddings(self, value):
817
+ self.model.embed_tokens = value
818
+
819
+ def get_output_embeddings(self):
820
+ return self.lm_head
821
+
822
+ def set_output_embeddings(self, new_embeddings):
823
+ self.lm_head = new_embeddings
824
+
825
+ def set_decoder(self, decoder):
826
+ self.model = decoder
827
+
828
+ def get_decoder(self):
829
+ return self.model
830
+
831
+ @add_start_docstrings_to_model_forward(MegrezMoe_INPUTS_DOCSTRING)
832
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
833
+ def forward(
834
+ self,
835
+ input_ids: torch.LongTensor = None,
836
+ attention_mask: Optional[torch.Tensor] = None,
837
+ position_ids: Optional[torch.LongTensor] = None,
838
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
839
+ inputs_embeds: Optional[torch.FloatTensor] = None,
840
+ labels: Optional[torch.LongTensor] = None,
841
+ use_cache: Optional[bool] = None,
842
+ output_attentions: Optional[bool] = None,
843
+ output_hidden_states: Optional[bool] = None,
844
+ return_dict: Optional[bool] = None,
845
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
846
+ r"""
847
+ Args:
848
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
849
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
850
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
851
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
852
+
853
+ Returns:
854
+
855
+ Example:
856
+
857
+ ```python
858
+ >>> from transformers import AutoTokenizer, MegrezMoeForCausalLM
859
+
860
+ >>> model = MegrezMoeForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
861
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
862
+
863
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
864
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
865
+
866
+ >>> # Generate
867
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
868
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
869
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
870
+ ```"""
871
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
872
+ output_hidden_states = (
873
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
874
+ )
875
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
876
+
877
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
878
+ outputs = self.model(
879
+ input_ids=input_ids,
880
+ attention_mask=attention_mask,
881
+ position_ids=position_ids,
882
+ past_key_values=past_key_values,
883
+ inputs_embeds=inputs_embeds,
884
+ use_cache=use_cache,
885
+ output_attentions=output_attentions,
886
+ output_hidden_states=output_hidden_states,
887
+ return_dict=return_dict,
888
+ )
889
+
890
+ hidden_states = outputs[0]
891
+ logits = self.lm_head(hidden_states)
892
+ logits = logits.float()
893
+
894
+ loss = None
895
+ if labels is not None:
896
+ # Shift so that tokens < n predict n
897
+ shift_logits = logits[..., :-1, :].contiguous()
898
+ shift_labels = labels[..., 1:].contiguous()
899
+ # Flatten the tokens
900
+ loss_fct = CrossEntropyLoss()
901
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
902
+ shift_labels = shift_labels.view(-1)
903
+ # Enable model parallelism
904
+ shift_labels = shift_labels.to(shift_logits.device)
905
+ loss = loss_fct(shift_logits, shift_labels)
906
+
907
+ if not return_dict:
908
+ output = (logits,) + outputs[1:]
909
+ return (loss,) + output if loss is not None else output
910
+
911
+ return CausalLMOutputWithPast(
912
+ loss=loss,
913
+ logits=logits,
914
+ past_key_values=outputs.past_key_values,
915
+ hidden_states=outputs.hidden_states,
916
+ attentions=outputs.attentions,
917
+ )
918
+
919
+ def prepare_inputs_for_generation(
920
+ self,
921
+ input_ids,
922
+ past_key_values=None,
923
+ attention_mask=None,
924
+ inputs_embeds=None,
925
+ **kwargs,
926
+ ):
927
+ if past_key_values is not None:
928
+ if isinstance(past_key_values, Cache):
929
+ cache_length = past_key_values.get_seq_length()
930
+ past_length = past_key_values.seen_tokens
931
+ # max_cache_length = past_key_values.get_max_length()
932
+ max_cache_length = past_key_values.get_max_cache_shape()
933
+ else:
934
+ cache_length = past_length = past_key_values[0][0].shape[2]
935
+ max_cache_length = None
936
+
937
+ # Keep only the unprocessed tokens:
938
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
939
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
940
+ # input)
941
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
942
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
943
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
944
+ # input_ids based on the past_length.
945
+ elif past_length < input_ids.shape[1]:
946
+ input_ids = input_ids[:, past_length:]
947
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
948
+
949
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
950
+ if (
951
+ max_cache_length is not None
952
+ and attention_mask is not None
953
+ and cache_length + input_ids.shape[1] > max_cache_length
954
+ ):
955
+ attention_mask = attention_mask[:, -max_cache_length:]
956
+
957
+ position_ids = kwargs.get("position_ids", None)
958
+ if attention_mask is not None and position_ids is None:
959
+ # create position_ids on the fly for batch generation
960
+ position_ids = attention_mask.long().cumsum(-1) - 1
961
+ position_ids.masked_fill_(attention_mask == 0, 1)
962
+ if past_key_values:
963
+ position_ids = position_ids[:, -input_ids.shape[1] :]
964
+
965
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
966
+ if inputs_embeds is not None and past_key_values is None:
967
+ model_inputs = {"inputs_embeds": inputs_embeds}
968
+ else:
969
+ model_inputs = {"input_ids": input_ids}
970
+
971
+ model_inputs.update(
972
+ {
973
+ "position_ids": position_ids,
974
+ "past_key_values": past_key_values,
975
+ "use_cache": kwargs.get("use_cache"),
976
+ "attention_mask": attention_mask,
977
+ }
978
+ )
979
+ return model_inputs
980
+
981
+ @staticmethod
982
+ def _reorder_cache(past_key_values, beam_idx):
983
+ reordered_past = ()
984
+ for layer_past in past_key_values:
985
+ reordered_past += (
986
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
987
+ )
988
+ return reordered_past
989
+
990
+
991
+ @add_start_docstrings(
992
+ """
993
+ The MegrezMoe Model transformer with a sequence classification head on top (linear layer).
994
+
995
+ [`MegrezMoeForSequenceClassification`] uses the last token in order to do the classification, as other causal models
996
+ (e.g. GPT-2) do.
997
+
998
+ Since it does classification on the last token, it requires to know the position of the last token. If a
999
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1000
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1001
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1002
+ each row of the batch).
1003
+ """,
1004
+ MegrezMoe_START_DOCSTRING,
1005
+ )
1006
+ class MegrezMoeForSequenceClassification(MegrezMoePreTrainedModel):
1007
+ def __init__(self, config):
1008
+ super().__init__(config)
1009
+ self.num_labels = config.num_labels
1010
+ self.model = MegrezMoeModel(config)
1011
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1012
+
1013
+ # Initialize weights and apply final processing
1014
+ self.post_init()
1015
+
1016
+ def get_input_embeddings(self):
1017
+ return self.model.embed_tokens
1018
+
1019
+ def set_input_embeddings(self, value):
1020
+ self.model.embed_tokens = value
1021
+
1022
+ @add_start_docstrings_to_model_forward(MegrezMoe_INPUTS_DOCSTRING)
1023
+ def forward(
1024
+ self,
1025
+ input_ids: torch.LongTensor = None,
1026
+ attention_mask: Optional[torch.Tensor] = None,
1027
+ position_ids: Optional[torch.LongTensor] = None,
1028
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1029
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1030
+ labels: Optional[torch.LongTensor] = None,
1031
+ use_cache: Optional[bool] = None,
1032
+ output_attentions: Optional[bool] = None,
1033
+ output_hidden_states: Optional[bool] = None,
1034
+ return_dict: Optional[bool] = None,
1035
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1036
+ r"""
1037
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1038
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1039
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1040
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1041
+ """
1042
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1043
+
1044
+ transformer_outputs = self.model(
1045
+ input_ids,
1046
+ attention_mask=attention_mask,
1047
+ position_ids=position_ids,
1048
+ past_key_values=past_key_values,
1049
+ inputs_embeds=inputs_embeds,
1050
+ use_cache=use_cache,
1051
+ output_attentions=output_attentions,
1052
+ output_hidden_states=output_hidden_states,
1053
+ return_dict=return_dict,
1054
+ )
1055
+ hidden_states = transformer_outputs[0]
1056
+ logits = self.score(hidden_states)
1057
+
1058
+ if input_ids is not None:
1059
+ batch_size = input_ids.shape[0]
1060
+ else:
1061
+ batch_size = inputs_embeds.shape[0]
1062
+
1063
+ if self.config.pad_token_id is None and batch_size != 1:
1064
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1065
+ if self.config.pad_token_id is None:
1066
+ sequence_lengths = -1
1067
+ else:
1068
+ if input_ids is not None:
1069
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1070
+ logits.device
1071
+ )
1072
+ else:
1073
+ sequence_lengths = -1
1074
+
1075
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1076
+
1077
+ loss = None
1078
+ if labels is not None:
1079
+ labels = labels.to(logits.device)
1080
+ if self.config.problem_type is None:
1081
+ if self.num_labels == 1:
1082
+ self.config.problem_type = "regression"
1083
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1084
+ self.config.problem_type = "single_label_classification"
1085
+ else:
1086
+ self.config.problem_type = "multi_label_classification"
1087
+
1088
+ if self.config.problem_type == "regression":
1089
+ loss_fct = MSELoss()
1090
+ if self.num_labels == 1:
1091
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1092
+ else:
1093
+ loss = loss_fct(pooled_logits, labels)
1094
+ elif self.config.problem_type == "single_label_classification":
1095
+ loss_fct = CrossEntropyLoss()
1096
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1097
+ elif self.config.problem_type == "multi_label_classification":
1098
+ loss_fct = BCEWithLogitsLoss()
1099
+ loss = loss_fct(pooled_logits, labels)
1100
+ if not return_dict:
1101
+ output = (pooled_logits,) + transformer_outputs[1:]
1102
+ return ((loss,) + output) if loss is not None else output
1103
+
1104
+ return SequenceClassifierOutputWithPast(
1105
+ loss=loss,
1106
+ logits=pooled_logits,
1107
+ past_key_values=transformer_outputs.past_key_values,
1108
+ hidden_states=transformer_outputs.hidden_states,
1109
+ attentions=transformer_outputs.attentions,
1110
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "eos_token": {
3
+ "content": "<|turn_end|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "pad_token": {
10
+ "content": "<|pad|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ }
16
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "added_tokens_decoder": {
4
+ "120000": {
5
+ "content": "<|eos|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "120001": {
13
+ "content": "<|unk|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "120002": {
21
+ "content": "<|pad|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "120003": {
29
+ "content": "<|role_start|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "120004": {
37
+ "content": "<|role_end|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "120005": {
45
+ "content": "<|turn_end|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "120006": {
53
+ "content": "<|code_start|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "120007": {
61
+ "content": "<|code_end|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "120008": {
69
+ "content": "<|commit_start|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "120009": {
77
+ "content": "<|commit_end|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "120010": {
85
+ "content": "<|diff_start|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "120011": {
93
+ "content": "<|diff_end|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "120012": {
101
+ "content": "<|code_execution_start|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "120013": {
109
+ "content": "<|code_execution_end|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ },
116
+ "120014": {
117
+ "content": "<|image_start|>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": true
123
+ },
124
+ "120015": {
125
+ "content": "<|image_end|>",
126
+ "lstrip": false,
127
+ "normalized": false,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": true
131
+ },
132
+ "120016": {
133
+ "content": "<|image_pad|>",
134
+ "lstrip": false,
135
+ "normalized": false,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": true
139
+ },
140
+ "120017": {
141
+ "content": "<|video_start|>",
142
+ "lstrip": false,
143
+ "normalized": false,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": true
147
+ },
148
+ "120018": {
149
+ "content": "<|video_end|>",
150
+ "lstrip": false,
151
+ "normalized": false,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": true
155
+ },
156
+ "120019": {
157
+ "content": "<|video_pad|>",
158
+ "lstrip": false,
159
+ "normalized": false,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": true
163
+ },
164
+ "120020": {
165
+ "content": "<|audio_start|>",
166
+ "lstrip": false,
167
+ "normalized": false,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": true
171
+ },
172
+ "120021": {
173
+ "content": "<|audio_end|>",
174
+ "lstrip": false,
175
+ "normalized": false,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": true
179
+ },
180
+ "120022": {
181
+ "content": "<|audio_pad|>",
182
+ "lstrip": false,
183
+ "normalized": false,
184
+ "rstrip": false,
185
+ "single_word": false,
186
+ "special": true
187
+ },
188
+ "120023": {
189
+ "content": "<|function_start|>",
190
+ "lstrip": false,
191
+ "normalized": false,
192
+ "rstrip": false,
193
+ "single_word": false,
194
+ "special": true
195
+ },
196
+ "120024": {
197
+ "content": "<|function_end|>",
198
+ "lstrip": false,
199
+ "normalized": false,
200
+ "rstrip": false,
201
+ "single_word": false,
202
+ "special": true
203
+ },
204
+ "120025": {
205
+ "content": "<|turn_end>",
206
+ "lstrip": false,
207
+ "normalized": false,
208
+ "rstrip": false,
209
+ "single_word": false,
210
+ "special": true
211
+ },
212
+ "120026": {
213
+ "content": "<think>",
214
+ "lstrip": false,
215
+ "normalized": false,
216
+ "rstrip": false,
217
+ "single_word": false,
218
+ "special": true
219
+ },
220
+ "120027": {
221
+ "content": "</think>",
222
+ "lstrip": false,
223
+ "normalized": false,
224
+ "rstrip": false,
225
+ "single_word": false,
226
+ "special": true
227
+ }
228
+ },
229
+ "clean_up_tokenization_spaces": true,
230
+ "eos_token": "<|turn_end|>",
231
+ "extra_special_tokens": {},
232
+ "model_max_length": 32768,
233
+ "pad_token": "<|pad|>",
234
+ "padding_side": "right",
235
+ "tokenizer_class": "PreTrainedTokenizer"
236
+ }