ehartford commited on
Commit
8df5c69
·
verified ·
1 Parent(s): ad2caa6

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. LICENSE +27 -0
  3. README.md +801 -0
  4. THIRD_PARTY_NOTICES.md +47 -0
  5. config.json +60 -0
  6. configuration_deepseek.py +212 -0
  7. docs/deploy_guidance.md +196 -0
  8. docs/tool_call_guidance.md +241 -0
  9. figures/Base-Evaluation.png +3 -0
  10. figures/banner.png +3 -0
  11. figures/kimi-logo.png +0 -0
  12. generation_config.json +4 -0
  13. kimi-logo.png +0 -0
  14. model-1-of-61.safetensors +3 -0
  15. model-10-of-61.safetensors +3 -0
  16. model-11-of-61.safetensors +3 -0
  17. model-12-of-61.safetensors +3 -0
  18. model-14-of-61.safetensors +3 -0
  19. model-17-of-61.safetensors +3 -0
  20. model-19-of-61.safetensors +3 -0
  21. model-20-of-61.safetensors +3 -0
  22. model-22-of-61.safetensors +3 -0
  23. model-23-of-61.safetensors +3 -0
  24. model-25-of-61.safetensors +3 -0
  25. model-28-of-61.safetensors +3 -0
  26. model-31-of-61.safetensors +3 -0
  27. model-32-of-61.safetensors +3 -0
  28. model-34-of-61.safetensors +3 -0
  29. model-35-of-61.safetensors +3 -0
  30. model-36-of-61.safetensors +3 -0
  31. model-40-of-61.safetensors +3 -0
  32. model-43-of-61.safetensors +3 -0
  33. model-45-of-61.safetensors +3 -0
  34. model-48-of-61.safetensors +3 -0
  35. model-49-of-61.safetensors +3 -0
  36. model-5-of-61.safetensors +3 -0
  37. model-51-of-61.safetensors +3 -0
  38. model-52-of-61.safetensors +3 -0
  39. model-53-of-61.safetensors +3 -0
  40. model-54-of-61.safetensors +3 -0
  41. model-58-of-61.safetensors +3 -0
  42. model-59-of-61.safetensors +3 -0
  43. model-6-of-61.safetensors +3 -0
  44. model-7-of-61.safetensors +3 -0
  45. model-8-of-61.safetensors +3 -0
  46. model.safetensors.index.json +0 -0
  47. modeling_deepseek.py +1849 -0
  48. tiktoken.model +3 -0
  49. tokenization_kimi.py +323 -0
  50. tokenizer_config.json +165 -0
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
37
+ figures/Base-Evaluation.png filter=lfs diff=lfs merge=lfs -text
38
+ banner.png filter=lfs diff=lfs merge=lfs -text
39
+ figures/banner.png filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Modified MIT License
2
+
3
+ Copyright (c) 2025 Moonshot AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the “Software”), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ Our only modification part is that, if the Software (or any derivative works
24
+ thereof) is used for any of your commercial products or services that have
25
+ more than 100 million monthly active users, or more than 20 million US dollars
26
+ (or equivalent in other currencies) in monthly revenue, you shall prominently
27
+ display "Kimi K2" on the user interface of such product or service.
README.md ADDED
@@ -0,0 +1,801 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: modified-mit
4
+ library_name: transformers
5
+ ---
6
+ <div align="center">
7
+ <picture>
8
+ <img src="figures/kimi-logo.png" width="30%" alt="Kimi K2: Open Agentic Intellignece">
9
+ </picture>
10
+ </div>
11
+
12
+ <hr>
13
+
14
+ <div align="center" style="line-height:1">
15
+ <a href="https://www.kimi.com" target="_blank"><img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-Kimi%20K2-ff6b6b?color=1783ff&logoColor=white"/></a>
16
+ <a href="https://github.com/moonshotai/Kimi-K2"><img alt="github" src="https://img.shields.io/badge/🤖%20Github-Kimi%20K2-ff6b6b?color=1783ff&logoColor=white"/></a>
17
+ <a href="https://www.moonshot.ai" target="_blank"><img alt="Homepage" src="https://img.shields.io/badge/Homepage-Moonshot%20AI-white?logo=Kimi&logoColor=white"/></a>
18
+ </div>
19
+
20
+ <div align="center" style="line-height: 1;">
21
+ <a href="https://huggingface.co/moonshotai" target="_blank"><img alt="Hugging Face" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Moonshot%20AI-ffc107?color=ffc107&logoColor=white"/></a>
22
+ <a href="https://twitter.com/kimi_moonshot" target="_blank"><img alt="Twitter Follow" src="https://img.shields.io/badge/Twitter-Kimi.ai-white?logo=x&logoColor=white"/></a>
23
+ <a href="https://discord.gg/TYU2fdJykW" target="_blank"><img alt="Discord" src="https://img.shields.io/badge/Discord-Kimi.ai-white?logo=discord&logoColor=white"/></a>
24
+ </div>
25
+
26
+ <div align="center" style="line-height: 1;">
27
+ <a href="https://github.com/moonshotai/Kimi-K2/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Modified_MIT-f5de53?&color=f5de53"/></a>
28
+ </div>
29
+
30
+ <p align="center">
31
+ <b>📰&nbsp;&nbsp;<a href="https://moonshotai.github.io/Kimi-K2/">Tech Blog</a></b> &nbsp;&nbsp;&nbsp; | &nbsp;&nbsp;&nbsp; <b>📄&nbsp;&nbsp;Paper Link (coming soon)</b>
32
+ </p>
33
+
34
+ ## 0. Changelog
35
+
36
+ ### 2025.7.15
37
+ - We have updated our tokenizer implementation. Now special tokens like `[EOS]` can be encoded to their token ids.
38
+ - We fixed a bug in the chat template that was breaking multi-turn tool calls.
39
+
40
+ ## 1. Model Introduction
41
+
42
+ Kimi K2 is a state-of-the-art mixture-of-experts (MoE) language model with 32 billion activated parameters and 1 trillion total parameters. Trained with the Muon optimizer, Kimi K2 achieves exceptional performance across frontier knowledge, reasoning, and coding tasks while being meticulously optimized for agentic capabilities.
43
+
44
+ ### Key Features
45
+ - Large-Scale Training: Pre-trained a 1T parameter MoE model on 15.5T tokens with zero training instability.
46
+ - MuonClip Optimizer: We apply the Muon optimizer to an unprecedented scale, and develop novel optimization techniques to resolve instabilities while scaling up.
47
+ - Agentic Intelligence: Specifically designed for tool use, reasoning, and autonomous problem-solving.
48
+
49
+ ### Model Variants
50
+ - **Kimi-K2-Base**: The foundation model, a strong start for researchers and builders who want full control for fine-tuning and custom solutions.
51
+ - **Kimi-K2-Instruct**: The post-trained model best for drop-in, general-purpose chat and agentic experiences. It is a reflex-grade model without long thinking.
52
+
53
+ <div align="center">
54
+ <picture>
55
+ <img src="figures/banner.png" width="80%" alt="Evaluation Results">
56
+ </picture>
57
+ </div>
58
+
59
+ ## 2. Model Summary
60
+
61
+ <div align="center">
62
+
63
+
64
+ | | |
65
+ |:---:|:---:|
66
+ | **Architecture** | Mixture-of-Experts (MoE) |
67
+ | **Total Parameters** | 1T |
68
+ | **Activated Parameters** | 32B |
69
+ | **Number of Layers** (Dense layer included) | 61 |
70
+ | **Number of Dense Layers** | 1 |
71
+ | **Attention Hidden Dimension** | 7168 |
72
+ | **MoE Hidden Dimension** (per Expert) | 2048 |
73
+ | **Number of Attention Heads** | 64 |
74
+ | **Number of Experts** | 384 |
75
+ | **Selected Experts per Token** | 8 |
76
+ | **Number of Shared Experts** | 1 |
77
+ | **Vocabulary Size** | 160K |
78
+ | **Context Length** | 128K |
79
+ | **Attention Mechanism** | MLA |
80
+ | **Activation Function** | SwiGLU |
81
+ </div>
82
+
83
+ ## 3. Evaluation Results
84
+
85
+ #### Instruction model evaluation results
86
+
87
+ <div align="center">
88
+ <table>
89
+ <thead>
90
+ <tr>
91
+ <th align="center">Benchmark</th>
92
+ <th align="center">Metric</th>
93
+ <th align="center"><sup>Kimi K2 Instruct</sup></th>
94
+ <th align="center"><sup>DeepSeek-V3-0324</sup></th>
95
+ <th align="center"><sup>Qwen3-235B-A22B <br><sup>(non-thinking)</sup></sup></th>
96
+ <th align="center"><sup>Claude Sonnet 4 <br><sup>(w/o extended thinking)</sup></sup></th>
97
+ <th align="center"><sup>Claude Opus 4 <br><sup>(w/o extended thinking)</sup></sup></th>
98
+ <th align="center"><sup>GPT-4.1</sup></th>
99
+ <th align="center"><sup>Gemini 2.5 Flash <br> Preview (05-20)</sup></th>
100
+ </tr>
101
+ </thead>
102
+ <tbody>
103
+ <tr>
104
+ <td align="center" colspan=9><strong>Coding Tasks</strong></td>
105
+ </tr>
106
+ <tr>
107
+ <td align="center">LiveCodeBench v6<br><sup>(Aug 24 - May 25)</sup></td>
108
+ <td align="center">Pass@1</td>
109
+ <td align="center"><strong>53.7</strong></td>
110
+ <td align="center">46.9</td>
111
+ <td align="center">37.0</td>
112
+ <td align="center">48.5</td>
113
+ <td align="center">47.4</td>
114
+ <td align="center">44.7</td>
115
+ <td align="center">44.7</td>
116
+ </tr>
117
+ <tr>
118
+ <td align="center">OJBench</td>
119
+ <td align="center">Pass@1</td>
120
+ <td align="center"><strong>27.1</strong></td>
121
+ <td align="center">24.0</td>
122
+ <td align="center">11.3</td>
123
+ <td align="center">15.3</td>
124
+ <td align="center">19.6</td>
125
+ <td align="center">19.5</td>
126
+ <td align="center">19.5</td>
127
+ </tr>
128
+
129
+ <tr>
130
+ <td align="center">MultiPL-E</td>
131
+ <td align="center">Pass@1</td>
132
+ <td align="center"><ins><strong>85.7</strong></ins></td>
133
+ <td align="center">83.1</td>
134
+ <td align="center">78.2</td>
135
+ <td align="center">88.6</td>
136
+ <td align="center"><strong>89.6</strong></td>
137
+ <td align="center">86.7</td>
138
+ <td align="center">85.6</td>
139
+ </tr>
140
+
141
+ <tr>
142
+ <td align="center">SWE-bench Verified <br/><sup>(Agentless Coding)</sup></td>
143
+ <td align="center">Single Patch w/o Test (Acc)</td>
144
+ <td align="center"><ins><strong>51.8</strong></ins></td>
145
+ <td align="center">36.6</td>
146
+ <td align="center">39.4</td>
147
+ <td align="center">50.2</td>
148
+ <td align="center"><strong>53.0</strong></td>
149
+ <td align="center">40.8</td>
150
+ <td align="center">32.6</td>
151
+ </tr>
152
+
153
+ <tr>
154
+ <td align="center" rowspan="2">SWE-bench Verified <br/> <sup>(Agentic Coding)</sup></td>
155
+ <td align="center">Single Attempt (Acc)</td>
156
+ <td align="center"><ins><strong>65.8</strong></ins></td>
157
+ <td align="center">38.8</td>
158
+ <td align="center">34.4</td>
159
+ <td align="center"><strong>72.7</strong><sup>*</sup></td>
160
+ <td align="center">72.5<sup>*</sup></td>
161
+ <td align="center">54.6</td>
162
+ <td align="center">—</td>
163
+ </tr>
164
+
165
+ <tr>
166
+ <!--<td align="center">(Agentic Coding)</td>-->
167
+ <td align="center">Multiple Attempts (Acc)</td>
168
+ <td align="center"><ins><strong>71.6</strong></ins></td>
169
+ <td align="center">—</td>
170
+ <td align="center">—</td>
171
+ <td align="center"><strong>80.2</strong></td>
172
+ <td align="center">79.4<sup>*</sup></td>
173
+ <td align="center">—</td>
174
+ <td align="center">—</td>
175
+ </tr>
176
+
177
+ <tr>
178
+ <td align="center">SWE-bench Multilingual<br /> <sup>(Agentic Coding)</sup></td>
179
+ <td align="center">Single Attempt (Acc)</td>
180
+ <td align="center"><ins><strong>47.3</strong> </ins></td>
181
+ <td align="center">25.8</td>
182
+ <td align="center">20.9</td>
183
+ <td align="center"><strong>51.0</strong></td>
184
+ <td align="center">—</td>
185
+ <td align="center">31.5</td>
186
+ <td align="center">—</td>
187
+ </tr>
188
+
189
+ <tr>
190
+ <td align="center" rowspan="2">TerminalBench</td>
191
+ <td align="center">Inhouse Framework (Acc)</td>
192
+ <td align="center"><ins><strong>30.0</strong></ins></td>
193
+ <td align="center">—</td>
194
+ <td align="center">—</td>
195
+ <td align="center">35.5</td>
196
+ <td align="center"><strong>43.2</strong></td>
197
+ <td align="center">8.3</td>
198
+ <td align="center">—</td>
199
+ </tr>
200
+
201
+ <tr>
202
+ <!--<td align="center">TerminalBench</td>-->
203
+ <td align="center">Terminus (Acc)</td>
204
+ <td align="center"><ins><strong>25.0</strong> </ins></td>
205
+ <td align="center">16.3</td>
206
+ <td align="center">6.6</td>
207
+ <td align="center">—</td>
208
+ <td align="center">—</td>
209
+ <td align="center"><strong>30.3</strong></td>
210
+ <td align="center">16.8</td>
211
+ </tr>
212
+ <tr>
213
+ <td align="center">Aider-Polyglot</td>
214
+ <td align="center">Acc</td>
215
+ <td align="center">60.0</td>
216
+ <td align="center">55.1</td>
217
+ <td align="center"><ins><strong>61.8</strong></ins></td>
218
+ <td align="center">56.4</td>
219
+ <td align="center"><strong>70.7</strong></td>
220
+ <td align="center">52.4</td>
221
+ <td align="center">44.0</td>
222
+ </tr>
223
+ <tr>
224
+ <td align="center" colspan=9><strong>Tool Use Tasks</strong></td>
225
+ </tr>
226
+ <tr>
227
+ <td align="center">Tau2 retail</td>
228
+ <td align="center">Avg@4</td>
229
+ <td align="center"><ins><strong>70.6</strong></ins></td>
230
+ <td align="center">69.1</td>
231
+ <td align="center">57.0</td>
232
+ <td align="center">75.0</td>
233
+ <td align="center"><strong>81.8</strong></td>
234
+ <td align="center">74.8</td>
235
+ <td align="center">64.3</td>
236
+ </tr>
237
+ <tr>
238
+ <td align="center">Tau2 airline</td>
239
+ <td align="center">Avg@4</td>
240
+ <td align="center"><ins><strong>56.5</strong></ins></td>
241
+ <td align="center">39.0</td>
242
+ <td align="center">26.5</td>
243
+ <td align="center">55.5</td>
244
+ <td align="center"><strong>60.0</strong></td>
245
+ <td align="center">54.5</td>
246
+ <td align="center">42.5</td>
247
+ </tr>
248
+ <tr>
249
+ <td align="center">Tau2 telecom</td>
250
+ <td align="center">Avg@4</td>
251
+ <td align="center"><strong>65.8</strong></td>
252
+ <td align="center">32.5</td>
253
+ <td align="center">22.1</td>
254
+ <td align="center">45.2</td>
255
+ <td align="center">57.0</td>
256
+ <td align="center">38.6</td>
257
+ <td align="center">16.9</td>
258
+ </tr>
259
+ <tr>
260
+ <td align="center">AceBench</td>
261
+ <td align="center">Acc</td>
262
+ <td align="center"><ins><strong>76.5</strong></ins></td>
263
+ <td align="center">72.7</td>
264
+ <td align="center">70.5</td>
265
+ <td align="center">76.2</td>
266
+ <td align="center">75.6</td>
267
+ <td align="center"><strong>80.1</strong></td>
268
+ <td align="center">74.5</td>
269
+ </tr>
270
+ <tr>
271
+ <td align="center" colspan=9><strong>Math &amp; STEM Tasks</strong></td>
272
+ </tr>
273
+ <tr>
274
+ <td align="center">AIME 2024</td>
275
+ <td align="center">Avg@64</td>
276
+ <td align="center"><strong>69.6</strong></td>
277
+ <td align="center">59.4<sup>*</sup></td>
278
+ <td align="center">40.1<sup>*</sup></td>
279
+ <td align="center">43.4</td>
280
+ <td align="center">48.2</td>
281
+ <td align="center">46.5</td>
282
+ <td align="center">61.3</td>
283
+ </tr>
284
+ <tr>
285
+ <td align="center">AIME 2025</td>
286
+ <td align="center">Avg@64</td>
287
+ <td align="center"><strong>49.5</strong></td>
288
+ <td align="center">46.7</td>
289
+ <td align="center">24.7<sup>*</sup></td>
290
+ <td align="center">33.1<sup>*</sup></td>
291
+ <td align="center">33.9<sup>*</sup></td>
292
+ <td align="center">37.0</td>
293
+ <td align="center">46.6</td>
294
+ </tr>
295
+ <tr>
296
+ <td align="center">MATH-500</td>
297
+ <td align="center">Acc</td>
298
+ <td align="center"><strong>97.4</strong></td>
299
+ <td align="center">94.0<sup>*</sup></td>
300
+ <td align="center">91.2<sup>*</sup></td>
301
+ <td align="center">94.0</td>
302
+ <td align="center">94.4</td>
303
+ <td align="center">92.4</td>
304
+ <td align="center">95.4</td>
305
+ </tr>
306
+ <tr>
307
+ <td align="center">HMMT 2025</td>
308
+ <td align="center">Avg@32</td>
309
+ <td align="center"><strong>38.8</strong></td>
310
+ <td align="center">27.5</td>
311
+ <td align="center">11.9</td>
312
+ <td align="center">15.9</td>
313
+ <td align="center">15.9</td>
314
+ <td align="center">19.4</td>
315
+ <td align="center">34.7</td>
316
+ </tr>
317
+ <tr>
318
+ <td align="center">CNMO 2024</td>
319
+ <td align="center">Avg@16</td>
320
+ <td align="center">74.3</td>
321
+ <td align="center"><ins><strong>74.7</strong></ins></td>
322
+ <td align="center">48.6</td>
323
+ <td align="center">60.4</td>
324
+ <td align="center">57.6</td>
325
+ <td align="center">56.6</td>
326
+ <td align="center"><strong>75.0</strong></td>
327
+ </tr>
328
+ <tr>
329
+ <td align="center">PolyMath-en</td>
330
+ <td align="center">Avg@4</td>
331
+ <td align="center"><strong>65.1</strong></td>
332
+ <td align="center">59.5</td>
333
+ <td align="center">51.9</td>
334
+ <td align="center">52.8</td>
335
+ <td align="center">49.8</td>
336
+ <td align="center">54.0</td>
337
+ <td align="center">49.9</td>
338
+ </tr>
339
+
340
+ <tr>
341
+ <td align="center">ZebraLogic</td>
342
+ <td align="center">Acc</td>
343
+ <td align="center"><strong>89.0</strong></td>
344
+ <td align="center">84.0</td>
345
+ <td align="center">37.7<sup>*</sup></td>
346
+ <td align="center">73.7</td>
347
+ <td align="center">59.3</td>
348
+ <td align="center">58.5</td>
349
+ <td align="center">57.9</td>
350
+ </tr>
351
+
352
+ <tr>
353
+ <td align="center">AutoLogi</td>
354
+ <td align="center">Acc</td>
355
+ <td align="center"><ins><strong>89.5</strong></ins></td>
356
+ <td align="center">88.9</td>
357
+ <td align="center">83.3</td>
358
+ <td align="center"><strong>89.8</strong></td>
359
+ <td align="center">86.1</td>
360
+ <td align="center">88.2</td>
361
+ <td align="center">84.1</td>
362
+ </tr>
363
+
364
+ <tr>
365
+ <td align="center">GPQA-Diamond</td>
366
+ <td align="center">Avg@8</td>
367
+ <td align="center"><strong>75.1</strong></td>
368
+ <td align="center">68.4<sup>*</sup></td>
369
+ <td align="center">62.9<sup>*</sup></td>
370
+ <td align="center">70.0<sup>*</sup></td>
371
+ <td align="center">74.9<sup>*</sup></td>
372
+ <td align="center">66.3</td>
373
+ <td align="center">68.2</td>
374
+ </tr>
375
+
376
+ <tr>
377
+ <td align="center">SuperGPQA</td>
378
+ <td align="center">Acc</td>
379
+ <td align="center"><strong>57.2</strong></td>
380
+ <td align="center">53.7</td>
381
+ <td align="center">50.2</td>
382
+ <td align="center">55.7</td>
383
+ <td align="center">56.5</td>
384
+ <td align="center">50.8</td>
385
+ <td align="center">49.6</td>
386
+ </tr>
387
+
388
+ <tr>
389
+ <td align="center">Humanity's Last Exam<br><sup>(Text Only)</sup></td>
390
+ <td align="center">-</td>
391
+ <td align="center">4.7</td>
392
+ <td align="center">5.2</td>
393
+ <td align="center"><ins><strong>5.7</strong></ins></td>
394
+ <td align="center">5.8</td>
395
+ <td align="center"><strong>7.1</strong></td>
396
+ <td align="center">3.7</td>
397
+ <td align="center">5.6</td>
398
+ </tr>
399
+
400
+ <tr>
401
+ <td align="center" colspan=9><strong>General Tasks</strong></td>
402
+ </tr>
403
+
404
+ <tr>
405
+ <td align="center">MMLU</td>
406
+ <td align="center">EM</td>
407
+ <td align="center"><ins><strong>89.5</strong></ins></td>
408
+ <td align="center">89.4</td>
409
+ <td align="center">87.0</td>
410
+ <td align="center">91.5</td>
411
+ <td align="center"><strong>92.9</strong></td>
412
+ <td align="center">90.4</td>
413
+ <td align="center">90.1</td>
414
+ </tr>
415
+
416
+ <tr>
417
+ <td align="center">MMLU-Redux</td>
418
+ <td align="center">EM</td>
419
+ <td align="center"><ins><strong>92.7</strong></ins></td>
420
+ <td align="center">90.5</td>
421
+ <td align="center">89.2</td>
422
+ <td align="center">93.6</td>
423
+ <td align="center"><strong>94.2</strong></td>
424
+ <td align="center">92.4</td>
425
+ <td align="center">90.6</td>
426
+ </tr>
427
+
428
+ <tr>
429
+ <td align="center">MMLU-Pro</td>
430
+ <td align="center">EM</td>
431
+ <td align="center">81.1</td>
432
+ <td align="center"><ins><strong>81.2</strong></ins><sup>*</sup></td>
433
+ <td align="center">77.3</td>
434
+ <td align="center">83.7</td>
435
+ <td align="center"><strong>86.6</strong></td>
436
+ <td align="center">81.8</td>
437
+ <td align="center">79.4</td>
438
+ </tr>
439
+
440
+ <tr>
441
+ <td align="center">IFEval</td>
442
+ <td align="center">Prompt Strict</td>
443
+ <td align="center"><strong>89.8</strong></td>
444
+ <td align="center">81.1</td>
445
+ <td align="center">83.2<sup>*</sup></td>
446
+ <td align="center">87.6</td>
447
+ <td align="center">87.4</td>
448
+ <td align="center">88.0</td>
449
+ <td align="center">84.3</td>
450
+ </tr>
451
+
452
+ <tr>
453
+ <td align="center">Multi-Challenge</td>
454
+ <td align="center">Acc</td>
455
+ <td align="center"><strong>54.1</strong></td>
456
+ <td align="center">31.4</td>
457
+ <td align="center">34.0</td>
458
+ <td align="center">46.8</td>
459
+ <td align="center">49.0</td>
460
+ <td align="center">36.4</td>
461
+ <td align="center">39.5</td>
462
+ </tr>
463
+
464
+ <tr>
465
+ <td align="center">SimpleQA</td>
466
+ <td align="center">Correct</td>
467
+ <td align="center"><ins><strong>31.0</strong></ins></td>
468
+ <td align="center">27.7</td>
469
+ <td align="center">13.2</td>
470
+ <td align="center">15.9</td>
471
+ <td align="center">22.8</td>
472
+ <td align="center"><strong>42.3</strong></td>
473
+ <td align="center">23.3</td>
474
+ </tr>
475
+
476
+ <tr>
477
+ <td align="center">Livebench</td>
478
+ <td align="center">Pass@1</td>
479
+ <td align="center"><strong>76.4</strong></td>
480
+ <td align="center">72.4</td>
481
+ <td align="center">67.6</td>
482
+ <td align="center">74.8</td>
483
+ <td align="center">74.6</td>
484
+ <td align="center">69.8</td>
485
+ <td align="center">67.8</td>
486
+ </tr>
487
+ </tbody>
488
+ </table>
489
+ </div>
490
+ <sup>
491
+ • Bold denotes global SOTA, and underlined denotes open-source SOTA.
492
+ </sup><br/><sup>
493
+ • Data points marked with * are taken directly from the model's tech report or blog.
494
+ </sup><br/><sup>
495
+ • All metrics, except for SWE-bench Verified (Agentless), are evaluated with an 8k output token length. SWE-bench Verified (Agentless) is limited to a 16k output token length.
496
+ </sup><br/><sup>
497
+ • Kimi K2 achieves 65.8% pass@1 on the SWE-bench Verified tests with bash/editor tools (single-attempt patches, no test-time compute). It also achieves a 47.3% pass@1 on the SWE-bench Multilingual tests under the same conditions. Additionally, we report results on SWE-bench Verified tests (71.6%) that leverage parallel test-time compute by sampling multiple sequences and selecting the single best via an internal scoring model.
498
+ </sup><br/><sup>
499
+ • To ensure the stability of the evaluation, we employed avg@k on the AIME, HMMT, CNMO, PolyMath-en, GPQA-Diamond, EvalPlus, Tau2.
500
+ </sup><br/><sup>
501
+ • Some data points have been omitted due to prohibitively expensive evaluation costs.
502
+ </sup>
503
+
504
+ ---
505
+
506
+ #### Base model evaluation results
507
+
508
+ <div align="center">
509
+
510
+ <table>
511
+ <thead>
512
+ <tr>
513
+ <th align="center">Benchmark</th>
514
+ <th align="center">Metric</th>
515
+ <th align="center">Shot</th>
516
+ <th align="center">Kimi K2 Base</th>
517
+ <th align="center">Deepseek-V3-Base</th>
518
+ <th align="center">Qwen2.5-72B</th>
519
+ <th align="center">Llama 4 Maverick</th>
520
+ </tr>
521
+ </thead>
522
+ <tbody>
523
+ <tr>
524
+ <td align="center" colspan="7"><strong>General Tasks</strong></td>
525
+ </tr>
526
+ <tr>
527
+ <td align="center">MMLU</td>
528
+ <td align="center">EM</td>
529
+ <td align="center">5-shot</td>
530
+ <td align="center"><strong>87.8</strong></td>
531
+ <td align="center">87.1</td>
532
+ <td align="center">86.1</td>
533
+ <td align="center">84.9</td>
534
+ </tr>
535
+ <tr>
536
+ <td align="center">MMLU-pro</td>
537
+ <td align="center">EM</td>
538
+ <td align="center">5-shot</td>
539
+ <td align="center"><strong>69.2</strong></td>
540
+ <td align="center">60.6</td>
541
+ <td align="center">62.8</td>
542
+ <td align="center">63.5</td>
543
+ </tr>
544
+ <tr>
545
+ <td align="center">MMLU-redux-2.0</td>
546
+ <td align="center">EM</td>
547
+ <td align="center">5-shot</td>
548
+ <td align="center"><strong>90.2</strong></td>
549
+ <td align="center">89.5</td>
550
+ <td align="center">87.8</td>
551
+ <td align="center">88.2</td>
552
+ </tr>
553
+ <tr>
554
+ <td align="center">SimpleQA</td>
555
+ <td align="center">Correct</td>
556
+ <td align="center">5-shot</td>
557
+ <td align="center"><strong>35.3</strong></td>
558
+ <td align="center">26.5</td>
559
+ <td align="center">10.3</td>
560
+ <td align="center">23.7</td>
561
+ </tr>
562
+ <tr>
563
+ <td align="center">TriviaQA</td>
564
+ <td align="center">EM</td>
565
+ <td align="center">5-shot</td>
566
+ <td align="center"><strong>85.1</strong></td>
567
+ <td align="center">84.1</td>
568
+ <td align="center">76.0</td>
569
+ <td align="center">79.3</td>
570
+ </tr>
571
+ <tr>
572
+ <td align="center">GPQA-Diamond</td>
573
+ <td align="center">Avg@8</td>
574
+ <td align="center">5-shot</td>
575
+ <td align="center">48.1</td>
576
+ <td align="center"><strong>50.5</strong></td>
577
+ <td align="center">40.8</td>
578
+ <td align="center">49.4</td>
579
+ </tr>
580
+ <tr>
581
+ <td align="center">SuperGPQA</td>
582
+ <td align="center">EM</td>
583
+ <td align="center">5-shot</td>
584
+ <td align="center"><strong>44.7</strong></td>
585
+ <td align="center">39.2</td>
586
+ <td align="center">34.2</td>
587
+ <td align="center">38.8</td>
588
+ </tr>
589
+ <tr>
590
+ <td align="center" colspan="7"><strong>Coding Tasks</strong></td>
591
+ </tr>
592
+ <tr>
593
+ <td align="center">LiveCodeBench v6</td>
594
+ <td align="center">Pass@1</td>
595
+ <td align="center">1-shot</td>
596
+ <td align="center"><strong>26.3</strong></td>
597
+ <td align="center">22.9</td>
598
+ <td align="center">21.1</td>
599
+ <td align="center">25.1</td>
600
+ </tr>
601
+ <tr>
602
+ <td align="center">EvalPlus</td>
603
+ <td align="center">Pass@1</td>
604
+ <td align="center">-</td>
605
+ <td align="center"><strong>80.3</strong></td>
606
+ <td align="center">65.6</td>
607
+ <td align="center">66.0</td>
608
+ <td align="center">65.5</td>
609
+ </tr>
610
+ <tr>
611
+ <td align="center" colspan="7"><strong>Mathematics Tasks</strong></td>
612
+ </tr>
613
+ <tr>
614
+ <td align="center">MATH</td>
615
+ <td align="center">EM</td>
616
+ <td align="center">4-shot</td>
617
+ <td align="center"><strong>70.2</strong></td>
618
+ <td align="center">60.1</td>
619
+ <td align="center">61.0</td>
620
+ <td align="center">63.0</td>
621
+ </tr>
622
+ <tr>
623
+ <td align="center">GSM8k</td>
624
+ <td align="center">EM</td>
625
+ <td align="center">8-shot</td>
626
+ <td align="center"><strong>92.1</strong></td>
627
+ <td align="center">91.7</td>
628
+ <td align="center">90.4</td>
629
+ <td align="center">86.3</td>
630
+ </tr>
631
+ <tr>
632
+ <td align="center" colspan="7"><strong>Chinese Tasks</strong></td>
633
+ </tr>
634
+ <tr>
635
+ <td align="center">C-Eval</td>
636
+ <td align="center">EM</td>
637
+ <td align="center">5-shot</td>
638
+ <td align="center"><strong>92.5</strong></td>
639
+ <td align="center">90.0</td>
640
+ <td align="center">90.9</td>
641
+ <td align="center">80.9</td>
642
+ </tr>
643
+ <tr>
644
+ <td align="center">CSimpleQA</td>
645
+ <td align="center">Correct</td>
646
+ <td align="center">5-shot</td>
647
+ <td align="center"><strong>77.6</strong></td>
648
+ <td align="center">72.1</td>
649
+ <td align="center">50.5</td>
650
+ <td align="center">53.5</td>
651
+ </tr>
652
+ </tbody>
653
+ </table>
654
+ </div>
655
+ <sup>
656
+ • We only evaluate open-source pretrained models in this work. We report results for Qwen2.5-72B because the base checkpoint for Qwen3-235B-A22B was not open-sourced at the time of our study.
657
+ </sup><br/><sup>
658
+ • All models are evaluated using the same evaluation protocol.
659
+
660
+ </sup>
661
+
662
+
663
+ ## 4. Deployment
664
+ > [!Note]
665
+ > You can access Kimi K2's API on https://platform.moonshot.ai , we provide OpenAI/Anthropic-compatible API for you.
666
+ >
667
+ > The Anthropic-compatible API maps temperature by `real_temperature = request_temperature * 0.6` for better compatible with existing applications.
668
+
669
+ Our model checkpoints are stored in the block-fp8 format, you can find it on [Huggingface](https://huggingface.co/moonshotai/Kimi-K2-Instruct).
670
+
671
+ Currently, Kimi-K2 is recommended to run on the following inference engines:
672
+
673
+ * vLLM
674
+ * SGLang
675
+ * KTransformers
676
+ * TensorRT-LLM
677
+
678
+ Deployment examples for vLLM and SGLang can be found in the [Model Deployment Guide](docs/deploy_guidance.md).
679
+
680
+ ---
681
+
682
+ ## 5. Model Usage
683
+
684
+ ### Chat Completion
685
+
686
+ Once the local inference service is up, you can interact with it through the chat endpoint:
687
+
688
+ ```python
689
+ def simple_chat(client: OpenAI, model_name: str):
690
+ messages = [
691
+ {"role": "system", "content": "You are Kimi, an AI assistant created by Moonshot AI."},
692
+ {"role": "user", "content": [{"type": "text", "text": "Please give a brief self-introduction."}]},
693
+ ]
694
+ response = client.chat.completions.create(
695
+ model=model_name,
696
+ messages=messages,
697
+ stream=False,
698
+ temperature=0.6,
699
+ max_tokens=256
700
+ )
701
+ print(response.choices[0].message.content)
702
+ ```
703
+
704
+ > [!NOTE]
705
+ > The recommended temperature for Kimi-K2-Instruct is `temperature = 0.6`.
706
+ > If no special instructions are required, the system prompt above is a good default.
707
+
708
+ ---
709
+
710
+ ### Tool Calling
711
+
712
+ Kimi-K2-Instruct has strong tool-calling capabilities.
713
+ To enable them, you need to pass the list of available tools in each request, then the model will autonomously decide when and how to invoke them.
714
+
715
+ The following example demonstrates calling a weather tool end-to-end:
716
+
717
+ ```python
718
+ # Your tool implementation
719
+ def get_weather(city: str) -> dict:
720
+ return {"weather": "Sunny"}
721
+
722
+ # Tool schema definition
723
+ tools = [{
724
+ "type": "function",
725
+ "function": {
726
+ "name": "get_weather",
727
+ "description": "Retrieve current weather information. Call this when the user asks about the weather.",
728
+ "parameters": {
729
+ "type": "object",
730
+ "required": ["city"],
731
+ "properties": {
732
+ "city": {
733
+ "type": "string",
734
+ "description": "Name of the city"
735
+ }
736
+ }
737
+ }
738
+ }
739
+ }]
740
+
741
+ # Map tool names to their implementations
742
+ tool_map = {
743
+ "get_weather": get_weather
744
+ }
745
+
746
+ def tool_call_with_client(client: OpenAI, model_name: str):
747
+ messages = [
748
+ {"role": "system", "content": "You are Kimi, an AI assistant created by Moonshot AI."},
749
+ {"role": "user", "content": "What's the weather like in Beijing today? Use the tool to check."}
750
+ ]
751
+ finish_reason = None
752
+ while finish_reason is None or finish_reason == "tool_calls":
753
+ completion = client.chat.completions.create(
754
+ model=model_name,
755
+ messages=messages,
756
+ temperature=0.6,
757
+ tools=tools, # tool list defined above
758
+ tool_choice="auto"
759
+ )
760
+ choice = completion.choices[0]
761
+ finish_reason = choice.finish_reason
762
+ if finish_reason == "tool_calls":
763
+ messages.append(choice.message)
764
+ for tool_call in choice.message.tool_calls:
765
+ tool_call_name = tool_call.function.name
766
+ tool_call_arguments = json.loads(tool_call.function.arguments)
767
+ tool_function = tool_map[tool_call_name]
768
+ tool_result = tool_function(**tool_call_arguments)
769
+ print("tool_result:", tool_result)
770
+
771
+ messages.append({
772
+ "role": "tool",
773
+ "tool_call_id": tool_call.id,
774
+ "name": tool_call_name,
775
+ "content": json.dumps(tool_result)
776
+ })
777
+ print("-" * 100)
778
+ print(choice.message.content)
779
+ ```
780
+
781
+ The `tool_call_with_client` function implements the pipeline from user query to tool execution.
782
+ This pipeline requires the inference engine to support Kimi-K2’s native tool-parsing logic.
783
+ For streaming output and manual tool-parsing, see the [Tool Calling Guide](docs/tool_call_guidance.md).
784
+
785
+ ---
786
+
787
+ ## 6. License
788
+
789
+ Both the code repository and the model weights are released under the [Modified MIT License](LICENSE).
790
+
791
+ ---
792
+
793
+ ## 7. Third Party Notices
794
+
795
+ See [THIRD PARTY NOTICES](THIRD_PARTY_NOTICES.md)
796
+
797
+ ---
798
+
799
+ ## 7. Contact Us
800
+
801
+ If you have any questions, please reach out at [[email protected]](mailto:[email protected]).
THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # THIRD_PARTY_NOTICES
2
+
3
+ This file lists third-party software contained in Kimi-K2 along with their licenses, in compliance with the redistribution clauses of those licenses.
4
+
5
+ ---
6
+
7
+ ## 1. DeepSeek-V3
8
+
9
+ Our model archietecture is DeepSeek-V3-like. Some of modeling codes are copied from the source repository.
10
+
11
+ - **Source Repository**
12
+ https://huggingface.co/deepseek-ai/DeepSeek-V3
13
+
14
+ - **Files / Directories Used**
15
+ - configuation_deepseek.py
16
+ - modeling_deepseek.py
17
+
18
+ - **License Type**
19
+ MIT License
20
+
21
+ - **Copyright Notice**
22
+ Copyright (c) 2023 DeepSeek
23
+
24
+ - **Full License Text**
25
+ ```
26
+ MIT License
27
+
28
+ Copyright (c) 2023 DeepSeek
29
+
30
+ Permission is hereby granted, free of charge, to any person obtaining a copy
31
+ of this software and associated documentation files (the "Software"), to deal
32
+ in the Software without restriction, including without limitation the rights
33
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
34
+ copies of the Software, and to permit persons to whom the Software is
35
+ furnished to do so, subject to the following conditions:
36
+
37
+ The above copyright notice and this permission notice shall be included in all
38
+ copies or substantial portions of the Software.
39
+
40
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
45
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
46
+ SOFTWARE.
47
+ ```
config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DeepseekV3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_deepseek.DeepseekV3Config",
9
+ "AutoModel": "modeling_deepseek.DeepseekV3Model",
10
+ "AutoModelForCausalLM": "modeling_deepseek.DeepseekV3ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.001,
13
+ "bos_token_id": 163584,
14
+ "eos_token_id": 163585,
15
+ "first_k_dense_replace": 1,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 7168,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 18432,
20
+ "kv_lora_rank": 512,
21
+ "max_position_embeddings": 131072,
22
+ "model_type": "kimi_k2",
23
+ "moe_intermediate_size": 2048,
24
+ "moe_layer_freq": 1,
25
+ "n_group": 1,
26
+ "n_routed_experts": 384,
27
+ "n_shared_experts": 1,
28
+ "norm_topk_prob": true,
29
+ "num_attention_heads": 64,
30
+ "num_experts_per_tok": 8,
31
+ "num_hidden_layers": 61,
32
+ "num_key_value_heads": 64,
33
+ "num_nextn_predict_layers": 0,
34
+ "pretraining_tp": 1,
35
+ "q_lora_rank": 1536,
36
+ "qk_nope_head_dim": 128,
37
+ "qk_rope_head_dim": 64,
38
+ "rms_norm_eps": 1e-06,
39
+ "rope_theta": 50000.0,
40
+ "routed_scaling_factor": 2.827,
41
+ "rope_scaling": {
42
+ "beta_fast": 1.0,
43
+ "beta_slow": 1.0,
44
+ "factor": 32.0,
45
+ "mscale": 1.0,
46
+ "mscale_all_dim": 1.0,
47
+ "original_max_position_embeddings": 4096,
48
+ "type": "yarn"
49
+ },
50
+ "scoring_func": "sigmoid",
51
+ "seq_aux": true,
52
+ "tie_word_embeddings": false,
53
+ "topk_group": 1,
54
+ "topk_method": "noaux_tc",
55
+ "torch_dtype": "bfloat16",
56
+ "transformers_version": "4.48.3",
57
+ "use_cache": true,
58
+ "v_head_dim": 128,
59
+ "vocab_size": 163840
60
+ }
configuration_deepseek.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copy from https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/configuration_deepseek.py
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+ DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
9
+ class DeepseekV3Config(PretrainedConfig):
10
+ r"""
11
+ This is the configuration class to store the configuration of a [`DeepseekV3Model`]. It is used to instantiate an DeepSeek
12
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
13
+ defaults will yield a similar configuration to that of the DeepSeek-V3.
14
+
15
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
16
+ documentation from [`PretrainedConfig`] for more information.
17
+
18
+
19
+ Args:
20
+ vocab_size (`int`, *optional*, defaults to 129280):
21
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
22
+ `inputs_ids` passed when calling [`DeepseekV3Model`]
23
+ hidden_size (`int`, *optional*, defaults to 4096):
24
+ Dimension of the hidden representations.
25
+ intermediate_size (`int`, *optional*, defaults to 11008):
26
+ Dimension of the MLP representations.
27
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
28
+ Dimension of the MoE representations.
29
+ num_hidden_layers (`int`, *optional*, defaults to 32):
30
+ Number of hidden layers in the Transformer decoder.
31
+ num_nextn_predict_layers (`int`, *optional*, defaults to 1):
32
+ Number of nextn predict layers in the DeepSeekV3 Model.
33
+ num_attention_heads (`int`, *optional*, defaults to 32):
34
+ Number of attention heads for each attention layer in the Transformer decoder.
35
+ n_shared_experts (`int`, *optional*, defaults to None):
36
+ Number of shared experts, None means dense model.
37
+ n_routed_experts (`int`, *optional*, defaults to None):
38
+ Number of routed experts, None means dense model.
39
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
40
+ Scaling factor or routed experts.
41
+ topk_method (`str`, *optional*, defaults to `gready`):
42
+ Topk method used in routed gate.
43
+ n_group (`int`, *optional*, defaults to None):
44
+ Number of groups for routed experts.
45
+ topk_group (`int`, *optional*, defaults to None):
46
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
47
+ num_experts_per_tok (`int`, *optional*, defaults to None):
48
+ Number of selected experts, None means dense model.
49
+ moe_layer_freq (`int`, *optional*, defaults to 1):
50
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
51
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
52
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
53
+ \--k dense layers--/
54
+ norm_topk_prob (`bool`, *optional*, defaults to False):
55
+ Whether to normalize the weights of the routed experts.
56
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
57
+ Method of computing expert weights.
58
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
59
+ Auxiliary loss weight coefficient.
60
+ seq_aux = (`bool`, *optional*, defaults to True):
61
+ Whether to compute the auxiliary loss for each individual sample.
62
+ num_key_value_heads (`int`, *optional*):
63
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
64
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
65
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
66
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
67
+ by meanpooling all the original heads within that group. For more details checkout [this
68
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
69
+ `num_attention_heads`.
70
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
71
+ The non-linear activation function (function or string) in the decoder.
72
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
73
+ The maximum sequence length that this model might ever be used with.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
77
+ The epsilon used by the rms normalization layers.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`.
81
+ pad_token_id (`int`, *optional*):
82
+ Padding token id.
83
+ bos_token_id (`int`, *optional*, defaults to 1):
84
+ Beginning of stream token id.
85
+ eos_token_id (`int`, *optional*, defaults to 2):
86
+ End of stream token id.
87
+ pretraining_tp (`int`, *optional*, defaults to 1):
88
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
89
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
90
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
91
+ issue](https://github.com/pytorch/pytorch/issues/76232).
92
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
93
+ Whether to tie weight embeddings
94
+ rope_theta (`float`, *optional*, defaults to 10000.0):
95
+ The base period of the RoPE embeddings.
96
+ rope_scaling (`Dict`, *optional*):
97
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
98
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
99
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
100
+ `max_position_embeddings` to the expected new maximum.
101
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
102
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
103
+ attention_dropout (`float`, *optional*, defaults to 0.0):
104
+ The dropout ratio for the attention probabilities.
105
+
106
+ ```python
107
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
108
+
109
+ >>> # Initializing a Deepseek-V3 style configuration
110
+ >>> configuration = DeepseekV3Config()
111
+
112
+ >>> # Accessing the model configuration
113
+ >>> configuration = model.config
114
+ ```"""
115
+
116
+ model_type = "deepseek_v3"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=129280,
122
+ hidden_size=7168,
123
+ intermediate_size=18432,
124
+ moe_intermediate_size = 2048,
125
+ num_hidden_layers=61,
126
+ num_nextn_predict_layers=1,
127
+ num_attention_heads=128,
128
+ num_key_value_heads=128,
129
+ n_shared_experts = 1,
130
+ n_routed_experts = 256,
131
+ ep_size = 1,
132
+ routed_scaling_factor = 2.5,
133
+ kv_lora_rank = 512,
134
+ q_lora_rank = 1536,
135
+ qk_rope_head_dim = 64,
136
+ v_head_dim = 128,
137
+ qk_nope_head_dim = 128,
138
+ topk_method = 'noaux_tc',
139
+ n_group = 8,
140
+ topk_group = 4,
141
+ num_experts_per_tok = 8,
142
+ moe_layer_freq = 1,
143
+ first_k_dense_replace = 3,
144
+ norm_topk_prob = True,
145
+ scoring_func = 'sigmoid',
146
+ aux_loss_alpha = 0.001,
147
+ seq_aux = True,
148
+ hidden_act="silu",
149
+ max_position_embeddings=4096,
150
+ initializer_range=0.02,
151
+ rms_norm_eps=1e-6,
152
+ use_cache=True,
153
+ pad_token_id=None,
154
+ bos_token_id=0,
155
+ eos_token_id=1,
156
+ pretraining_tp=1,
157
+ tie_word_embeddings=False,
158
+ rope_theta=10000.0,
159
+ rope_scaling=None,
160
+ attention_bias=False,
161
+ attention_dropout=0.0,
162
+ **kwargs,
163
+ ):
164
+ self.vocab_size = vocab_size
165
+ self.max_position_embeddings = max_position_embeddings
166
+ self.hidden_size = hidden_size
167
+ self.intermediate_size = intermediate_size
168
+ self.moe_intermediate_size = moe_intermediate_size
169
+ self.num_hidden_layers = num_hidden_layers
170
+ self.num_nextn_predict_layers = num_nextn_predict_layers
171
+ self.num_attention_heads = num_attention_heads
172
+ self.n_shared_experts = n_shared_experts
173
+ self.n_routed_experts = n_routed_experts
174
+ self.ep_size = ep_size
175
+ self.routed_scaling_factor = routed_scaling_factor
176
+ self.kv_lora_rank = kv_lora_rank
177
+ self.q_lora_rank = q_lora_rank
178
+ self.qk_rope_head_dim = qk_rope_head_dim
179
+ self.v_head_dim = v_head_dim
180
+ self.qk_nope_head_dim = qk_nope_head_dim
181
+ self.topk_method = topk_method
182
+ self.n_group = n_group
183
+ self.topk_group = topk_group
184
+ self.num_experts_per_tok = num_experts_per_tok
185
+ self.moe_layer_freq = moe_layer_freq
186
+ self.first_k_dense_replace = first_k_dense_replace
187
+ self.norm_topk_prob = norm_topk_prob
188
+ self.scoring_func = scoring_func
189
+ self.aux_loss_alpha = aux_loss_alpha
190
+ self.seq_aux = seq_aux
191
+ # for backward compatibility
192
+ if num_key_value_heads is None:
193
+ num_key_value_heads = num_attention_heads
194
+
195
+ self.num_key_value_heads = num_key_value_heads
196
+ self.hidden_act = hidden_act
197
+ self.initializer_range = initializer_range
198
+ self.rms_norm_eps = rms_norm_eps
199
+ self.pretraining_tp = pretraining_tp
200
+ self.use_cache = use_cache
201
+ self.rope_theta = rope_theta
202
+ self.rope_scaling = rope_scaling
203
+ self.attention_bias = attention_bias
204
+ self.attention_dropout = attention_dropout
205
+
206
+ super().__init__(
207
+ pad_token_id=pad_token_id,
208
+ bos_token_id=bos_token_id,
209
+ eos_token_id=eos_token_id,
210
+ tie_word_embeddings=tie_word_embeddings,
211
+ **kwargs,
212
+ )
docs/deploy_guidance.md ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Kimi-K2 Deployment Guide
2
+
3
+ > [!Note]
4
+ > This guide only provides some examples of deployment commands for Kimi-K2, which may not be the optimal configuration. Since inference engines are still being updated frequenty, please continue to follow the guidance from their homepage if you want to achieve better inference performance.
5
+
6
+
7
+ ## vLLM Deployment
8
+
9
+ The smallest deployment unit for Kimi-K2 FP8 weights with 128k seqlen on mainstream H200 or H20 platform is a cluster with 16 GPUs with either Tensor Parallel (TP) or "data parallel + expert parallel" (DP+EP).
10
+ Running parameters for this environment are provided below. You may scale up to more nodes and increase expert-parallelism to enlarge the inference batch size and overall throughput.
11
+
12
+ ### Tensor Parallelism
13
+
14
+ When the parallelism degree ≤ 16, you can run inference with pure Tensor Parallelism. A sample launch command is:
15
+
16
+ ``` bash
17
+ # start ray on node 0 and node 1
18
+
19
+ # node 0:
20
+ vllm serve $MODEL_PATH \
21
+ --port 8000 \
22
+ --served-model-name kimi-k2 \
23
+ --trust-remote-code \
24
+ --tensor-parallel-size 16 \
25
+ --enable-auto-tool-choice \
26
+ --tool-call-parser kimi_k2
27
+ ```
28
+
29
+ **Key parameter notes:**
30
+ - `--tensor-parallel-size 16`: If using more than 16 GPUs, combine with pipeline-parallelism.
31
+ - `--enable-auto-tool-choice`: Required when enabling tool usage.
32
+ - `--tool-call-parser kimi_k2`: Required when enabling tool usage.
33
+
34
+ ### Data Parallelism + Expert Parallelism
35
+
36
+ You can install libraries like DeepEP and DeepGEMM as needed. Then run the command (example on H200):
37
+
38
+ ``` bash
39
+ # node 0
40
+ vllm serve $MODEL_PATH --port 8000 --served-model-name kimi-k2 --trust-remote-code --data-parallel-size 16 --data-parallel-size-local 8 --data-parallel-address $MASTER_IP --data-parallel-rpc-port $PORT --enable-expert-parallel --max-num-batched-tokens 8192 --max-num-seqs 256 --gpu-memory-utilization 0.85 --enable-auto-tool-choice --tool-call-parser kimi_k2
41
+
42
+ # node 1
43
+ vllm serve $MODEL_PATH --headless --data-parallel-start-rank 8 --port 8000 --served-model-name kimi-k2 --trust-remote-code --data-parallel-size 16 --data-parallel-size-local 8 --data-parallel-address $MASTER_IP --data-parallel-rpc-port $PORT --enable-expert-parallel --max-num-batched-tokens 8192 --max-num-seqs 256 --gpu-memory-utilization 0.85 --enable-auto-tool-choice --tool-call-parser kimi_k2
44
+ ```
45
+
46
+ ## SGLang Deployment
47
+
48
+ Similarly, we can use TP or DP+EP in SGLang for Deployment, here are the examples.
49
+
50
+
51
+ ### Tensor Parallelism
52
+
53
+ Here is the simple example code to run TP16 with two nodes on H200:
54
+
55
+ ``` bash
56
+ # Node 0
57
+ python -m sglang.launch_server --model-path $MODEL_PATH --tp 16 --dist-init-addr $MASTER_IP:50000 --nnodes 2 --node-rank 0 --trust-remote-code --tool-call-parser kimi_k2
58
+
59
+ # Node 1
60
+ python -m sglang.launch_server --model-path $MODEL_PATH --tp 16 --dist-init-addr $MASTER_IP:50000 --nnodes 2 --node-rank 1 --trust-remote-code --tool-call-parser kimi_k2
61
+ ```
62
+
63
+ **Key parameter notes:**
64
+ - `--tool-call-parser kimi_k2`: Required when enabling tool usage.
65
+
66
+ ### Data Parallelism + Expert Parallelism
67
+
68
+ Here is an example for large scale Prefill-Decode Disaggregation (4P12D H200) with DP+EP in SGLang:
69
+
70
+ ``` bash
71
+ # for prefill node
72
+ MC_TE_METRIC=true SGLANG_DISAGGREGATION_HEARTBEAT_INTERVAL=10000000 SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=100000 SGLANG_DISAGGREGATION_WAITING_TIMEOUT=100000 PYTHONUNBUFFERED=1 \
73
+ python -m sglang.launch_server --model-path $MODEL_PATH \
74
+ --trust-remote-code --disaggregation-mode prefill --dist-init-addr $PREFILL_NODE0$:5757 --tp-size 32 --dp-size 32 --enable-dp-attention --host $LOCAL_IP --decode-log-interval 1 --disable-radix-cache --enable-deepep-moe --moe-dense-tp-size 1 --enable-dp-lm-head --disable-shared-experts-fusion --watchdog-timeout 1000000 --enable-two-batch-overlap --disaggregation-ib-device $IB_DEVICE --chunked-prefill-size 131072 --mem-fraction-static 0.85 --deepep-mode normal --ep-dispatch-algorithm dynamic --eplb-algorithm deepseek --max-running-requests 1024 --nnodes 4 --node-rank $RANK --tool-call-parser kimi_k2
75
+
76
+
77
+ # for decode node
78
+ SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=480 MC_TE_METRIC=true SGLANG_DISAGGREGATION_HEARTBEAT_INTERVAL=10000000 SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=100000 SGLANG_DISAGGREGATION_WAITING_TIMEOUT=100000 PYTHONUNBUFFERED=1 \
79
+ python -m sglang.launch_server --model-path $MODEL_PATH --trust-remote-code --disaggregation-mode decode --dist-init-addr $DECODE_NODE0:5757 --tp-size 96 --dp-size 96 --enable-dp-attention --host $LOCAL_IP --decode-log-interval 1 --context-length 2176 --disable-radix-cache --enable-deepep-moe --moe-dense-tp-size 1 --enable-dp-lm-head --disable-shared-experts-fusion --watchdog-timeout 1000000 --enable-two-batch-overlap --disaggregation-ib-device $IB_DEVICE --deepep-mode low_latency --mem-fraction-static 0.8 --cuda-graph-bs 480 --max-running-requests 46080 --ep-num-redundant-experts 96 --nnodes 12 --node-rank $RANK --tool-call-parser kimi_k2
80
+
81
+ # pdlb
82
+ PYTHONUNBUFFERED=1 python -m sglang.srt.disaggregation.launch_lb --prefill http://${PREFILL_NODE0}:30000 --decode http://${DECODE_NODE0}:30000
83
+ ```
84
+
85
+ ## KTransformers Deployment
86
+
87
+ Please copy all configuration files (i.e., everything except the .safetensors files) into the GGUF checkpoint folder at /path/to/K2. Then run:
88
+ ``` bash
89
+ python ktransformers/server/main.py --model_path /path/to/K2 --gguf_path /path/to/K2 --cache_lens 30000
90
+ ```
91
+
92
+ To enable AMX optimization, run:
93
+
94
+ ``` bash
95
+ python ktransformers/server/main.py --model_path /path/to/K2 --gguf_path /path/to/K2 --cache_lens 30000 --optimize_config_path ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat-fp8-linear-ggml-experts-serve-amx.yaml
96
+ ```
97
+
98
+ ## TensoRT-LLM Deployment
99
+ ### Prerequisite
100
+ Please refer to [this guide](https://nvidia.github.io/TensorRT-LLM/installation/build-from-source-linux.html) to build TensorRT-LLM v1.0.0-rc2 from source and start a TRT-LLM docker container.
101
+
102
+ install blobfile by:
103
+ ```bash
104
+ pip install blobfile
105
+ ```
106
+ ### Multi-node Serving
107
+ TensorRT-LLM supports multi-node inference. You can use mpirun to launch Kimi-K2 with multi-node jobs. We will use two nodes for this example.
108
+
109
+ #### mpirun
110
+ mpirun requires each node to have passwordless ssh access to the other node. We need to setup the environment inside the docker container. Run the container with host network and mount the current directory as well as model directory to the container.
111
+
112
+ ```bash
113
+ # use host network
114
+ IMAGE=<YOUR_IMAGE>
115
+ NAME=test_2node_docker
116
+ # host1
117
+ docker run -it --name ${NAME}_host1 --ipc=host --gpus=all --network host --privileged --ulimit memlock=-1 --ulimit stack=67108864 -v ${PWD}:/workspace -v <YOUR_MODEL_DIR>:/models/DeepSeek-V3 -w /workspace ${IMAGE}
118
+ # host2
119
+ docker run -it --name ${NAME}_host2 --ipc=host --gpus=all --network host --privileged --ulimit memlock=-1 --ulimit stack=67108864 -v ${PWD}:/workspace -v <YOUR_MODEL_DIR>:/models/DeepSeek-V3 -w /workspace ${IMAGE}
120
+ ```
121
+
122
+ Set up ssh inside the container
123
+
124
+ ```bash
125
+ apt-get update && apt-get install -y openssh-server
126
+
127
+ # modify /etc/ssh/sshd_config
128
+ PermitRootLogin yes
129
+ PubkeyAuthentication yes
130
+ # modify /etc/ssh/sshd_config, change default port 22 to another unused port
131
+ port 2233
132
+
133
+ # modify /etc/ssh
134
+ ```
135
+
136
+ Generate ssh key on host1 and copy to host2, vice versa.
137
+
138
+ ```bash
139
+ # on host1
140
+ ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519
141
+ ssh-copy-id -i ~/.ssh/id_ed25519.pub root@<HOST2>
142
+ # on host2
143
+ ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519
144
+ ssh-copy-id -i ~/.ssh/id_ed25519.pub root@<HOST1>
145
+
146
+ # restart ssh service on host1 and host2
147
+ service ssh restart # or
148
+ /etc/init.d/ssh restart # or
149
+ systemctl restart ssh
150
+ ```
151
+
152
+ Generate additional config for trtllm serve.
153
+ ```bash
154
+ cat >/path/to/TensorRT-LLM/extra-llm-api-config.yml <<EOF
155
+ cuda_graph_config:
156
+ padding_enabled: true
157
+ batch_sizes:
158
+ - 1
159
+ - 2
160
+ - 4
161
+ - 8
162
+ - 16
163
+ - 32
164
+ - 64
165
+ - 128
166
+ print_iter_log: true
167
+ enable_attention_dp: true
168
+ EOF
169
+ ```
170
+
171
+
172
+ After the preparations,you can run the trtllm-serve on two nodes using mpirun:
173
+
174
+ ```bash
175
+ mpirun -np 16 \
176
+ -H <HOST1>:8,<HOST2>:8 \
177
+ -mca plm_rsh_args "-p 2233" \
178
+ --allow-run-as-root \
179
+ trtllm-llmapi-launch trtllm-serve serve \
180
+ --backend pytorch \
181
+ --tp_size 16 \
182
+ --ep_size 8 \
183
+ --kv_cache_free_gpu_memory_fraction 0.95 \
184
+ --trust_remote_code \
185
+ --max_batch_size 128 \
186
+ --max_num_tokens 4096 \
187
+ --extra_llm_api_options /path/to/TensorRT-LLM/extra-llm-api-config.yml \
188
+ --port 8000 \
189
+ <YOUR_MODEL_DIR>
190
+ ```
191
+
192
+ ## Others
193
+
194
+ Kimi-K2 reuses the `DeepSeekV3CausalLM` architecture and convert it's weight into proper shape to save redevelopment effort. To let inference engines distinguish it from DeepSeek-V3 and apply the best optimizations, we set `"model_type": "kimi_k2"` in `config.json`.
195
+
196
+ If you are using a framework that is not on the recommended list, you can still run the model by manually changing `model_type` to "deepseek_v3" in `config.json` as a temporary workaround. You may need to manually parse tool calls in case no tool call parser is available in your framework.
docs/tool_call_guidance.md ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Tool Calling
2
+ To enable the tool calling feature, you may need to set certain tool calling parser options when starting the service. See [deploy_guidance](./deploy_guidance.md) for details.
3
+ In Kimi-K2, a tool calling process includes:
4
+ - Passing function descriptions to Kimi-K2
5
+ - Kimi-K2 decides to make a function call and returns the necessary information for the function call to the user
6
+ - The user performs the function call, collects the call results, and passes the function call results to Kimi-K2
7
+ - Kimi-K2 continues to generate content based on the function call results until the model believes it has obtained sufficient information to respond to the user
8
+
9
+ ### Preparing Tools
10
+ Suppose we have a function `get_weather` that can query the weather conditions in real-time.
11
+ This function accepts a city name as a parameter and returns the weather conditions. We need to prepare a structured description for it so that Kimi-K2 can understand its functionality.
12
+
13
+ ```python
14
+ def get_weather(city):
15
+ return {"weather": "Sunny"}
16
+
17
+ # Collect the tool descriptions in tools
18
+ tools = [{
19
+ "type": "function",
20
+ "function": {
21
+ "name": "get_weather",
22
+ "description": "Get weather information. Call this tool when the user needs to get weather information",
23
+ "parameters": {
24
+ "type": "object",
25
+ "required": ["city"],
26
+ "properties": {
27
+ "city": {
28
+ "type": "string",
29
+ "description": "City name",
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }]
35
+
36
+ # Tool name->object mapping for easy calling later
37
+ tool_map = {
38
+ "get_weather": get_weather
39
+ }
40
+ ```
41
+ ### Chat with tools
42
+ We use `openai.OpenAI` to send messages to Kimi-K2 along with tool descriptions. Kimi-K2 will autonomously decide whether to use and how to use the provided tools.
43
+ If Kimi-K2 believes a tool call is needed, it will return a result with `finish_reason='tool_calls'`. At this point, the returned result includes the tool call information.
44
+ After calling tools with the provided information, we then need to append the tool call results to the chat history and continue calling Kimi-K2.
45
+ Kimi-K2 may need to call tools multiple times until the model believes the current results can answer the user's question. We should check `finish_reason` until it is not `tool_calls`.
46
+
47
+ The results obtained by the user after calling the tools should be added to `messages` with `role='tool'`.
48
+
49
+ ```python
50
+ import json
51
+ from openai import OpenAI
52
+ model_name='moonshotai/Kimi-K2-Instruct'
53
+ client = OpenAI(base_url=endpoint,
54
+ api_key='xxx')
55
+
56
+ messages = [
57
+ {"role": "user", "content": "What's the weather like in Beijing today? Let's check using the tool."}
58
+ ]
59
+ finish_reason = None
60
+ while finish_reason is None or finish_reason == "tool_calls":
61
+ completion = client.chat.completions.create(
62
+ model=model_name,
63
+ messages=messages,
64
+ temperature=0.3,
65
+ tools=tools,
66
+ tool_choice="auto",
67
+ )
68
+ choice = completion.choices[0]
69
+ finish_reason = choice.finish_reason
70
+ # Note: The finish_reason when tool calls end may vary across different engines, so this condition check needs to be adjusted accordingly
71
+ if finish_reason == "tool_calls":
72
+ messages.append(choice.message)
73
+ for tool_call in choice.message.tool_calls:
74
+ tool_call_name = tool_call.function.name
75
+ tool_call_arguments = json.loads(tool_call.function.arguments)
76
+ tool_function = tool_map[tool_call_name]
77
+ tool_result = tool_function(tool_call_arguments)
78
+ print("tool_result", tool_result)
79
+
80
+ messages.append({
81
+ "role": "tool",
82
+ "tool_call_id": tool_call.id,
83
+ "name": tool_call_name,
84
+ "content": json.dumps(tool_result),
85
+ })
86
+ print('-' * 100)
87
+ print(choice.message.content)
88
+ ```
89
+ ### Tool Calling in Streaming Mode
90
+ Tool calling can also be used in streaming mode. In this case, we need to collect the tool call information returned in the stream until we have a complete tool call. Please refer to the code below:
91
+
92
+ ```python
93
+ messages = [
94
+ {"role": "user", "content": "What's the weather like in Beijing today? Let's check using the tool."}
95
+ ]
96
+ finish_reason = None
97
+ msg = ''
98
+ while finish_reason is None or finish_reason == "tool_calls":
99
+ completion = client.chat.completions.create(
100
+ model=model_name,
101
+ messages=messages,
102
+ temperature=0.3,
103
+ tools=tools,
104
+ tool_choice="auto",
105
+ stream=True
106
+ )
107
+ tool_calls = []
108
+ for chunk in completion:
109
+ delta = chunk.choices[0].delta
110
+ if delta.content:
111
+ msg += delta.content
112
+ if delta.tool_calls:
113
+ for tool_call_chunk in delta.tool_calls:
114
+ if tool_call_chunk.index is not None:
115
+ # Extend the tool_calls list
116
+ while len(tool_calls) <= tool_call_chunk.index:
117
+ tool_calls.append({
118
+ "id": "",
119
+ "type": "function",
120
+ "function": {
121
+ "name": "",
122
+ "arguments": ""
123
+ }
124
+ })
125
+
126
+ tc = tool_calls[tool_call_chunk.index]
127
+
128
+ if tool_call_chunk.id:
129
+ tc["id"] += tool_call_chunk.id
130
+ if tool_call_chunk.function.name:
131
+ tc["function"]["name"] += tool_call_chunk.function.name
132
+ if tool_call_chunk.function.arguments:
133
+ tc["function"]["arguments"] += tool_call_chunk.function.arguments
134
+
135
+ finish_reason = chunk.choices[0].finish_reason
136
+ # Note: The finish_reason when tool calls end may vary across different engines, so this condition check needs to be adjusted accordingly
137
+ if finish_reason == "tool_calls":
138
+ for tool_call in tool_calls:
139
+ tool_call_name = tool_call['function']['name']
140
+ tool_call_arguments = json.loads(tool_call['function']['arguments'])
141
+ tool_function = tool_map[tool_call_name]
142
+ tool_result = tool_function(tool_call_arguments)
143
+ messages.append({
144
+ "role": "tool",
145
+ "tool_call_id": tool_call['id'],
146
+ "name": tool_call_name,
147
+ "content": json.dumps(tool_result),
148
+ })
149
+ # The text generated by the tool call is not the final version, reset msg
150
+ msg = ''
151
+
152
+ print(msg)
153
+ ```
154
+ ### Manually Parsing Tool Calls
155
+ The tool call requests generated by Kimi-K2 can also be parsed manually, which is especially useful when the service you are using does not provide a tool-call parser.
156
+ The tool call requests generated by Kimi-K2 are wrapped by `<|tool_calls_section_begin|>` and `<|tool_calls_section_end|>`,
157
+ with each tool call wrapped by `<|tool_call_begin|>` and `<|tool_call_end|>`. The tool ID and arguments are separated by `<|tool_call_argument_begin|>`.
158
+ The format of the tool ID is `functions.{func_name}:{idx}`, from which we can parse the function name.
159
+
160
+ Based on the above rules, we can directly post request to the completions interface and manually parse tool calls.
161
+
162
+ ```python
163
+ import requests
164
+ from transformers import AutoTokenizer
165
+ messages = [
166
+ {"role": "user", "content": "What's the weather like in Beijing today? Let's check using the tool."}
167
+ ]
168
+ msg = ''
169
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
170
+ while True:
171
+ text = tokenizer.apply_chat_template(
172
+ messages,
173
+ tokenize=False,
174
+ tools=tools,
175
+ add_generation_prompt=True,
176
+ )
177
+ payload = {
178
+ "model": model_name,
179
+ "prompt": text,
180
+ "max_tokens": 512
181
+ }
182
+ response = requests.post(
183
+ f"{endpoint}/completions",
184
+ headers={"Content-Type": "application/json"},
185
+ json=payload,
186
+ stream=False,
187
+ )
188
+ raw_out = response.json()
189
+
190
+ raw_output = raw_out["choices"][0]["text"]
191
+ tool_calls = extract_tool_call_info(raw_output)
192
+ if len(tool_calls) == 0:
193
+ # No tool calls
194
+ msg = raw_output
195
+ break
196
+ else:
197
+ for tool_call in tool_calls:
198
+ tool_call_name = tool_call['function']['name']
199
+ tool_call_arguments = json.loads(tool_call['function']['arguments'])
200
+ tool_function = tool_map[tool_call_name]
201
+ tool_result = tool_function(tool_call_arguments)
202
+
203
+ messages.append({
204
+ "role": "tool",
205
+ "tool_call_id": tool_call['id'],
206
+ "name": tool_call_name,
207
+ "content": json.dumps(tool_result),
208
+ })
209
+ print('-' * 100)
210
+ print(msg)
211
+ ```
212
+ Here, `extract_tool_call_info` parses the model output and returns the model call information. A simple implementation would be:
213
+ ```python
214
+ def extract_tool_call_info(tool_call_rsp: str):
215
+ if '<|tool_calls_section_begin|>' not in tool_call_rsp:
216
+ # No tool calls
217
+ return []
218
+ import re
219
+ pattern = r"<\|tool_calls_section_begin\|>(.*?)<\|tool_calls_section_end\|>"
220
+
221
+ tool_calls_sections = re.findall(pattern, tool_call_rsp, re.DOTALL)
222
+
223
+ # Extract multiple tool calls
224
+ func_call_pattern = r"<\|tool_call_begin\|>\s*(?P<tool_call_id>[\w\.]+:\d+)\s*<\|tool_call_argument_begin\|>\s*(?P<function_arguments>.*?)\s*<\|tool_call_end\|>"
225
+ tool_calls = []
226
+ for match in re.findall(func_call_pattern, tool_calls_sections[0], re.DOTALL):
227
+ function_id, function_args = match
228
+ # function_id: functions.get_weather:0
229
+ function_name = function_id.split('.')[1].split(':')[0]
230
+ tool_calls.append(
231
+ {
232
+ "id": function_id,
233
+ "type": "function",
234
+ "function": {
235
+ "name": function_name,
236
+ "arguments": function_args
237
+ }
238
+ }
239
+ )
240
+ return tool_calls
241
+ ```
figures/Base-Evaluation.png ADDED

Git LFS Details

  • SHA256: d1d3ee49430417c17326c9def19264756a3bc0b0aa001e598d0e0d751ebf93f8
  • Pointer size: 131 Bytes
  • Size of remote file: 245 kB
figures/banner.png ADDED

Git LFS Details

  • SHA256: 380b39db25a6842cedaabad354a0a4929b617835094800124bba756c3b0e98f8
  • Pointer size: 131 Bytes
  • Size of remote file: 292 kB
figures/kimi-logo.png ADDED
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_length": 131072,
3
+ "eos_token_id": 163586
4
+ }
kimi-logo.png ADDED
model-1-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7383ae82886098e3355c7f58c806acc23b2eb021e7fad6fa406b6528841425b7
3
+ size 3343812312
model-10-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b21d08f2cb6dc040e256ee9871c6aa151bbba09f51a017ae9fc11d1b55a15e19
3
+ size 34118878784
model-11-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb2220d6d97dd218acc9a3f22d275cbce99465e436abbeb760372483917f6ae7
3
+ size 34118879952
model-12-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33e0a357983e1ac3765ec8bf07928a6764e2540116be00bc8ffa95a0bbbeec6b
3
+ size 34118879952
model-14-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aba47f6864348191641d1187fe4dcabd0197180254a51e02797825bcd7a096c0
3
+ size 34118879952
model-17-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:427226868a21cb6a4704a5a744ff08c9a3a75f531e1eeb92a02c56767fe91d52
3
+ size 34118879952
model-19-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8cf771ece90219517290dc8d3bde1a2db68343bd376d64d4ef890cf0a2d6fe3d
3
+ size 34118879952
model-20-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:572dfc07d04237b356af6e118c333fe3dbfc25f9f21f01f35a7651f711a8a336
3
+ size 34118879952
model-22-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebf12f7c32d3793deebc83384fc1ffea2a9e191467ec67b4048d4dd9cecae3ae
3
+ size 34118879952
model-23-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aaa9a31a77789432354d7cec5265183a28b7e77b8a0bf0ab5c6e42ef72696484
3
+ size 34118879952
model-25-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fcf4477fa1d57e795c063fb0e5c64790784efc4b56e62fe18a263ab3c218f24c
3
+ size 34118879952
model-28-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5b3d405c6bbaf5b54df594fb30391f17df94c4ef499c674e628d31f72f61d56
3
+ size 34118879952
model-31-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71215a48d38a45cdcc173ed78a6fa730546cd1a78e1cf8bd0f4017fd9f643511
3
+ size 34118879952
model-32-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba1b1db54c6d0d559b58f69aa472998ae54a876f2271e300ed155ca1eff13ce0
3
+ size 34118879952
model-34-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9abf313b1b0ee85970af16d07bbf075b938a18b75de67935d53abad408db9181
3
+ size 34118879952
model-35-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e390859e25b0b9db65a9d0501ae3d2690a3d62a1a75c18978c8f13e4fb46640c
3
+ size 34118879952
model-36-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:947ab77bdc30cee2b195bb130eed6078b4a0f5b5abcd147e1599daf718eb7c91
3
+ size 34118879952
model-40-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86fe2f537295c6ff4f6c4c58a9679dee694d50eff54dc5aea222bb8f6a68ff8a
3
+ size 34118879952
model-43-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86f656e23695230bf44124e5ffea130ac45ca011eac29a8f1e86c7c509feeff6
3
+ size 34118879952
model-45-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e89ab6450c8720244ccf561cbbe1b36674c25457a77f249ca3a02fd7f4f57e1e
3
+ size 34118879952
model-48-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:727a5f69a30dc142722994f68b2df3b5e6c09a71c5ae82c79ec63328bef8d024
3
+ size 34118879952
model-49-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17d26f413355882e608d0a12e3cafc0f1b0781caadb817b43abc38924e25a2f8
3
+ size 34118879952
model-5-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ff7b77b7c7643bc6ac02aa7a776d9ec9d4e89d23bc5b86f0057c3c395e57615
3
+ size 34118878784
model-51-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0fd40dfbaedb8beea209993f01c2325d924ef3c7d93291008d3f05162fd38e2d
3
+ size 34118879952
model-52-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b3d0f05bc0185f97923370402c92581a3f84a07b40ef758c653deaab32893ad
3
+ size 34118879952
model-53-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21aa25fa7f6c2baef7e826528dd1e039ca2a690cf0421d43614586e1025a3549
3
+ size 34118879952
model-54-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29969057a26e63e3d59cd0ad6577edfb79240b77507986bd4d783840edb1c2ad
3
+ size 34118879952
model-58-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92233fb9f2bdb6115321006a6502f62837aab2df94d68bbfe489980e844c0562
3
+ size 34118879952
model-59-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:624a775545fd2e084bf777bfd87d8f0a5294a2cb53e1995307b3ce43374f0aa9
3
+ size 34118879952
model-6-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70b9ce34eeed3871bdbdfab1564115e907c0620dd1fb2ae26e1a0d005c847882
3
+ size 34118878784
model-7-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cec49be0228e1286c761c15edb403a2827ec836b06c6a64e01bbdffc9a5a2735
3
+ size 34118878784
model-8-of-61.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3152bbb1e5b1cd4fb83b13f351a8d3df75931440225f658f9d37036ae5e42c5
3
+ size 34118878784
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_deepseek.py ADDED
@@ -0,0 +1,1849 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_deepseek import DeepseekV3Config
58
+ import torch.distributed as dist
59
+ import numpy as np
60
+
61
+ if is_flash_attn_2_available():
62
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
63
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
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 = "DeepseekV3Config"
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(
85
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
86
+ )
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+
94
+ class DeepseekV3RMSNorm(nn.Module):
95
+ def __init__(self, hidden_size, eps=1e-6):
96
+ """
97
+ DeepseekV3RMSNorm 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(DeepseekV3RMSNorm)
112
+
113
+
114
+ class DeepseekV3RotaryEmbedding(nn.Module):
115
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
116
+ super().__init__()
117
+
118
+ self.dim = dim
119
+ self.max_position_embeddings = max_position_embeddings
120
+ self.base = base
121
+ inv_freq = 1.0 / (
122
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
123
+ )
124
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
125
+
126
+ # Build here to make `torch.jit.trace` work.
127
+ self._set_cos_sin_cache(
128
+ seq_len=max_position_embeddings,
129
+ device=self.inv_freq.device,
130
+ dtype=torch.get_default_dtype(),
131
+ )
132
+ self.max_seq_len_cached = None
133
+
134
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
135
+ self.max_seq_len_cached = seq_len
136
+ t = torch.arange(
137
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
138
+ )
139
+
140
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
141
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
142
+ emb = torch.cat((freqs, freqs), dim=-1)
143
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
144
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
145
+
146
+ def forward(self, x, seq_len=None):
147
+ # x: [bs, num_attention_heads, seq_len, head_size]
148
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
149
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
150
+
151
+ return (
152
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
153
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
154
+ )
155
+
156
+
157
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV3
158
+ class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
159
+ """DeepseekV3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
160
+
161
+ def __init__(
162
+ self,
163
+ dim,
164
+ max_position_embeddings=2048,
165
+ base=10000,
166
+ device=None,
167
+ scaling_factor=1.0,
168
+ ):
169
+ self.scaling_factor = scaling_factor
170
+ super().__init__(dim, max_position_embeddings, base, device)
171
+
172
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
173
+ self.max_seq_len_cached = seq_len
174
+ t = torch.arange(
175
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
176
+ )
177
+ t = t / self.scaling_factor
178
+
179
+ freqs = torch.outer(t, self.inv_freq)
180
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
181
+ emb = torch.cat((freqs, freqs), dim=-1)
182
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
183
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
184
+
185
+
186
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV3
187
+ class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
188
+ """DeepseekV3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
189
+
190
+ def __init__(
191
+ self,
192
+ dim,
193
+ max_position_embeddings=2048,
194
+ base=10000,
195
+ device=None,
196
+ scaling_factor=1.0,
197
+ ):
198
+ self.scaling_factor = scaling_factor
199
+ super().__init__(dim, max_position_embeddings, base, device)
200
+
201
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
202
+ self.max_seq_len_cached = seq_len
203
+
204
+ if seq_len > self.max_position_embeddings:
205
+ base = self.base * (
206
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
207
+ - (self.scaling_factor - 1)
208
+ ) ** (self.dim / (self.dim - 2))
209
+ inv_freq = 1.0 / (
210
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
211
+ )
212
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
213
+
214
+ t = torch.arange(
215
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
216
+ )
217
+
218
+ freqs = torch.outer(t, self.inv_freq)
219
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
220
+ emb = torch.cat((freqs, freqs), dim=-1)
221
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
222
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
223
+
224
+
225
+ # Inverse dim formula to find dim based on number of rotations
226
+ def yarn_find_correction_dim(
227
+ num_rotations, dim, base=10000, max_position_embeddings=2048
228
+ ):
229
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
230
+ 2 * math.log(base)
231
+ )
232
+
233
+
234
+ # Find dim range bounds based on rotations
235
+ def yarn_find_correction_range(
236
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
237
+ ):
238
+ low = math.floor(
239
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
240
+ )
241
+ high = math.ceil(
242
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
243
+ )
244
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
245
+
246
+
247
+ def yarn_get_mscale(scale=1, mscale=1):
248
+ if scale <= 1:
249
+ return 1.0
250
+ return 0.1 * mscale * math.log(scale) + 1.0
251
+
252
+
253
+ def yarn_linear_ramp_mask(min, max, dim):
254
+ if min == max:
255
+ max += 0.001 # Prevent singularity
256
+
257
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
258
+ ramp_func = torch.clamp(linear_func, 0, 1)
259
+ return ramp_func
260
+
261
+
262
+ class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding):
263
+
264
+ def __init__(
265
+ self,
266
+ dim,
267
+ max_position_embeddings=2048,
268
+ base=10000,
269
+ device=None,
270
+ scaling_factor=1.0,
271
+ original_max_position_embeddings=4096,
272
+ beta_fast=32,
273
+ beta_slow=1,
274
+ mscale=1,
275
+ mscale_all_dim=0,
276
+ ):
277
+ self.scaling_factor = scaling_factor
278
+ self.original_max_position_embeddings = original_max_position_embeddings
279
+ self.beta_fast = beta_fast
280
+ self.beta_slow = beta_slow
281
+ self.mscale = mscale
282
+ self.mscale_all_dim = mscale_all_dim
283
+ super().__init__(dim, max_position_embeddings, base, device)
284
+
285
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
286
+ self.max_seq_len_cached = seq_len
287
+ dim = self.dim
288
+
289
+ freq_extra = 1.0 / (
290
+ self.base
291
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
292
+ )
293
+ freq_inter = 1.0 / (
294
+ self.scaling_factor
295
+ * self.base
296
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
297
+ )
298
+
299
+ low, high = yarn_find_correction_range(
300
+ self.beta_fast,
301
+ self.beta_slow,
302
+ dim,
303
+ self.base,
304
+ self.original_max_position_embeddings,
305
+ )
306
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
307
+ device=device, dtype=torch.float32
308
+ )
309
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
310
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
311
+
312
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
313
+
314
+ freqs = torch.outer(t, inv_freq)
315
+
316
+ _mscale = float(
317
+ yarn_get_mscale(self.scaling_factor, self.mscale)
318
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
319
+ )
320
+
321
+ emb = torch.cat((freqs, freqs), dim=-1)
322
+ self.register_buffer(
323
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
324
+ )
325
+ self.register_buffer(
326
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
327
+ )
328
+
329
+
330
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
331
+ def rotate_half(x):
332
+ """Rotates half the hidden dims of the input."""
333
+ x1 = x[..., : x.shape[-1] // 2]
334
+ x2 = x[..., x.shape[-1] // 2 :]
335
+ return torch.cat((-x2, x1), dim=-1)
336
+
337
+
338
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
339
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
340
+ """Applies Rotary Position Embedding to the query and key tensors.
341
+
342
+ Args:
343
+ q (`torch.Tensor`): The query tensor.
344
+ k (`torch.Tensor`): The key tensor.
345
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
346
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
347
+ position_ids (`torch.Tensor`):
348
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
349
+ used to pass offsetted position ids when working with a KV-cache.
350
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
351
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
352
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
353
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
354
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
355
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
356
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
357
+ Returns:
358
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
359
+ """
360
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
361
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
362
+
363
+ b, h, s, d = q.shape
364
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
365
+
366
+ b, h, s, d = k.shape
367
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
368
+
369
+ q_embed = (q * cos) + (rotate_half(q) * sin)
370
+ k_embed = (k * cos) + (rotate_half(k) * sin)
371
+ return q_embed, k_embed
372
+
373
+
374
+ class DeepseekV3MLP(nn.Module):
375
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
376
+ super().__init__()
377
+ self.config = config
378
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
379
+ self.intermediate_size = (
380
+ config.intermediate_size if intermediate_size is None else intermediate_size
381
+ )
382
+
383
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
384
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
385
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
386
+ self.act_fn = ACT2FN[config.hidden_act]
387
+
388
+ def forward(self, x):
389
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
390
+ return down_proj
391
+
392
+
393
+ class MoEGate(nn.Module):
394
+ def __init__(self, config):
395
+ super().__init__()
396
+ self.config = config
397
+ self.top_k = config.num_experts_per_tok
398
+ self.n_routed_experts = config.n_routed_experts
399
+ self.routed_scaling_factor = config.routed_scaling_factor
400
+ self.scoring_func = config.scoring_func
401
+ self.seq_aux = config.seq_aux
402
+ self.topk_method = config.topk_method
403
+ self.n_group = config.n_group
404
+ self.topk_group = config.topk_group
405
+
406
+ # topk selection algorithm
407
+ self.norm_topk_prob = config.norm_topk_prob
408
+ self.gating_dim = config.hidden_size
409
+ self.weight = nn.Parameter(
410
+ torch.empty((self.n_routed_experts, self.gating_dim))
411
+ )
412
+ if self.topk_method == "noaux_tc":
413
+ self.e_score_correction_bias = nn.Parameter(
414
+ torch.empty((self.n_routed_experts))
415
+ )
416
+ self.reset_parameters()
417
+
418
+ def reset_parameters(self) -> None:
419
+ import torch.nn.init as init
420
+
421
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
422
+
423
+ def forward(self, hidden_states):
424
+ bsz, seq_len, h = hidden_states.shape
425
+ ### compute gating score
426
+ hidden_states = hidden_states.view(-1, h)
427
+ logits = F.linear(
428
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
429
+ )
430
+ if self.scoring_func == "sigmoid":
431
+ scores = logits.sigmoid()
432
+ else:
433
+ raise NotImplementedError(
434
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
435
+ )
436
+
437
+ ### select top-k experts
438
+ if self.topk_method == "noaux_tc":
439
+ assert not self.training
440
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
441
+ group_scores = (
442
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
443
+ ) # [n, n_group]
444
+ group_idx = torch.topk(
445
+ group_scores, k=self.topk_group, dim=-1, sorted=False
446
+ )[
447
+ 1
448
+ ] # [n, top_k_group]
449
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
450
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
451
+ score_mask = (
452
+ group_mask.unsqueeze(-1)
453
+ .expand(
454
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
455
+ )
456
+ .reshape(bsz * seq_len, -1)
457
+ ) # [n, e]
458
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
459
+ _, topk_idx = torch.topk(
460
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
461
+ )
462
+ topk_weight = scores.gather(1, topk_idx)
463
+ else:
464
+ raise NotImplementedError(
465
+ f"insupportable TopK function for MoE gating: {self.topk_method}"
466
+ )
467
+
468
+ ### norm gate to sum 1
469
+ if self.top_k > 1 and self.norm_topk_prob:
470
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
471
+ topk_weight = topk_weight / denominator
472
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
473
+
474
+ return topk_idx, topk_weight
475
+
476
+ class DeepseekV3MoE(nn.Module):
477
+ """
478
+ A mixed expert module containing shared experts.
479
+ """
480
+
481
+ def __init__(self, config):
482
+ super().__init__()
483
+ self.config = config
484
+ self.num_experts_per_tok = config.num_experts_per_tok
485
+
486
+ if hasattr(config, "ep_size") and config.ep_size > 1:
487
+ assert config.ep_size == dist.get_world_size()
488
+ self.ep_size = config.ep_size
489
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
490
+ self.ep_rank = dist.get_rank()
491
+ self.experts = nn.ModuleList(
492
+ [
493
+ (
494
+ DeepseekV3MLP(
495
+ config, intermediate_size=config.moe_intermediate_size
496
+ )
497
+ if i >= self.ep_rank * self.experts_per_rank
498
+ and i < (self.ep_rank + 1) * self.experts_per_rank
499
+ else None
500
+ )
501
+ for i in range(config.n_routed_experts)
502
+ ]
503
+ )
504
+ else:
505
+ self.ep_size = 1
506
+ self.experts_per_rank = config.n_routed_experts
507
+ self.ep_rank = 0
508
+ self.experts = nn.ModuleList(
509
+ [
510
+ DeepseekV3MLP(
511
+ config, intermediate_size=config.moe_intermediate_size
512
+ )
513
+ for i in range(config.n_routed_experts)
514
+ ]
515
+ )
516
+ self.gate = MoEGate(config)
517
+ if config.n_shared_experts is not None:
518
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
519
+ self.shared_experts = DeepseekV3MLP(
520
+ config=config, intermediate_size=intermediate_size
521
+ )
522
+
523
+ def forward(self, hidden_states):
524
+ identity = hidden_states
525
+ orig_shape = hidden_states.shape
526
+ topk_idx, topk_weight = self.gate(hidden_states)
527
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
528
+ flat_topk_idx = topk_idx.view(-1)
529
+ if not self.training:
530
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
531
+ if self.config.n_shared_experts is not None:
532
+ y = y + self.shared_experts(identity)
533
+ return y
534
+
535
+ @torch.no_grad()
536
+ def moe_infer(self, x, topk_ids, topk_weight):
537
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
538
+ cnts.scatter_(1, topk_ids, 1)
539
+ tokens_per_expert = cnts.sum(dim=0)
540
+ idxs = topk_ids.view(-1).argsort()
541
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
542
+ sorted_tokens_shape = sorted_tokens.shape
543
+ if self.ep_size > 1:
544
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
545
+ tokens_per_expert_group = tokens_per_expert.new_empty(
546
+ tokens_per_expert.shape[0]
547
+ )
548
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
549
+ output_splits = (
550
+ tokens_per_expert_group.view(self.ep_size, -1)
551
+ .sum(1)
552
+ .cpu()
553
+ .numpy()
554
+ .tolist()
555
+ )
556
+ gathered_tokens = sorted_tokens.new_empty(
557
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
558
+ )
559
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
560
+ dist.all_to_all(
561
+ list(gathered_tokens.split(output_splits)),
562
+ list(sorted_tokens.split(input_split_sizes)),
563
+ )
564
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
565
+ self.ep_size, self.experts_per_rank
566
+ ).sum(dim=0)
567
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
568
+ s = 0
569
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
570
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
571
+ s += k
572
+ gatherd_idxs = gatherd_idxs.argsort()
573
+ sorted_tokens = gathered_tokens[gatherd_idxs]
574
+ tokens_per_expert = tokens_per_expert_post_gather
575
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
576
+
577
+ outputs = []
578
+ start_idx = 0
579
+ for i, num_tokens in enumerate(tokens_per_expert):
580
+ end_idx = start_idx + num_tokens
581
+ if num_tokens == 0:
582
+ continue
583
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
584
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
585
+ expert_out = expert(tokens_for_this_expert)
586
+ outputs.append(expert_out)
587
+ start_idx = end_idx
588
+
589
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
590
+ if self.ep_size > 1:
591
+ new_x = torch.empty_like(outs)
592
+ new_x[gatherd_idxs] = outs
593
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
594
+ dist.all_to_all(
595
+ list(gathered_tokens.split(input_split_sizes)),
596
+ list(new_x.split(output_splits)),
597
+ )
598
+ outs = gathered_tokens
599
+
600
+ new_x = torch.empty_like(outs)
601
+ new_x[idxs] = outs
602
+ final_out = (
603
+ new_x.view(*topk_ids.shape, -1)
604
+ .type(topk_weight.dtype)
605
+ .mul_(topk_weight.unsqueeze(dim=-1))
606
+ .sum(dim=1)
607
+ .type(new_x.dtype)
608
+ )
609
+ return final_out
610
+
611
+
612
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
613
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
614
+ """
615
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
616
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
617
+ """
618
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
619
+ if n_rep == 1:
620
+ return hidden_states
621
+ hidden_states = hidden_states[:, :, None, :, :].expand(
622
+ batch, num_key_value_heads, n_rep, slen, head_dim
623
+ )
624
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
625
+
626
+
627
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV3
628
+ class DeepseekV3Attention(nn.Module):
629
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
630
+
631
+ def __init__(self, config: DeepseekV3Config, layer_idx: Optional[int] = None):
632
+ super().__init__()
633
+ self.config = config
634
+ self.layer_idx = layer_idx
635
+ if layer_idx is None:
636
+ logger.warning_once(
637
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
638
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
639
+ "when creating this class."
640
+ )
641
+
642
+ self.attention_dropout = config.attention_dropout
643
+ self.hidden_size = config.hidden_size
644
+ self.num_heads = config.num_attention_heads
645
+
646
+ self.max_position_embeddings = config.max_position_embeddings
647
+ self.rope_theta = config.rope_theta
648
+ self.q_lora_rank = config.q_lora_rank
649
+ self.qk_rope_head_dim = config.qk_rope_head_dim
650
+ self.kv_lora_rank = config.kv_lora_rank
651
+ self.v_head_dim = config.v_head_dim
652
+ self.qk_nope_head_dim = config.qk_nope_head_dim
653
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
654
+
655
+ self.is_causal = True
656
+
657
+ if self.q_lora_rank is None:
658
+ self.q_proj = nn.Linear(
659
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
660
+ )
661
+ else:
662
+ self.q_a_proj = nn.Linear(
663
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
664
+ )
665
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
666
+ self.q_b_proj = nn.Linear(
667
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
668
+ )
669
+
670
+ self.kv_a_proj_with_mqa = nn.Linear(
671
+ self.hidden_size,
672
+ config.kv_lora_rank + config.qk_rope_head_dim,
673
+ bias=config.attention_bias,
674
+ )
675
+ self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank)
676
+ self.kv_b_proj = nn.Linear(
677
+ config.kv_lora_rank,
678
+ self.num_heads
679
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
680
+ bias=False,
681
+ )
682
+
683
+ self.o_proj = nn.Linear(
684
+ self.num_heads * self.v_head_dim,
685
+ self.hidden_size,
686
+ bias=config.attention_bias,
687
+ )
688
+ self._init_rope()
689
+
690
+ self.softmax_scale = self.q_head_dim ** (-0.5)
691
+ if self.config.rope_scaling is not None:
692
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
693
+ scaling_factor = self.config.rope_scaling["factor"]
694
+ if mscale_all_dim:
695
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
696
+ self.softmax_scale = self.softmax_scale * mscale * mscale
697
+
698
+ def _init_rope(self):
699
+ if self.config.rope_scaling is None:
700
+ self.rotary_emb = DeepseekV3RotaryEmbedding(
701
+ self.qk_rope_head_dim,
702
+ max_position_embeddings=self.max_position_embeddings,
703
+ base=self.rope_theta,
704
+ )
705
+ else:
706
+ scaling_type = self.config.rope_scaling["type"]
707
+ scaling_factor = self.config.rope_scaling["factor"]
708
+ if scaling_type == "linear":
709
+ self.rotary_emb = DeepseekV3LinearScalingRotaryEmbedding(
710
+ self.qk_rope_head_dim,
711
+ max_position_embeddings=self.max_position_embeddings,
712
+ scaling_factor=scaling_factor,
713
+ base=self.rope_theta,
714
+ )
715
+ elif scaling_type == "dynamic":
716
+ self.rotary_emb = DeepseekV3DynamicNTKScalingRotaryEmbedding(
717
+ self.qk_rope_head_dim,
718
+ max_position_embeddings=self.max_position_embeddings,
719
+ scaling_factor=scaling_factor,
720
+ base=self.rope_theta,
721
+ )
722
+ elif scaling_type == "yarn":
723
+ kwargs = {
724
+ key: self.config.rope_scaling[key]
725
+ for key in [
726
+ "original_max_position_embeddings",
727
+ "beta_fast",
728
+ "beta_slow",
729
+ "mscale",
730
+ "mscale_all_dim",
731
+ ]
732
+ if key in self.config.rope_scaling
733
+ }
734
+ self.rotary_emb = DeepseekV3YarnRotaryEmbedding(
735
+ self.qk_rope_head_dim,
736
+ max_position_embeddings=self.max_position_embeddings,
737
+ scaling_factor=scaling_factor,
738
+ base=self.rope_theta,
739
+ **kwargs,
740
+ )
741
+ else:
742
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
743
+
744
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
745
+ return (
746
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
747
+ .transpose(1, 2)
748
+ .contiguous()
749
+ )
750
+
751
+ def forward(
752
+ self,
753
+ hidden_states: torch.Tensor,
754
+ attention_mask: Optional[torch.Tensor] = None,
755
+ position_ids: Optional[torch.LongTensor] = None,
756
+ past_key_value: Optional[Cache] = None,
757
+ output_attentions: bool = False,
758
+ use_cache: bool = False,
759
+ **kwargs,
760
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
761
+ if "padding_mask" in kwargs:
762
+ warnings.warn(
763
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
764
+ )
765
+ bsz, q_len, _ = hidden_states.size()
766
+
767
+ if self.q_lora_rank is None:
768
+ q = self.q_proj(hidden_states)
769
+ else:
770
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
771
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
772
+ q_nope, q_pe = torch.split(
773
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
774
+ )
775
+
776
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
777
+ compressed_kv, k_pe = torch.split(
778
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
779
+ )
780
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
781
+ kv = (
782
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
783
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
784
+ .transpose(1, 2)
785
+ )
786
+
787
+ k_nope, value_states = torch.split(
788
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
789
+ )
790
+ kv_seq_len = value_states.shape[-2]
791
+ if past_key_value is not None:
792
+ if self.layer_idx is None:
793
+ raise ValueError(
794
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
795
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
796
+ "with a layer index."
797
+ )
798
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
799
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
800
+
801
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
802
+
803
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
804
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
805
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
806
+
807
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
808
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
809
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
810
+ if past_key_value is not None:
811
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
812
+ key_states, value_states = past_key_value.update(
813
+ key_states, value_states, self.layer_idx, cache_kwargs
814
+ )
815
+
816
+ attn_weights = (
817
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
818
+ )
819
+
820
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
821
+ raise ValueError(
822
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
823
+ f" {attn_weights.size()}"
824
+ )
825
+ assert attention_mask is not None
826
+ if attention_mask is not None:
827
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
828
+ raise ValueError(
829
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
830
+ )
831
+ attn_weights = attn_weights + attention_mask
832
+
833
+ # upcast attention to fp32
834
+ attn_weights = nn.functional.softmax(
835
+ attn_weights, dim=-1, dtype=torch.float32
836
+ ).to(query_states.dtype)
837
+ attn_weights = nn.functional.dropout(
838
+ attn_weights, p=self.attention_dropout, training=self.training
839
+ )
840
+ attn_output = torch.matmul(attn_weights, value_states)
841
+
842
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
843
+ raise ValueError(
844
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
845
+ f" {attn_output.size()}"
846
+ )
847
+
848
+ attn_output = attn_output.transpose(1, 2).contiguous()
849
+
850
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
851
+
852
+ attn_output = self.o_proj(attn_output)
853
+
854
+ if not output_attentions:
855
+ attn_weights = None
856
+
857
+ return attn_output, attn_weights, past_key_value
858
+
859
+
860
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV3
861
+ class DeepseekV3FlashAttention2(DeepseekV3Attention):
862
+ """
863
+ DeepseekV3 flash attention module. This module inherits from `DeepseekV3Attention` as the weights of the module stays
864
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
865
+ flash attention and deal with padding tokens in case the input contains any of them.
866
+ """
867
+
868
+ def __init__(self, *args, **kwargs):
869
+ super().__init__(*args, **kwargs)
870
+
871
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
872
+ # 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.
873
+ # 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).
874
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
875
+
876
+ def forward(
877
+ self,
878
+ hidden_states: torch.Tensor,
879
+ attention_mask: Optional[torch.LongTensor] = None,
880
+ position_ids: Optional[torch.LongTensor] = None,
881
+ past_key_value: Optional[Cache] = None,
882
+ output_attentions: bool = False,
883
+ use_cache: bool = False,
884
+ **kwargs,
885
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
886
+ # DeepseekV3FlashAttention2 attention does not support output_attentions
887
+ if "padding_mask" in kwargs:
888
+ warnings.warn(
889
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
890
+ )
891
+
892
+ # overwrite attention_mask with padding_mask
893
+ attention_mask = kwargs.pop("padding_mask")
894
+
895
+ output_attentions = False
896
+
897
+ bsz, q_len, _ = hidden_states.size()
898
+
899
+ if self.q_lora_rank is None:
900
+ q = self.q_proj(hidden_states)
901
+ else:
902
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
903
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
904
+ q_nope, q_pe = torch.split(
905
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
906
+ )
907
+
908
+ # Flash attention requires the input to have the shape
909
+ # batch_size x seq_length x head_dim x hidden_dim
910
+ # therefore we just need to keep the original shape
911
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
912
+ compressed_kv, k_pe = torch.split(
913
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
914
+ )
915
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
916
+ kv = (
917
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
918
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
919
+ .transpose(1, 2)
920
+ )
921
+
922
+ k_nope, value_states = torch.split(
923
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
924
+ )
925
+ kv_seq_len = value_states.shape[-2]
926
+
927
+ kv_seq_len = value_states.shape[-2]
928
+ if past_key_value is not None:
929
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
930
+
931
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
932
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
933
+
934
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
935
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
936
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
937
+
938
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
939
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
940
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
941
+
942
+ if self.q_head_dim != self.v_head_dim:
943
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
944
+
945
+ if past_key_value is not None:
946
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
947
+ key_states, value_states = past_key_value.update(
948
+ key_states, value_states, self.layer_idx, cache_kwargs
949
+ )
950
+
951
+ # 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
952
+ # to be able to avoid many of these transpose/reshape/view.
953
+ query_states = query_states.transpose(1, 2)
954
+ key_states = key_states.transpose(1, 2)
955
+ value_states = value_states.transpose(1, 2)
956
+
957
+ dropout_rate = self.attention_dropout if self.training else 0.0
958
+
959
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
960
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
961
+ # cast them back in the correct dtype just to be sure everything works as expected.
962
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
963
+ # in fp32. (DeepseekV3RMSNorm handles it correctly)
964
+
965
+ input_dtype = query_states.dtype
966
+ if input_dtype == torch.float32:
967
+ # Handle the case where the model is quantized
968
+ if hasattr(self.config, "_pre_quantization_dtype"):
969
+ target_dtype = self.config._pre_quantization_dtype
970
+ elif torch.is_autocast_enabled():
971
+ target_dtype = torch.get_autocast_gpu_dtype()
972
+ else:
973
+ target_dtype = (
974
+ self.q_proj.weight.dtype
975
+ if self.q_lora_rank is None
976
+ else self.q_a_proj.weight.dtype
977
+ )
978
+
979
+ logger.warning_once(
980
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
981
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
982
+ f" {target_dtype}."
983
+ )
984
+
985
+ query_states = query_states.to(target_dtype)
986
+ key_states = key_states.to(target_dtype)
987
+ value_states = value_states.to(target_dtype)
988
+
989
+ attn_output = self._flash_attention_forward(
990
+ query_states,
991
+ key_states,
992
+ value_states,
993
+ attention_mask,
994
+ q_len,
995
+ dropout=dropout_rate,
996
+ softmax_scale=self.softmax_scale,
997
+ )
998
+ if self.q_head_dim != self.v_head_dim:
999
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1000
+
1001
+ attn_output = attn_output.reshape(
1002
+ bsz, q_len, self.num_heads * self.v_head_dim
1003
+ ).contiguous()
1004
+ attn_output = self.o_proj(attn_output)
1005
+
1006
+ if not output_attentions:
1007
+ attn_weights = None
1008
+
1009
+ return attn_output, attn_weights, past_key_value
1010
+
1011
+ def _flash_attention_forward(
1012
+ self,
1013
+ query_states,
1014
+ key_states,
1015
+ value_states,
1016
+ attention_mask,
1017
+ query_length,
1018
+ dropout=0.0,
1019
+ softmax_scale=None,
1020
+ ):
1021
+ """
1022
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1023
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1024
+
1025
+ Args:
1026
+ query_states (`torch.Tensor`):
1027
+ Input query states to be passed to Flash Attention API
1028
+ key_states (`torch.Tensor`):
1029
+ Input key states to be passed to Flash Attention API
1030
+ value_states (`torch.Tensor`):
1031
+ Input value states to be passed to Flash Attention API
1032
+ attention_mask (`torch.Tensor`):
1033
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1034
+ position of padding tokens and 1 for the position of non-padding tokens.
1035
+ dropout (`int`, *optional*):
1036
+ Attention dropout
1037
+ softmax_scale (`float`, *optional*):
1038
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1039
+ """
1040
+ if not self._flash_attn_uses_top_left_mask:
1041
+ causal = self.is_causal
1042
+ else:
1043
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV3FlashAttention2 __init__.
1044
+ causal = self.is_causal and query_length != 1
1045
+
1046
+ # Contains at least one padding token in the sequence
1047
+ if attention_mask is not None:
1048
+ batch_size = query_states.shape[0]
1049
+ (
1050
+ query_states,
1051
+ key_states,
1052
+ value_states,
1053
+ indices_q,
1054
+ cu_seq_lens,
1055
+ max_seq_lens,
1056
+ ) = self._upad_input(
1057
+ query_states, key_states, value_states, attention_mask, query_length
1058
+ )
1059
+
1060
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1061
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1062
+
1063
+ attn_output_unpad = flash_attn_varlen_func(
1064
+ query_states,
1065
+ key_states,
1066
+ value_states,
1067
+ cu_seqlens_q=cu_seqlens_q,
1068
+ cu_seqlens_k=cu_seqlens_k,
1069
+ max_seqlen_q=max_seqlen_in_batch_q,
1070
+ max_seqlen_k=max_seqlen_in_batch_k,
1071
+ dropout_p=dropout,
1072
+ softmax_scale=softmax_scale,
1073
+ causal=causal,
1074
+ )
1075
+
1076
+ attn_output = pad_input(
1077
+ attn_output_unpad, indices_q, batch_size, query_length
1078
+ )
1079
+ else:
1080
+ attn_output = flash_attn_func(
1081
+ query_states,
1082
+ key_states,
1083
+ value_states,
1084
+ dropout,
1085
+ softmax_scale=softmax_scale,
1086
+ causal=causal,
1087
+ )
1088
+
1089
+ return attn_output
1090
+
1091
+ def _upad_input(
1092
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1093
+ ):
1094
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1095
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1096
+
1097
+ key_layer = index_first_axis(
1098
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1099
+ indices_k,
1100
+ )
1101
+ value_layer = index_first_axis(
1102
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1103
+ indices_k,
1104
+ )
1105
+ if query_length == kv_seq_len:
1106
+ query_layer = index_first_axis(
1107
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1108
+ indices_k,
1109
+ )
1110
+ cu_seqlens_q = cu_seqlens_k
1111
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1112
+ indices_q = indices_k
1113
+ elif query_length == 1:
1114
+ max_seqlen_in_batch_q = 1
1115
+ cu_seqlens_q = torch.arange(
1116
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1117
+ ) # There is a memcpy here, that is very bad.
1118
+ indices_q = cu_seqlens_q[:-1]
1119
+ query_layer = query_layer.squeeze(1)
1120
+ else:
1121
+ # The -q_len: slice assumes left padding.
1122
+ attention_mask = attention_mask[:, -query_length:]
1123
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1124
+ query_layer, attention_mask
1125
+ )
1126
+
1127
+ return (
1128
+ query_layer,
1129
+ key_layer,
1130
+ value_layer,
1131
+ indices_q,
1132
+ (cu_seqlens_q, cu_seqlens_k),
1133
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1134
+ )
1135
+
1136
+
1137
+ ATTENTION_CLASSES = {
1138
+ "eager": DeepseekV3Attention,
1139
+ "flash_attention_2": DeepseekV3FlashAttention2,
1140
+ }
1141
+
1142
+
1143
+ class DeepseekV3DecoderLayer(nn.Module):
1144
+ def __init__(self, config: DeepseekV3Config, layer_idx: int):
1145
+ super().__init__()
1146
+ self.hidden_size = config.hidden_size
1147
+
1148
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1149
+ config=config, layer_idx=layer_idx
1150
+ )
1151
+
1152
+ self.mlp = (
1153
+ DeepseekV3MoE(config)
1154
+ if (
1155
+ config.n_routed_experts is not None
1156
+ and layer_idx >= config.first_k_dense_replace
1157
+ and layer_idx % config.moe_layer_freq == 0
1158
+ )
1159
+ else DeepseekV3MLP(config)
1160
+ )
1161
+ self.input_layernorm = DeepseekV3RMSNorm(
1162
+ config.hidden_size, eps=config.rms_norm_eps
1163
+ )
1164
+ self.post_attention_layernorm = DeepseekV3RMSNorm(
1165
+ config.hidden_size, eps=config.rms_norm_eps
1166
+ )
1167
+
1168
+ def forward(
1169
+ self,
1170
+ hidden_states: torch.Tensor,
1171
+ attention_mask: Optional[torch.Tensor] = None,
1172
+ position_ids: Optional[torch.LongTensor] = None,
1173
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1174
+ output_attentions: Optional[bool] = False,
1175
+ use_cache: Optional[bool] = False,
1176
+ **kwargs,
1177
+ ) -> Tuple[
1178
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1179
+ ]:
1180
+ """
1181
+ Args:
1182
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1183
+ attention_mask (`torch.FloatTensor`, *optional*):
1184
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1185
+ query_sequence_length, key_sequence_length)` if default attention is used.
1186
+ output_attentions (`bool`, *optional*):
1187
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1188
+ returned tensors for more detail.
1189
+ use_cache (`bool`, *optional*):
1190
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1191
+ (see `past_key_values`).
1192
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1193
+ """
1194
+ if "padding_mask" in kwargs:
1195
+ warnings.warn(
1196
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1197
+ )
1198
+ residual = hidden_states
1199
+
1200
+ hidden_states = self.input_layernorm(hidden_states)
1201
+
1202
+ # Self Attention
1203
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1204
+ hidden_states=hidden_states,
1205
+ attention_mask=attention_mask,
1206
+ position_ids=position_ids,
1207
+ past_key_value=past_key_value,
1208
+ output_attentions=output_attentions,
1209
+ use_cache=use_cache,
1210
+ **kwargs,
1211
+ )
1212
+ hidden_states = residual + hidden_states
1213
+
1214
+ # Fully Connected
1215
+ residual = hidden_states
1216
+ hidden_states = self.post_attention_layernorm(hidden_states)
1217
+ hidden_states = self.mlp(hidden_states)
1218
+ hidden_states = residual + hidden_states
1219
+
1220
+ outputs = (hidden_states,)
1221
+
1222
+ if output_attentions:
1223
+ outputs += (self_attn_weights,)
1224
+
1225
+ if use_cache:
1226
+ outputs += (present_key_value,)
1227
+
1228
+ return outputs
1229
+
1230
+
1231
+ DeepseekV3_START_DOCSTRING = r"""
1232
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1233
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1234
+ etc.)
1235
+
1236
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1237
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1238
+ and behavior.
1239
+
1240
+ Parameters:
1241
+ config ([`DeepseekV3Config`]):
1242
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1243
+ load the weights associated with the model, only the configuration. Check out the
1244
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1245
+ """
1246
+
1247
+
1248
+ @add_start_docstrings(
1249
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1250
+ DeepseekV3_START_DOCSTRING,
1251
+ )
1252
+ class DeepseekV3PreTrainedModel(PreTrainedModel):
1253
+ config_class = DeepseekV3Config
1254
+ base_model_prefix = "model"
1255
+ supports_gradient_checkpointing = True
1256
+ _no_split_modules = ["DeepseekV3DecoderLayer"]
1257
+ _skip_keys_device_placement = "past_key_values"
1258
+ _supports_flash_attn_2 = True
1259
+ _supports_cache_class = True
1260
+
1261
+ def _init_weights(self, module):
1262
+ std = self.config.initializer_range
1263
+ if isinstance(module, nn.Linear):
1264
+ module.weight.data.normal_(mean=0.0, std=std)
1265
+ if module.bias is not None:
1266
+ module.bias.data.zero_()
1267
+ elif isinstance(module, nn.Embedding):
1268
+ module.weight.data.normal_(mean=0.0, std=std)
1269
+ if module.padding_idx is not None:
1270
+ module.weight.data[module.padding_idx].zero_()
1271
+
1272
+
1273
+ DeepseekV3_INPUTS_DOCSTRING = r"""
1274
+ Args:
1275
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1276
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1277
+ it.
1278
+
1279
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1280
+ [`PreTrainedTokenizer.__call__`] for details.
1281
+
1282
+ [What are input IDs?](../glossary#input-ids)
1283
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1284
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1285
+
1286
+ - 1 for tokens that are **not masked**,
1287
+ - 0 for tokens that are **masked**.
1288
+
1289
+ [What are attention masks?](../glossary#attention-mask)
1290
+
1291
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1292
+ [`PreTrainedTokenizer.__call__`] for details.
1293
+
1294
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1295
+ `past_key_values`).
1296
+
1297
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1298
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1299
+ information on the default strategy.
1300
+
1301
+ - 1 indicates the head is **not masked**,
1302
+ - 0 indicates the head is **masked**.
1303
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1304
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1305
+ config.n_positions - 1]`.
1306
+
1307
+ [What are position IDs?](../glossary#position-ids)
1308
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1309
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1310
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1311
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1312
+
1313
+ Two formats are allowed:
1314
+ - a [`~cache_utils.Cache`] instance;
1315
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1316
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1317
+ cache format.
1318
+
1319
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1320
+ legacy cache format will be returned.
1321
+
1322
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1323
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1324
+ of shape `(batch_size, sequence_length)`.
1325
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1326
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1327
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1328
+ model's internal embedding lookup matrix.
1329
+ use_cache (`bool`, *optional*):
1330
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1331
+ `past_key_values`).
1332
+ output_attentions (`bool`, *optional*):
1333
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1334
+ tensors for more detail.
1335
+ output_hidden_states (`bool`, *optional*):
1336
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1337
+ more detail.
1338
+ return_dict (`bool`, *optional*):
1339
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1340
+ """
1341
+
1342
+
1343
+ @add_start_docstrings(
1344
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1345
+ DeepseekV3_START_DOCSTRING,
1346
+ )
1347
+ class DeepseekV3Model(DeepseekV3PreTrainedModel):
1348
+ """
1349
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`]
1350
+
1351
+ Args:
1352
+ config: DeepseekV3Config
1353
+ """
1354
+
1355
+ def __init__(self, config: DeepseekV3Config):
1356
+ super().__init__(config)
1357
+ self.padding_idx = config.pad_token_id
1358
+ self.vocab_size = config.vocab_size
1359
+
1360
+ self.embed_tokens = nn.Embedding(
1361
+ config.vocab_size, config.hidden_size, self.padding_idx
1362
+ )
1363
+ self.layers = nn.ModuleList(
1364
+ [
1365
+ DeepseekV3DecoderLayer(config, layer_idx)
1366
+ for layer_idx in range(config.num_hidden_layers)
1367
+ ]
1368
+ )
1369
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1370
+ self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1371
+
1372
+ self.gradient_checkpointing = False
1373
+ # Initialize weights and apply final processing
1374
+ self.post_init()
1375
+
1376
+ def get_input_embeddings(self):
1377
+ return self.embed_tokens
1378
+
1379
+ def set_input_embeddings(self, value):
1380
+ self.embed_tokens = value
1381
+
1382
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1383
+ def forward(
1384
+ self,
1385
+ input_ids: torch.LongTensor = None,
1386
+ attention_mask: Optional[torch.Tensor] = None,
1387
+ position_ids: Optional[torch.LongTensor] = None,
1388
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1389
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1390
+ use_cache: Optional[bool] = None,
1391
+ output_attentions: Optional[bool] = None,
1392
+ output_hidden_states: Optional[bool] = None,
1393
+ return_dict: Optional[bool] = None,
1394
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1395
+ output_attentions = (
1396
+ output_attentions
1397
+ if output_attentions is not None
1398
+ else self.config.output_attentions
1399
+ )
1400
+ output_hidden_states = (
1401
+ output_hidden_states
1402
+ if output_hidden_states is not None
1403
+ else self.config.output_hidden_states
1404
+ )
1405
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1406
+
1407
+ return_dict = (
1408
+ return_dict if return_dict is not None else self.config.use_return_dict
1409
+ )
1410
+
1411
+ # retrieve input_ids and inputs_embeds
1412
+ if input_ids is not None and inputs_embeds is not None:
1413
+ raise ValueError(
1414
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1415
+ )
1416
+ elif input_ids is not None:
1417
+ batch_size, seq_length = input_ids.shape[:2]
1418
+ elif inputs_embeds is not None:
1419
+ batch_size, seq_length = inputs_embeds.shape[:2]
1420
+ else:
1421
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1422
+
1423
+ past_key_values_length = 0
1424
+ if use_cache:
1425
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1426
+ if use_legacy_cache:
1427
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1428
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1429
+
1430
+ if position_ids is None:
1431
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1432
+ position_ids = torch.arange(
1433
+ past_key_values_length,
1434
+ seq_length + past_key_values_length,
1435
+ dtype=torch.long,
1436
+ device=device,
1437
+ )
1438
+ position_ids = position_ids.unsqueeze(0)
1439
+
1440
+ if inputs_embeds is None:
1441
+ inputs_embeds = self.embed_tokens(input_ids)
1442
+
1443
+ if self._use_flash_attention_2:
1444
+ # 2d mask is passed through the layers
1445
+ attention_mask = (
1446
+ attention_mask
1447
+ if (attention_mask is not None and 0 in attention_mask)
1448
+ else None
1449
+ )
1450
+ else:
1451
+ # 4d mask is passed through the layers
1452
+ attention_mask = _prepare_4d_causal_attention_mask(
1453
+ attention_mask,
1454
+ (batch_size, seq_length),
1455
+ inputs_embeds,
1456
+ past_key_values_length,
1457
+ )
1458
+
1459
+ # embed positions
1460
+ hidden_states = inputs_embeds
1461
+
1462
+ # decoder layers
1463
+ all_hidden_states = () if output_hidden_states else None
1464
+ all_self_attns = () if output_attentions else None
1465
+ next_decoder_cache = None
1466
+
1467
+ for decoder_layer in self.layers:
1468
+ if output_hidden_states:
1469
+ all_hidden_states += (hidden_states,)
1470
+
1471
+ layer_outputs = decoder_layer(
1472
+ hidden_states,
1473
+ attention_mask=attention_mask,
1474
+ position_ids=position_ids,
1475
+ past_key_value=past_key_values,
1476
+ output_attentions=output_attentions,
1477
+ use_cache=use_cache,
1478
+ )
1479
+
1480
+ hidden_states = layer_outputs[0]
1481
+
1482
+ if use_cache:
1483
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1484
+
1485
+ if output_attentions:
1486
+ all_self_attns += (layer_outputs[1],)
1487
+
1488
+ hidden_states = self.norm(hidden_states)
1489
+
1490
+ # add hidden states from the last decoder layer
1491
+ if output_hidden_states:
1492
+ all_hidden_states += (hidden_states,)
1493
+
1494
+ next_cache = None
1495
+ if use_cache:
1496
+ next_cache = (
1497
+ next_decoder_cache.to_legacy_cache()
1498
+ if use_legacy_cache
1499
+ else next_decoder_cache
1500
+ )
1501
+ if not return_dict:
1502
+ return tuple(
1503
+ v
1504
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1505
+ if v is not None
1506
+ )
1507
+ return BaseModelOutputWithPast(
1508
+ last_hidden_state=hidden_states,
1509
+ past_key_values=next_cache,
1510
+ hidden_states=all_hidden_states,
1511
+ attentions=all_self_attns,
1512
+ )
1513
+
1514
+
1515
+ class DeepseekV3ForCausalLM(DeepseekV3PreTrainedModel):
1516
+ _tied_weights_keys = ["lm_head.weight"]
1517
+
1518
+ def __init__(self, config):
1519
+ super().__init__(config)
1520
+ self.model = DeepseekV3Model(config)
1521
+ self.vocab_size = config.vocab_size
1522
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1523
+
1524
+ # Initialize weights and apply final processing
1525
+ self.post_init()
1526
+
1527
+ def get_input_embeddings(self):
1528
+ return self.model.embed_tokens
1529
+
1530
+ def set_input_embeddings(self, value):
1531
+ self.model.embed_tokens = value
1532
+
1533
+ def get_output_embeddings(self):
1534
+ return self.lm_head
1535
+
1536
+ def set_output_embeddings(self, new_embeddings):
1537
+ self.lm_head = new_embeddings
1538
+
1539
+ def set_decoder(self, decoder):
1540
+ self.model = decoder
1541
+
1542
+ def get_decoder(self):
1543
+ return self.model
1544
+
1545
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1546
+ @replace_return_docstrings(
1547
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1548
+ )
1549
+ def forward(
1550
+ self,
1551
+ input_ids: torch.LongTensor = None,
1552
+ attention_mask: Optional[torch.Tensor] = None,
1553
+ position_ids: Optional[torch.LongTensor] = None,
1554
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1555
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1556
+ labels: Optional[torch.LongTensor] = None,
1557
+ use_cache: Optional[bool] = None,
1558
+ output_attentions: Optional[bool] = None,
1559
+ output_hidden_states: Optional[bool] = None,
1560
+ return_dict: Optional[bool] = None,
1561
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1562
+ r"""
1563
+ Args:
1564
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1565
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1566
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1567
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1568
+
1569
+ Returns:
1570
+
1571
+ Example:
1572
+
1573
+ ```python
1574
+ >>> from transformers import AutoTokenizer, DeepseekV3ForCausalLM
1575
+
1576
+ >>> model = DeepseekV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1577
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1578
+
1579
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1580
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1581
+
1582
+ >>> # Generate
1583
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1584
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1585
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1586
+ ```"""
1587
+ output_attentions = (
1588
+ output_attentions
1589
+ if output_attentions is not None
1590
+ else self.config.output_attentions
1591
+ )
1592
+ output_hidden_states = (
1593
+ output_hidden_states
1594
+ if output_hidden_states is not None
1595
+ else self.config.output_hidden_states
1596
+ )
1597
+ return_dict = (
1598
+ return_dict if return_dict is not None else self.config.use_return_dict
1599
+ )
1600
+
1601
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1602
+ outputs = self.model(
1603
+ input_ids=input_ids,
1604
+ attention_mask=attention_mask,
1605
+ position_ids=position_ids,
1606
+ past_key_values=past_key_values,
1607
+ inputs_embeds=inputs_embeds,
1608
+ use_cache=use_cache,
1609
+ output_attentions=output_attentions,
1610
+ output_hidden_states=output_hidden_states,
1611
+ return_dict=return_dict,
1612
+ )
1613
+
1614
+ hidden_states = outputs[0]
1615
+ logits = self.lm_head(hidden_states)
1616
+ logits = logits.float()
1617
+
1618
+ loss = None
1619
+ if labels is not None:
1620
+ # Shift so that tokens < n predict n
1621
+ shift_logits = logits[..., :-1, :].contiguous()
1622
+ shift_labels = labels[..., 1:].contiguous()
1623
+ # Flatten the tokens
1624
+ loss_fct = CrossEntropyLoss()
1625
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1626
+ shift_labels = shift_labels.view(-1)
1627
+ # Enable model parallelism
1628
+ shift_labels = shift_labels.to(shift_logits.device)
1629
+ loss = loss_fct(shift_logits, shift_labels)
1630
+
1631
+ if not return_dict:
1632
+ output = (logits,) + outputs[1:]
1633
+ return (loss,) + output if loss is not None else output
1634
+
1635
+ return CausalLMOutputWithPast(
1636
+ loss=loss,
1637
+ logits=logits,
1638
+ past_key_values=outputs.past_key_values,
1639
+ hidden_states=outputs.hidden_states,
1640
+ attentions=outputs.attentions,
1641
+ )
1642
+
1643
+ def prepare_inputs_for_generation(
1644
+ self,
1645
+ input_ids,
1646
+ past_key_values=None,
1647
+ attention_mask=None,
1648
+ inputs_embeds=None,
1649
+ **kwargs,
1650
+ ):
1651
+ if past_key_values is not None:
1652
+ if isinstance(past_key_values, Cache):
1653
+ cache_length = past_key_values.get_seq_length()
1654
+ past_length = past_key_values.seen_tokens
1655
+ max_cache_length = past_key_values.get_max_length()
1656
+ else:
1657
+ cache_length = past_length = past_key_values[0][0].shape[2]
1658
+ max_cache_length = None
1659
+
1660
+ # Keep only the unprocessed tokens:
1661
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1662
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1663
+ # input)
1664
+ if (
1665
+ attention_mask is not None
1666
+ and attention_mask.shape[1] > input_ids.shape[1]
1667
+ ):
1668
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1669
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1670
+ # input_ids based on the past_length.
1671
+ elif past_length < input_ids.shape[1]:
1672
+ input_ids = input_ids[:, past_length:]
1673
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1674
+
1675
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1676
+ if (
1677
+ max_cache_length is not None
1678
+ and attention_mask is not None
1679
+ and cache_length + input_ids.shape[1] > max_cache_length
1680
+ ):
1681
+ attention_mask = attention_mask[:, -max_cache_length:]
1682
+
1683
+ position_ids = kwargs.get("position_ids", None)
1684
+ if attention_mask is not None and position_ids is None:
1685
+ # create position_ids on the fly for batch generation
1686
+ position_ids = attention_mask.long().cumsum(-1) - 1
1687
+ position_ids.masked_fill_(attention_mask == 0, 1)
1688
+ if past_key_values:
1689
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1690
+
1691
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1692
+ if inputs_embeds is not None and past_key_values is None:
1693
+ model_inputs = {"inputs_embeds": inputs_embeds}
1694
+ else:
1695
+ model_inputs = {"input_ids": input_ids}
1696
+
1697
+ model_inputs.update(
1698
+ {
1699
+ "position_ids": position_ids,
1700
+ "past_key_values": past_key_values,
1701
+ "use_cache": kwargs.get("use_cache"),
1702
+ "attention_mask": attention_mask,
1703
+ }
1704
+ )
1705
+ return model_inputs
1706
+
1707
+ @staticmethod
1708
+ def _reorder_cache(past_key_values, beam_idx):
1709
+ reordered_past = ()
1710
+ for layer_past in past_key_values:
1711
+ reordered_past += (
1712
+ tuple(
1713
+ past_state.index_select(0, beam_idx.to(past_state.device))
1714
+ for past_state in layer_past
1715
+ ),
1716
+ )
1717
+ return reordered_past
1718
+
1719
+
1720
+ @add_start_docstrings(
1721
+ """
1722
+ The DeepseekV3 Model transformer with a sequence classification head on top (linear layer).
1723
+
1724
+ [`DeepseekV3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1725
+ (e.g. GPT-2) do.
1726
+
1727
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1728
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1729
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1730
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1731
+ each row of the batch).
1732
+ """,
1733
+ DeepseekV3_START_DOCSTRING,
1734
+ )
1735
+ class DeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel):
1736
+ def __init__(self, config):
1737
+ super().__init__(config)
1738
+ self.num_labels = config.num_labels
1739
+ self.model = DeepseekV3Model(config)
1740
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1741
+
1742
+ # Initialize weights and apply final processing
1743
+ self.post_init()
1744
+
1745
+ def get_input_embeddings(self):
1746
+ return self.model.embed_tokens
1747
+
1748
+ def set_input_embeddings(self, value):
1749
+ self.model.embed_tokens = value
1750
+
1751
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1752
+ def forward(
1753
+ self,
1754
+ input_ids: torch.LongTensor = None,
1755
+ attention_mask: Optional[torch.Tensor] = None,
1756
+ position_ids: Optional[torch.LongTensor] = None,
1757
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1758
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1759
+ labels: Optional[torch.LongTensor] = None,
1760
+ use_cache: Optional[bool] = None,
1761
+ output_attentions: Optional[bool] = None,
1762
+ output_hidden_states: Optional[bool] = None,
1763
+ return_dict: Optional[bool] = None,
1764
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1765
+ r"""
1766
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1767
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1768
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1769
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1770
+ """
1771
+ return_dict = (
1772
+ return_dict if return_dict is not None else self.config.use_return_dict
1773
+ )
1774
+
1775
+ transformer_outputs = self.model(
1776
+ input_ids,
1777
+ attention_mask=attention_mask,
1778
+ position_ids=position_ids,
1779
+ past_key_values=past_key_values,
1780
+ inputs_embeds=inputs_embeds,
1781
+ use_cache=use_cache,
1782
+ output_attentions=output_attentions,
1783
+ output_hidden_states=output_hidden_states,
1784
+ return_dict=return_dict,
1785
+ )
1786
+ hidden_states = transformer_outputs[0]
1787
+ logits = self.score(hidden_states)
1788
+
1789
+ if input_ids is not None:
1790
+ batch_size = input_ids.shape[0]
1791
+ else:
1792
+ batch_size = inputs_embeds.shape[0]
1793
+
1794
+ if self.config.pad_token_id is None and batch_size != 1:
1795
+ raise ValueError(
1796
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1797
+ )
1798
+ if self.config.pad_token_id is None:
1799
+ sequence_lengths = -1
1800
+ else:
1801
+ if input_ids is not None:
1802
+ sequence_lengths = (
1803
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1804
+ ).to(logits.device)
1805
+ else:
1806
+ sequence_lengths = -1
1807
+
1808
+ pooled_logits = logits[
1809
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1810
+ ]
1811
+
1812
+ loss = None
1813
+ if labels is not None:
1814
+ labels = labels.to(logits.device)
1815
+ if self.config.problem_type is None:
1816
+ if self.num_labels == 1:
1817
+ self.config.problem_type = "regression"
1818
+ elif self.num_labels > 1 and (
1819
+ labels.dtype == torch.long or labels.dtype == torch.int
1820
+ ):
1821
+ self.config.problem_type = "single_label_classification"
1822
+ else:
1823
+ self.config.problem_type = "multi_label_classification"
1824
+
1825
+ if self.config.problem_type == "regression":
1826
+ loss_fct = MSELoss()
1827
+ if self.num_labels == 1:
1828
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1829
+ else:
1830
+ loss = loss_fct(pooled_logits, labels)
1831
+ elif self.config.problem_type == "single_label_classification":
1832
+ loss_fct = CrossEntropyLoss()
1833
+ loss = loss_fct(
1834
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1835
+ )
1836
+ elif self.config.problem_type == "multi_label_classification":
1837
+ loss_fct = BCEWithLogitsLoss()
1838
+ loss = loss_fct(pooled_logits, labels)
1839
+ if not return_dict:
1840
+ output = (pooled_logits,) + transformer_outputs[1:]
1841
+ return ((loss,) + output) if loss is not None else output
1842
+
1843
+ return SequenceClassifierOutputWithPast(
1844
+ loss=loss,
1845
+ logits=pooled_logits,
1846
+ past_key_values=transformer_outputs.past_key_values,
1847
+ hidden_states=transformer_outputs.hidden_states,
1848
+ attentions=transformer_outputs.attentions,
1849
+ )
tiktoken.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b6c497a7469b33ced9c38afb1ad6e47f03f5e5dc05f15930799210ec050c5103
3
+ size 2795286
tokenization_kimi.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tiktoken
3
+
4
+ from logging import getLogger
5
+ from pathlib import Path
6
+ from typing import (
7
+ cast,
8
+ Tuple,
9
+ Dict,
10
+ Iterator,
11
+ List,
12
+ Union,
13
+ Optional,
14
+ )
15
+ from shutil import copyfile
16
+ from tiktoken.load import load_tiktoken_bpe
17
+ from tokenizers import AddedToken, pre_tokenizers, Regex
18
+ from transformers.tokenization_utils import PreTrainedTokenizer
19
+ from transformers.models.gpt2.tokenization_gpt2 import bytes_to_unicode
20
+
21
+
22
+
23
+ logger = getLogger(__name__)
24
+ VOCAB_FILES_NAMES = {"vocab_file": "tiktoken.model"}
25
+
26
+ class TikTokenTokenizer(PreTrainedTokenizer):
27
+ """
28
+ Tokenizing and encoding/decoding text using the Tiktoken tokenizer. See megatron/tokenizer/tiktoken_tokenizer.py.
29
+
30
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
31
+ this superclass for more information regarding those methods.
32
+
33
+ Args:
34
+ vocab_file (`str`):
35
+ The path to the Tiktoken model file.
36
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|begin_of_text|>",`):
37
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
38
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|end_of_text|>"`):
39
+ The end of sequence token.
40
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|reserved_special_token_249|>"`):
41
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
42
+ token instead. The second to last item in special_tokens.
43
+ pad_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|reserved_special_token_250|>"`):
44
+ The token used for padding, for example when batching sequences of different lengths.
45
+ additional_special_tokens (list of `str`, *optional*):
46
+ A tuple or a list of additional tokens, which will be marked as `special`, meaning that they will be
47
+ skipped when decoding if `skip_special_tokens` is set to `True`.
48
+ """
49
+
50
+ vocab_files_names = VOCAB_FILES_NAMES
51
+
52
+ model_input_names = ["input_ids", "attention_mask"]
53
+
54
+ special_tokens: Dict[str, int]
55
+
56
+ num_reserved_special_tokens = 256
57
+
58
+ pat_str = "|".join(
59
+ [
60
+ r"""[\p{Han}]+""",
61
+ r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?""",
62
+ r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?""",
63
+ r"""\p{N}{1,3}""",
64
+ r""" ?[^\s\p{L}\p{N}]+[\r\n]*""",
65
+ r"""\s*[\r\n]+""",
66
+ r"""\s+(?!\S)""",
67
+ r"""\s+""",
68
+ ]
69
+ )
70
+
71
+ def __init__(
72
+ self,
73
+ vocab_file,
74
+ bos_token: Union[str, AddedToken]="[BOS]",
75
+ eos_token: Union[str, AddedToken]="[EOS]",
76
+ unk_token: Union[str, AddedToken, None]=None,
77
+ pad_token: Union[str, AddedToken, None]=None,
78
+ additional_special_tokens: List[str]=None,
79
+ added_tokens_decoder: Optional[dict] = None,
80
+ **kwargs,
81
+ ):
82
+ assert os.path.isfile(vocab_file), vocab_file
83
+
84
+ if additional_special_tokens is None:
85
+ additional_special_tokens = [
86
+ "<|im_end|>",
87
+ "<|im_user|>",
88
+ "<|im_assistant|>",
89
+ "<|start_header_id|>",
90
+ "<|end_header_id|>",
91
+ "[EOT]",
92
+ "<|im_system|>",
93
+ "<|im_middle|>",
94
+ ]
95
+
96
+ special_tokens_mapping = {
97
+ i: added_tokens_decoder[i].content for i in added_tokens_decoder
98
+ }
99
+
100
+ self.vocab_file = vocab_file
101
+ mergeable_ranks = load_tiktoken_bpe(vocab_file)
102
+ num_base_tokens = len(mergeable_ranks)
103
+ self.special_tokens = {
104
+ special_tokens_mapping.get(i, f"<|reserved_token_{i}|>"): i
105
+ for i in range(
106
+ num_base_tokens, num_base_tokens + self.num_reserved_special_tokens + 2
107
+ )
108
+ }
109
+
110
+
111
+
112
+ self.model = tiktoken.Encoding(
113
+ name=Path(vocab_file).name,
114
+ pat_str=self.pat_str,
115
+ mergeable_ranks=mergeable_ranks,
116
+ special_tokens=self.special_tokens,
117
+ )
118
+ logger.info(f"Reloaded tiktoken model from {vocab_file}")
119
+
120
+ self.n_words: int = self.model.n_vocab
121
+ # BOS / EOS token IDs
122
+ self.bos_id: int = self.special_tokens[str(bos_token)]
123
+ self.eos_id: int = self.special_tokens[str(eos_token)]
124
+ logger.info(
125
+ f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}"
126
+ )
127
+
128
+ self.pad_id: int = self.special_tokens[str(pad_token)]
129
+ self.unk_id: int = self.special_tokens[str(unk_token)]
130
+
131
+ self.byte_encoder = bytes_to_unicode()
132
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
133
+
134
+ self.decoder = {}
135
+ for i in range(self.n_words):
136
+ # Taken from https://gist.github.com/xenova/a452a6474428de0182b17605a98631ee
137
+ decoding = ''.join([
138
+ self.byte_encoder[ord(char)] for char in
139
+ self.model.decode_single_token_bytes(i).decode('latin-1')
140
+ ])
141
+ self.decoder[i] = decoding
142
+
143
+ self.encoder = {}
144
+ for i in range(self.n_words):
145
+ if i in self.decoder:
146
+ self.encoder[self.decoder[i]] = i
147
+
148
+ super().__init__(
149
+ bos_token=bos_token,
150
+ eos_token=eos_token,
151
+ unk_token=unk_token,
152
+ pad_token=pad_token,
153
+ additional_special_tokens=additional_special_tokens,
154
+ **kwargs,
155
+ )
156
+ self.all_special_ids_set = set(self.all_special_ids)
157
+
158
+ def encode(
159
+ self,
160
+ text: str,
161
+ allow_special_tokens: bool = True,
162
+ **kwargs
163
+ ) -> List[int]:
164
+ """
165
+ Encodes a string into a list of token IDs.
166
+
167
+ Args:
168
+ text (str): The input string to be encoded.
169
+
170
+ Returns:
171
+ list[int]: A list of token IDs.
172
+ """
173
+ # If there are other args, we should call super().encode because there are a lot of code
174
+ # to handle those args. supper().encode finally will call _tokenize and _convert_token_to_id.
175
+ # NOTE: our encode method is not compatible with the super().encode method,
176
+ # e.g. split_special_tokens' default is True in our encode method.
177
+ if len(kwargs) > 0:
178
+ logger.warning( f"Calling super().encode with {kwargs}" )
179
+ return super().encode(text, **kwargs)
180
+
181
+ assert type(text) is str
182
+
183
+ # The tiktoken tokenizer can handle <=400k chars without
184
+ # pyo3_runtime.PanicException.
185
+ TIKTOKEN_MAX_ENCODE_CHARS = 400_000
186
+
187
+ # https://github.com/openai/tiktoken/issues/195
188
+ # Here we iterate over subsequences and split if we exceed the limit
189
+ # of max consecutive non-whitespace or whitespace characters.
190
+ MAX_NO_WHITESPACES_CHARS = 25_000
191
+
192
+ texts = self.pre_tokenizer_process(text)
193
+
194
+ all_substrs = []
195
+ for text in texts:
196
+ substrs = (
197
+ substr
198
+ for i in range(0, len(text), TIKTOKEN_MAX_ENCODE_CHARS)
199
+ for substr in self._split_whitespaces_or_nonwhitespaces(
200
+ text[i: i + TIKTOKEN_MAX_ENCODE_CHARS], MAX_NO_WHITESPACES_CHARS
201
+ )
202
+ )
203
+ all_substrs.extend(substrs)
204
+
205
+ t: List[int] = []
206
+ for substr in all_substrs:
207
+ if allow_special_tokens:
208
+ t.extend(
209
+ # we should consider special token as a common token
210
+ self.model.encode(
211
+ substr,
212
+ allowed_special="all",
213
+ )
214
+ )
215
+ else:
216
+ t.extend(
217
+ # we should consider special token as a common token
218
+ self.model.encode(
219
+ substr,
220
+ disallowed_special=(),
221
+ )
222
+ )
223
+
224
+ return t
225
+
226
+ def decode(
227
+ self,
228
+ token_ids: Union[int, List[int]],
229
+ **kwargs
230
+ ) -> str:
231
+ """
232
+ Decodes a list of token IDs into a string.
233
+
234
+ Args:
235
+ token_ids (List[int]): The list of token IDs to be decoded.
236
+
237
+ Returns:
238
+ str: The decoded string.
239
+ """
240
+ # If there are other args, we should call super().decode because there are a lot of code
241
+ # to handle those args. supper().encode finally will call convert_tokens_to_string and _convert_id_to_token.
242
+ if len(kwargs) > 0:
243
+ return super().decode(token_ids, **kwargs)
244
+
245
+ if type(token_ids) is int:
246
+ token_ids = [token_ids]
247
+
248
+ return self.model.decode(cast(List[int], token_ids))
249
+
250
+ @staticmethod
251
+ def _split_whitespaces_or_nonwhitespaces(
252
+ s: str, max_consecutive_slice_len: int
253
+ ) -> Iterator[str]:
254
+ """
255
+ Splits the string `s` so that each substring contains no more than `max_consecutive_slice_len`
256
+ consecutive whitespaces or consecutive non-whitespaces.
257
+ """
258
+ current_slice_len = 0
259
+ current_slice_is_space = s[0].isspace() if len(s) > 0 else False
260
+ slice_start = 0
261
+
262
+ for i in range(len(s)):
263
+ is_now_space = s[i].isspace()
264
+
265
+ if current_slice_is_space ^ is_now_space:
266
+ current_slice_len = 1
267
+ current_slice_is_space = is_now_space
268
+ else:
269
+ current_slice_len += 1
270
+ if current_slice_len > max_consecutive_slice_len:
271
+ yield s[slice_start:i]
272
+ slice_start = i
273
+ current_slice_len = 1
274
+ yield s[slice_start:]
275
+
276
+ def pre_tokenizer_process(self, text: str) -> List[str]:
277
+ """
278
+ pre-tokenizes the input text into a list of tokens.
279
+ This method is used to split the input text into smaller chunks for internal processing.
280
+ """
281
+ return [text]
282
+
283
+
284
+ """ ----- Below are the abstract methods required by PreTrainedTokenizer ----- """
285
+ @property
286
+ def vocab_size(self) -> int:
287
+ return self.n_words
288
+
289
+ def get_vocab(self) -> Dict[str, int]:
290
+ return self.encoder
291
+
292
+ def _tokenize(self, text: str, **kwargs) -> List[str]:
293
+ return [
294
+ self.decoder[t]
295
+ for t in self.encode(text)
296
+ ]
297
+
298
+ def _convert_token_to_id(self, token: str) -> int:
299
+ return self.encoder.get(token, self.unk_id)
300
+
301
+ def _convert_id_to_token(self, index: int) -> str:
302
+ return self.decoder.get(index)
303
+
304
+ @staticmethod
305
+ def clean_up_tokenization(out_string: str) -> str:
306
+ return out_string
307
+
308
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
309
+ text = ''.join(tokens)
310
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', 'replace')
311
+ return text
312
+
313
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
314
+ if not os.path.isdir(save_directory):
315
+ raise ValueError(f"vocabulary path ({save_directory}) should be a directory")
316
+ out_vocab_file = os.path.join(
317
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
318
+ )
319
+
320
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
321
+ copyfile(self.vocab_file, out_vocab_file)
322
+
323
+ return (out_vocab_file,)
tokenizer_config.json ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "163584": {
4
+ "content": "[BOS]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "163585": {
12
+ "content": "[EOS]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "163586": {
20
+ "content": "<|im_end|>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "163587": {
28
+ "content": "<|im_user|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "163588": {
36
+ "content": "<|im_assistant|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "163590": {
44
+ "content": "<|start_header_id|>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "163591": {
52
+ "content": "<|end_header_id|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "163593": {
60
+ "content": "[EOT]",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "163594": {
68
+ "content": "<|im_system|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "163595": {
76
+ "content": "<|tool_calls_section_begin|>",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": false
82
+ },
83
+ "163596": {
84
+ "content": "<|tool_calls_section_end|>",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": false
90
+ },
91
+ "163597": {
92
+ "content": "<|tool_call_begin|>",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": false
98
+ },
99
+ "163598": {
100
+ "content": "<|tool_call_argument_begin|>",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": false
106
+ },
107
+ "163599": {
108
+ "content": "<|tool_call_end|>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": false
114
+ },
115
+ "163601": {
116
+ "content": "<|im_middle|>",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "163838": {
124
+ "content": "[UNK]",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "163839": {
132
+ "content": "[PAD]",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ }
139
+ },
140
+ "additional_special_tokens": [
141
+ "<|im_end|>",
142
+ "<|im_user|>",
143
+ "<|im_assistant|>",
144
+ "<|start_header_id|>",
145
+ "<|end_header_id|>",
146
+ "[EOT]",
147
+ "<|im_system|>",
148
+ "<|im_middle|>"
149
+ ],
150
+ "bos_token": "[BOS]",
151
+ "clean_up_tokenization_spaces": false,
152
+ "eos_token": "[EOS]",
153
+ "extra_special_tokens": {},
154
+ "chat_template": "{%- if tools -%}\n <|im_system|>tool_declare<|im_middle|>{{ tools | tojson }}<|im_end|>\n{%- endif -%}\n{%- for message in messages -%}\n {%- if loop.first and messages[0]['role'] != 'system' -%}\n <|im_system|>system<|im_middle|>You are a helpful assistant<|im_end|>\n {%- endif -%}\n {%- if message['role'] == 'system' -%}\n <|im_system|>system<|im_middle|>\n {%- elif message['role'] == 'user' -%}\n <|im_user|>user<|im_middle|>\n {%- elif message['role'] == 'assistant' -%}\n <|im_assistant|>assistant<|im_middle|>\n {%- elif message['role'] == 'tool' -%}\n <|im_system|>tool<|im_middle|>\n {%- endif -%}\n {%- if message['role'] == 'assistant' and message.get('tool_calls') -%}\n {%- if message['content'] -%}{{ message['content'] }}{%- endif -%}\n <|tool_calls_section_begin|>\n {%- for tool_call in message['tool_calls'] -%}\n {%- set func_name = tool_call['function']['name'] -%}\n {%- set formatted_id = 'functions.' + func_name + ':' + loop.index0|string -%}\n <|tool_call_begin|>{{ formatted_id }}<|tool_call_argument_begin|>{{ tool_call['function']['arguments'] | tojson}}<|tool_call_end|>\n {%- endfor -%}\n <|tool_calls_section_end|>\n {%- elif message['role'] == 'tool' -%}\n ## Return of {{ message.tool_call_id }}\\n{{ message['content'] }}\n {%- elif message['content'] is string -%}\n {{ message['content'] }}\n {%- elif message['content'] is not none -%}\n {% for content in message['content'] -%}\n {% if content['type'] == 'image' or 'image' in content or 'image_url' in content -%}\n <|media_start|>image<|media_content|><|media_pad|><|media_end|>\n {% else -%}\n {{ content['text'] }}\n {%- endif -%}\n {%- endfor -%}\n {%- endif -%}\n <|im_end|>\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n <|im_assistant|>assistant<|im_middle|>\n{%- endif -%}",
155
+ "model_max_length": 1000000000000000019884624838656,
156
+ "pad_token": "[PAD]",
157
+ "tokenizer_class": "TikTokenTokenizer",
158
+ "unk_token": "[UNK]",
159
+ "auto_map": {
160
+ "AutoTokenizer": [
161
+ "tokenization_kimi.TikTokenTokenizer",
162
+ null
163
+ ]
164
+ }
165
+ }