pkumc commited on
Commit
e6aaeeb
·
verified ·
1 Parent(s): 2f4fa19

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LICENSE +21 -0
  2. README.md +239 -0
  3. config.json +61 -0
  4. configuration_deepseek.py +210 -0
  5. generation_config.json +9 -0
  6. inference/bf16_cast_channel_int8.py +95 -0
  7. inference/kernel.py +136 -0
  8. model-00001-of-000163.safetensors +3 -0
  9. model-00002-of-000163.safetensors +3 -0
  10. model-00003-of-000163.safetensors +3 -0
  11. model-00004-of-000163.safetensors +3 -0
  12. model-00005-of-000163.safetensors +3 -0
  13. model-00006-of-000163.safetensors +3 -0
  14. model-00007-of-000163.safetensors +3 -0
  15. model-00009-of-000163.safetensors +3 -0
  16. model-00010-of-000163.safetensors +3 -0
  17. model-00011-of-000163.safetensors +3 -0
  18. model-00012-of-000163.safetensors +3 -0
  19. model-00013-of-000163.safetensors +3 -0
  20. model-00014-of-000163.safetensors +3 -0
  21. model-00015-of-000163.safetensors +3 -0
  22. model-00016-of-000163.safetensors +3 -0
  23. model-00017-of-000163.safetensors +3 -0
  24. model-00019-of-000163.safetensors +3 -0
  25. model-00020-of-000163.safetensors +3 -0
  26. model-00021-of-000163.safetensors +3 -0
  27. model-00022-of-000163.safetensors +3 -0
  28. model-00023-of-000163.safetensors +3 -0
  29. model-00026-of-000163.safetensors +3 -0
  30. model-00029-of-000163.safetensors +3 -0
  31. model-00030-of-000163.safetensors +3 -0
  32. model-00031-of-000163.safetensors +3 -0
  33. model-00032-of-000163.safetensors +3 -0
  34. model-00033-of-000163.safetensors +3 -0
  35. model-00034-of-000163.safetensors +3 -0
  36. model-00035-of-000163.safetensors +3 -0
  37. model-00037-of-000163.safetensors +3 -0
  38. model-00038-of-000163.safetensors +3 -0
  39. model-00039-of-000163.safetensors +3 -0
  40. model-00040-of-000163.safetensors +3 -0
  41. model-00041-of-000163.safetensors +3 -0
  42. model-00042-of-000163.safetensors +3 -0
  43. model-00043-of-000163.safetensors +3 -0
  44. model-00045-of-000163.safetensors +3 -0
  45. model-00046-of-000163.safetensors +3 -0
  46. model-00047-of-000163.safetensors +3 -0
  47. model-00048-of-000163.safetensors +3 -0
  48. model-00049-of-000163.safetensors +3 -0
  49. model-00050-of-000163.safetensors +3 -0
  50. model-00051-of-000163.safetensors +3 -0
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 DeepSeek
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.
README.md ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ library_name: transformers
4
+ ---
5
+ # DeepSeek-R1
6
+ <!-- markdownlint-disable first-line-h1 -->
7
+ <!-- markdownlint-disable html -->
8
+ <!-- markdownlint-disable no-duplicate-header -->
9
+
10
+ <div align="center">
11
+ <img src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/logo.svg?raw=true" width="60%" alt="DeepSeek-V3" />
12
+ </div>
13
+ <hr>
14
+ <div align="center" style="line-height: 1;">
15
+ <a href="https://www.deepseek.com/" target="_blank" style="margin: 2px;">
16
+ <img alt="Homepage" src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/badge.svg?raw=true" style="display: inline-block; vertical-align: middle;"/>
17
+ </a>
18
+ <a href="https://chat.deepseek.com/" target="_blank" style="margin: 2px;">
19
+ <img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-DeepSeek%20R1-536af5?color=536af5&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
20
+ </a>
21
+ <a href="https://huggingface.co/deepseek-ai" target="_blank" style="margin: 2px;">
22
+ <img alt="Hugging Face" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-DeepSeek%20AI-ffc107?color=ffc107&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
23
+ </a>
24
+ </div>
25
+
26
+ <div align="center" style="line-height: 1;">
27
+ <a href="https://discord.gg/Tc7c45Zzu5" target="_blank" style="margin: 2px;">
28
+ <img alt="Discord" src="https://img.shields.io/badge/Discord-DeepSeek%20AI-7289da?logo=discord&logoColor=white&color=7289da" style="display: inline-block; vertical-align: middle;"/>
29
+ </a>
30
+ <a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/qr.jpeg?raw=true" target="_blank" style="margin: 2px;">
31
+ <img alt="Wechat" src="https://img.shields.io/badge/WeChat-DeepSeek%20AI-brightgreen?logo=wechat&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
32
+ </a>
33
+ <a href="https://twitter.com/deepseek_ai" target="_blank" style="margin: 2px;">
34
+ <img alt="Twitter Follow" src="https://img.shields.io/badge/Twitter-deepseek_ai-white?logo=x&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
35
+ </a>
36
+ </div>
37
+
38
+ <div align="center" style="line-height: 1;">
39
+ <a href="https://github.com/deepseek-ai/DeepSeek-R1/blob/main/LICENSE" style="margin: 2px;">
40
+ <img alt="License" src="https://img.shields.io/badge/License-MIT-f5de53?&color=f5de53" style="display: inline-block; vertical-align: middle;"/>
41
+ </a>
42
+ </div>
43
+
44
+
45
+ <p align="center">
46
+ <a href="https://github.com/deepseek-ai/DeepSeek-R1/blob/main/DeepSeek_R1.pdf"><b>Paper Link</b>👁️</a>
47
+ </p>
48
+
49
+
50
+ ## 1. Introduction
51
+
52
+ We introduce our first-generation reasoning models, DeepSeek-R1-Zero and DeepSeek-R1.
53
+ DeepSeek-R1-Zero, a model trained via large-scale reinforcement learning (RL) without supervised fine-tuning (SFT) as a preliminary step, demonstrated remarkable performance on reasoning.
54
+ With RL, DeepSeek-R1-Zero naturally emerged with numerous powerful and interesting reasoning behaviors.
55
+ However, DeepSeek-R1-Zero encounters challenges such as endless repetition, poor readability, and language mixing. To address these issues and further enhance reasoning performance,
56
+ we introduce DeepSeek-R1, which incorporates cold-start data before RL.
57
+ DeepSeek-R1 achieves performance comparable to OpenAI-o1 across math, code, and reasoning tasks.
58
+ To support the research community, we have open-sourced DeepSeek-R1-Zero, DeepSeek-R1, and six dense models distilled from DeepSeek-R1 based on Llama and Qwen. DeepSeek-R1-Distill-Qwen-32B outperforms OpenAI-o1-mini across various benchmarks, achieving new state-of-the-art results for dense models.
59
+
60
+ **NOTE: Before running DeepSeek-R1 series models locally, we kindly recommend reviewing the [Usage Recommendation](#usage-recommendations) section.**
61
+
62
+ <p align="center">
63
+ <img width="80%" src="figures/benchmark.jpg">
64
+ </p>
65
+
66
+ ## 2. Model Summary
67
+
68
+ ---
69
+
70
+ **Post-Training: Large-Scale Reinforcement Learning on the Base Model**
71
+
72
+ - We directly apply reinforcement learning (RL) to the base model without relying on supervised fine-tuning (SFT) as a preliminary step. This approach allows the model to explore chain-of-thought (CoT) for solving complex problems, resulting in the development of DeepSeek-R1-Zero. DeepSeek-R1-Zero demonstrates capabilities such as self-verification, reflection, and generating long CoTs, marking a significant milestone for the research community. Notably, it is the first open research to validate that reasoning capabilities of LLMs can be incentivized purely through RL, without the need for SFT. This breakthrough paves the way for future advancements in this area.
73
+
74
+ - We introduce our pipeline to develop DeepSeek-R1. The pipeline incorporates two RL stages aimed at discovering improved reasoning patterns and aligning with human preferences, as well as two SFT stages that serve as the seed for the model's reasoning and non-reasoning capabilities.
75
+ We believe the pipeline will benefit the industry by creating better models.
76
+
77
+ ---
78
+
79
+ **Distillation: Smaller Models Can Be Powerful Too**
80
+
81
+ - We demonstrate that the reasoning patterns of larger models can be distilled into smaller models, resulting in better performance compared to the reasoning patterns discovered through RL on small models. The open source DeepSeek-R1, as well as its API, will benefit the research community to distill better smaller models in the future.
82
+ - Using the reasoning data generated by DeepSeek-R1, we fine-tuned several dense models that are widely used in the research community. The evaluation results demonstrate that the distilled smaller dense models perform exceptionally well on benchmarks. We open-source distilled 1.5B, 7B, 8B, 14B, 32B, and 70B checkpoints based on Qwen2.5 and Llama3 series to the community.
83
+
84
+ ## 3. Model Downloads
85
+
86
+ ### DeepSeek-R1 Models
87
+
88
+ <div align="center">
89
+
90
+ | **Model** | **#Total Params** | **#Activated Params** | **Context Length** | **Download** |
91
+ | :------------: | :------------: | :------------: | :------------: | :------------: |
92
+ | DeepSeek-R1-Zero | 671B | 37B | 128K | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Zero) |
93
+ | DeepSeek-R1 | 671B | 37B | 128K | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1) |
94
+
95
+ </div>
96
+
97
+ DeepSeek-R1-Zero & DeepSeek-R1 are trained based on DeepSeek-V3-Base.
98
+ For more details regarding the model architecture, please refer to [DeepSeek-V3](https://github.com/deepseek-ai/DeepSeek-V3) repository.
99
+
100
+ ### DeepSeek-R1-Distill Models
101
+
102
+ <div align="center">
103
+
104
+ | **Model** | **Base Model** | **Download** |
105
+ | :------------: | :------------: | :------------: |
106
+ | DeepSeek-R1-Distill-Qwen-1.5B | [Qwen2.5-Math-1.5B](https://huggingface.co/Qwen/Qwen2.5-Math-1.5B) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B) |
107
+ | DeepSeek-R1-Distill-Qwen-7B | [Qwen2.5-Math-7B](https://huggingface.co/Qwen/Qwen2.5-Math-7B) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-7B) |
108
+ | DeepSeek-R1-Distill-Llama-8B | [Llama-3.1-8B](https://huggingface.co/meta-llama/Llama-3.1-8B) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-8B) |
109
+ | DeepSeek-R1-Distill-Qwen-14B | [Qwen2.5-14B](https://huggingface.co/Qwen/Qwen2.5-14B) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-14B) |
110
+ |DeepSeek-R1-Distill-Qwen-32B | [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B) |
111
+ | DeepSeek-R1-Distill-Llama-70B | [Llama-3.3-70B-Instruct](https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-70B) |
112
+
113
+ </div>
114
+
115
+ DeepSeek-R1-Distill models are fine-tuned based on open-source models, using samples generated by DeepSeek-R1.
116
+ We slightly change their configs and tokenizers. Please use our setting to run these models.
117
+
118
+ ## 4. Evaluation Results
119
+
120
+ ### DeepSeek-R1-Evaluation
121
+ For all our models, the maximum generation length is set to 32,768 tokens. For benchmarks requiring sampling, we use a temperature of $0.6$, a top-p value of $0.95$, and generate 64 responses per query to estimate pass@1.
122
+ <div align="center">
123
+
124
+
125
+ | Category | Benchmark (Metric) | Claude-3.5-Sonnet-1022 | GPT-4o 0513 | DeepSeek V3 | OpenAI o1-mini | OpenAI o1-1217 | DeepSeek R1 |
126
+ |----------|-------------------|----------------------|------------|--------------|----------------|------------|--------------|
127
+ | | Architecture | - | - | MoE | - | - | MoE |
128
+ | | # Activated Params | - | - | 37B | - | - | 37B |
129
+ | | # Total Params | - | - | 671B | - | - | 671B |
130
+ | English | MMLU (Pass@1) | 88.3 | 87.2 | 88.5 | 85.2 | **91.8** | 90.8 |
131
+ | | MMLU-Redux (EM) | 88.9 | 88.0 | 89.1 | 86.7 | - | **92.9** |
132
+ | | MMLU-Pro (EM) | 78.0 | 72.6 | 75.9 | 80.3 | - | **84.0** |
133
+ | | DROP (3-shot F1) | 88.3 | 83.7 | 91.6 | 83.9 | 90.2 | **92.2** |
134
+ | | IF-Eval (Prompt Strict) | **86.5** | 84.3 | 86.1 | 84.8 | - | 83.3 |
135
+ | | GPQA-Diamond (Pass@1) | 65.0 | 49.9 | 59.1 | 60.0 | **75.7** | 71.5 |
136
+ | | SimpleQA (Correct) | 28.4 | 38.2 | 24.9 | 7.0 | **47.0** | 30.1 |
137
+ | | FRAMES (Acc.) | 72.5 | 80.5 | 73.3 | 76.9 | - | **82.5** |
138
+ | | AlpacaEval2.0 (LC-winrate) | 52.0 | 51.1 | 70.0 | 57.8 | - | **87.6** |
139
+ | | ArenaHard (GPT-4-1106) | 85.2 | 80.4 | 85.5 | 92.0 | - | **92.3** |
140
+ | Code | LiveCodeBench (Pass@1-COT) | 33.8 | 34.2 | - | 53.8 | 63.4 | **65.9** |
141
+ | | Codeforces (Percentile) | 20.3 | 23.6 | 58.7 | 93.4 | **96.6** | 96.3 |
142
+ | | Codeforces (Rating) | 717 | 759 | 1134 | 1820 | **2061** | 2029 |
143
+ | | SWE Verified (Resolved) | **50.8** | 38.8 | 42.0 | 41.6 | 48.9 | 49.2 |
144
+ | | Aider-Polyglot (Acc.) | 45.3 | 16.0 | 49.6 | 32.9 | **61.7** | 53.3 |
145
+ | Math | AIME 2024 (Pass@1) | 16.0 | 9.3 | 39.2 | 63.6 | 79.2 | **79.8** |
146
+ | | MATH-500 (Pass@1) | 78.3 | 74.6 | 90.2 | 90.0 | 96.4 | **97.3** |
147
+ | | CNMO 2024 (Pass@1) | 13.1 | 10.8 | 43.2 | 67.6 | - | **78.8** |
148
+ | Chinese | CLUEWSC (EM) | 85.4 | 87.9 | 90.9 | 89.9 | - | **92.8** |
149
+ | | C-Eval (EM) | 76.7 | 76.0 | 86.5 | 68.9 | - | **91.8** |
150
+ | | C-SimpleQA (Correct) | 55.4 | 58.7 | **68.0** | 40.3 | - | 63.7 |
151
+
152
+ </div>
153
+
154
+
155
+ ### Distilled Model Evaluation
156
+
157
+
158
+ <div align="center">
159
+
160
+ | Model | AIME 2024 pass@1 | AIME 2024 cons@64 | MATH-500 pass@1 | GPQA Diamond pass@1 | LiveCodeBench pass@1 | CodeForces rating |
161
+ |------------------------------------------|------------------|-------------------|-----------------|----------------------|----------------------|-------------------|
162
+ | GPT-4o-0513 | 9.3 | 13.4 | 74.6 | 49.9 | 32.9 | 759 |
163
+ | Claude-3.5-Sonnet-1022 | 16.0 | 26.7 | 78.3 | 65.0 | 38.9 | 717 |
164
+ | o1-mini | 63.6 | 80.0 | 90.0 | 60.0 | 53.8 | **1820** |
165
+ | QwQ-32B-Preview | 44.0 | 60.0 | 90.6 | 54.5 | 41.9 | 1316 |
166
+ | DeepSeek-R1-Distill-Qwen-1.5B | 28.9 | 52.7 | 83.9 | 33.8 | 16.9 | 954 |
167
+ | DeepSeek-R1-Distill-Qwen-7B | 55.5 | 83.3 | 92.8 | 49.1 | 37.6 | 1189 |
168
+ | DeepSeek-R1-Distill-Qwen-14B | 69.7 | 80.0 | 93.9 | 59.1 | 53.1 | 1481 |
169
+ | DeepSeek-R1-Distill-Qwen-32B | **72.6** | 83.3 | 94.3 | 62.1 | 57.2 | 1691 |
170
+ | DeepSeek-R1-Distill-Llama-8B | 50.4 | 80.0 | 89.1 | 49.0 | 39.6 | 1205 |
171
+ | DeepSeek-R1-Distill-Llama-70B | 70.0 | **86.7** | **94.5** | **65.2** | **57.5** | 1633 |
172
+
173
+ </div>
174
+
175
+
176
+ ## 5. Chat Website & API Platform
177
+ You can chat with DeepSeek-R1 on DeepSeek's official website: [chat.deepseek.com](https://chat.deepseek.com), and switch on the button "DeepThink"
178
+
179
+ We also provide OpenAI-Compatible API at DeepSeek Platform: [platform.deepseek.com](https://platform.deepseek.com/)
180
+
181
+ ## 6. How to Run Locally
182
+
183
+ ### DeepSeek-R1 Models
184
+
185
+ Please visit [DeepSeek-V3](https://github.com/deepseek-ai/DeepSeek-V3) repo for more information about running DeepSeek-R1 locally.
186
+
187
+ **NOTE: Hugging Face's Transformers has not been directly supported yet.**
188
+
189
+ ### DeepSeek-R1-Distill Models
190
+
191
+ DeepSeek-R1-Distill models can be utilized in the same manner as Qwen or Llama models.
192
+
193
+ For instance, you can easily start a service using [vLLM](https://github.com/vllm-project/vllm):
194
+
195
+ ```shell
196
+ vllm serve deepseek-ai/DeepSeek-R1-Distill-Qwen-32B --tensor-parallel-size 2 --max-model-len 32768 --enforce-eager
197
+ ```
198
+
199
+ You can also easily start a service using [SGLang](https://github.com/sgl-project/sglang)
200
+
201
+ ```bash
202
+ python3 -m sglang.launch_server --model deepseek-ai/DeepSeek-R1-Distill-Qwen-32B --trust-remote-code --tp 2
203
+ ```
204
+
205
+ ### Usage Recommendations
206
+
207
+ **We recommend adhering to the following configurations when utilizing the DeepSeek-R1 series models, including benchmarking, to achieve the expected performance:**
208
+
209
+ 1. Set the temperature within the range of 0.5-0.7 (0.6 is recommended) to prevent endless repetitions or incoherent outputs.
210
+ 2. **Avoid adding a system prompt; all instructions should be contained within the user prompt.**
211
+ 3. For mathematical problems, it is advisable to include a directive in your prompt such as: "Please reason step by step, and put your final answer within \boxed{}."
212
+ 4. When evaluating model performance, it is recommended to conduct multiple tests and average the results.
213
+
214
+ Additionally, we have observed that the DeepSeek-R1 series models tend to bypass thinking pattern (i.e., outputting "\<think\>\n\n\</think\>") when responding to certain queries, which can adversely affect the model's performance.
215
+ **To ensure that the model engages in thorough reasoning, we recommend enforcing the model to initiate its response with "\<think\>\n" at the beginning of every output.**
216
+
217
+ ## 7. License
218
+ This code repository and the model weights are licensed under the [MIT License](https://github.com/deepseek-ai/DeepSeek-R1/blob/main/LICENSE).
219
+ DeepSeek-R1 series support commercial use, allow for any modifications and derivative works, including, but not limited to, distillation for training other LLMs. Please note that:
220
+ - DeepSeek-R1-Distill-Qwen-1.5B, DeepSeek-R1-Distill-Qwen-7B, DeepSeek-R1-Distill-Qwen-14B and DeepSeek-R1-Distill-Qwen-32B are derived from [Qwen-2.5 series](https://github.com/QwenLM/Qwen2.5), which are originally licensed under [Apache 2.0 License](https://huggingface.co/Qwen/Qwen2.5-1.5B/blob/main/LICENSE), and now finetuned with 800k samples curated with DeepSeek-R1.
221
+ - DeepSeek-R1-Distill-Llama-8B is derived from Llama3.1-8B-Base and is originally licensed under [llama3.1 license](https://huggingface.co/meta-llama/Llama-3.1-8B/blob/main/LICENSE).
222
+ - DeepSeek-R1-Distill-Llama-70B is derived from Llama3.3-70B-Instruct and is originally licensed under [llama3.3 license](https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct/blob/main/LICENSE).
223
+
224
+ ## 8. Citation
225
+ ```
226
+ @misc{deepseekai2025deepseekr1incentivizingreasoningcapability,
227
+ title={DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning},
228
+ author={DeepSeek-AI},
229
+ year={2025},
230
+ eprint={2501.12948},
231
+ archivePrefix={arXiv},
232
+ primaryClass={cs.CL},
233
+ url={https://arxiv.org/abs/2501.12948},
234
+ }
235
+
236
+ ```
237
+
238
+ ## 9. Contact
239
+ If you have any questions, please raise an issue or contact us at [[email protected]]([email protected]).
config.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 0,
14
+ "eos_token_id": 1,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 3,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 7168,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 18432,
21
+ "kv_lora_rank": 512,
22
+ "max_position_embeddings": 163840,
23
+ "model_type": "deepseek_v3",
24
+ "moe_intermediate_size": 2048,
25
+ "moe_layer_freq": 1,
26
+ "n_group": 8,
27
+ "n_routed_experts": 256,
28
+ "n_shared_experts": 1,
29
+ "norm_topk_prob": true,
30
+ "num_attention_heads": 128,
31
+ "num_experts_per_tok": 8,
32
+ "num_hidden_layers": 61,
33
+ "num_key_value_heads": 128,
34
+ "num_nextn_predict_layers": 1,
35
+ "pretraining_tp": 1,
36
+ "q_lora_rank": 1536,
37
+ "qk_nope_head_dim": 128,
38
+ "qk_rope_head_dim": 64,
39
+ "rms_norm_eps": 1e-06,
40
+ "rope_scaling": {
41
+ "beta_fast": 32,
42
+ "beta_slow": 1,
43
+ "factor": 40,
44
+ "mscale": 1.0,
45
+ "mscale_all_dim": 1.0,
46
+ "original_max_position_embeddings": 4096,
47
+ "type": "yarn"
48
+ },
49
+ "rope_theta": 10000,
50
+ "routed_scaling_factor": 2.5,
51
+ "scoring_func": "sigmoid",
52
+ "seq_aux": true,
53
+ "tie_word_embeddings": false,
54
+ "topk_group": 4,
55
+ "topk_method": "noaux_tc",
56
+ "torch_dtype": "bfloat16",
57
+ "transformers_version": "4.46.3",
58
+ "use_cache": true,
59
+ "v_head_dim": 128,
60
+ "vocab_size": 129280
61
+ }
configuration_deepseek.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ logger = logging.get_logger(__name__)
5
+
6
+ DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
7
+ class DeepseekV3Config(PretrainedConfig):
8
+ r"""
9
+ This is the configuration class to store the configuration of a [`DeepseekV3Model`]. It is used to instantiate an DeepSeek
10
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
11
+ defaults will yield a similar configuration to that of the DeepSeek-V3.
12
+
13
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
14
+ documentation from [`PretrainedConfig`] for more information.
15
+
16
+
17
+ Args:
18
+ vocab_size (`int`, *optional*, defaults to 129280):
19
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
20
+ `inputs_ids` passed when calling [`DeepseekV3Model`]
21
+ hidden_size (`int`, *optional*, defaults to 4096):
22
+ Dimension of the hidden representations.
23
+ intermediate_size (`int`, *optional*, defaults to 11008):
24
+ Dimension of the MLP representations.
25
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
26
+ Dimension of the MoE representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer decoder.
29
+ num_nextn_predict_layers (`int`, *optional*, defaults to 1):
30
+ Number of nextn predict layers in the DeepSeekV3 Model.
31
+ num_attention_heads (`int`, *optional*, defaults to 32):
32
+ Number of attention heads for each attention layer in the Transformer decoder.
33
+ n_shared_experts (`int`, *optional*, defaults to None):
34
+ Number of shared experts, None means dense model.
35
+ n_routed_experts (`int`, *optional*, defaults to None):
36
+ Number of routed experts, None means dense model.
37
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
38
+ Scaling factor or routed experts.
39
+ topk_method (`str`, *optional*, defaults to `gready`):
40
+ Topk method used in routed gate.
41
+ n_group (`int`, *optional*, defaults to None):
42
+ Number of groups for routed experts.
43
+ topk_group (`int`, *optional*, defaults to None):
44
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
45
+ num_experts_per_tok (`int`, *optional*, defaults to None):
46
+ Number of selected experts, None means dense model.
47
+ moe_layer_freq (`int`, *optional*, defaults to 1):
48
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
49
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
50
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
51
+ \--k dense layers--/
52
+ norm_topk_prob (`bool`, *optional*, defaults to False):
53
+ Whether to normalize the weights of the routed experts.
54
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
55
+ Method of computing expert weights.
56
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
57
+ Auxiliary loss weight coefficient.
58
+ seq_aux = (`bool`, *optional*, defaults to True):
59
+ Whether to compute the auxiliary loss for each individual sample.
60
+ num_key_value_heads (`int`, *optional*):
61
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
62
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
63
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
64
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
65
+ by meanpooling all the original heads within that group. For more details checkout [this
66
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
67
+ `num_attention_heads`.
68
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
69
+ The non-linear activation function (function or string) in the decoder.
70
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
71
+ The maximum sequence length that this model might ever be used with.
72
+ initializer_range (`float`, *optional*, defaults to 0.02):
73
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
74
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
75
+ The epsilon used by the rms normalization layers.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ pad_token_id (`int`, *optional*):
80
+ Padding token id.
81
+ bos_token_id (`int`, *optional*, defaults to 1):
82
+ Beginning of stream token id.
83
+ eos_token_id (`int`, *optional*, defaults to 2):
84
+ End of stream token id.
85
+ pretraining_tp (`int`, *optional*, defaults to 1):
86
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
87
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
88
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
89
+ issue](https://github.com/pytorch/pytorch/issues/76232).
90
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
91
+ Whether to tie weight embeddings
92
+ rope_theta (`float`, *optional*, defaults to 10000.0):
93
+ The base period of the RoPE embeddings.
94
+ rope_scaling (`Dict`, *optional*):
95
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
96
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
97
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
98
+ `max_position_embeddings` to the expected new maximum.
99
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
100
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
101
+ attention_dropout (`float`, *optional*, defaults to 0.0):
102
+ The dropout ratio for the attention probabilities.
103
+
104
+ ```python
105
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
106
+
107
+ >>> # Initializing a Deepseek-V3 style configuration
108
+ >>> configuration = DeepseekV3Config()
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "deepseek_v3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=129280,
120
+ hidden_size=7168,
121
+ intermediate_size=18432,
122
+ moe_intermediate_size = 2048,
123
+ num_hidden_layers=61,
124
+ num_nextn_predict_layers=1,
125
+ num_attention_heads=128,
126
+ num_key_value_heads=128,
127
+ n_shared_experts = 1,
128
+ n_routed_experts = 256,
129
+ ep_size = 1,
130
+ routed_scaling_factor = 2.5,
131
+ kv_lora_rank = 512,
132
+ q_lora_rank = 1536,
133
+ qk_rope_head_dim = 64,
134
+ v_head_dim = 128,
135
+ qk_nope_head_dim = 128,
136
+ topk_method = 'noaux_tc',
137
+ n_group = 8,
138
+ topk_group = 4,
139
+ num_experts_per_tok = 8,
140
+ moe_layer_freq = 1,
141
+ first_k_dense_replace = 3,
142
+ norm_topk_prob = True,
143
+ scoring_func = 'sigmoid',
144
+ aux_loss_alpha = 0.001,
145
+ seq_aux = True,
146
+ hidden_act="silu",
147
+ max_position_embeddings=4096,
148
+ initializer_range=0.02,
149
+ rms_norm_eps=1e-6,
150
+ use_cache=True,
151
+ pad_token_id=None,
152
+ bos_token_id=0,
153
+ eos_token_id=1,
154
+ pretraining_tp=1,
155
+ tie_word_embeddings=False,
156
+ rope_theta=10000.0,
157
+ rope_scaling=None,
158
+ attention_bias=False,
159
+ attention_dropout=0.0,
160
+ **kwargs,
161
+ ):
162
+ self.vocab_size = vocab_size
163
+ self.max_position_embeddings = max_position_embeddings
164
+ self.hidden_size = hidden_size
165
+ self.intermediate_size = intermediate_size
166
+ self.moe_intermediate_size = moe_intermediate_size
167
+ self.num_hidden_layers = num_hidden_layers
168
+ self.num_nextn_predict_layers = num_nextn_predict_layers
169
+ self.num_attention_heads = num_attention_heads
170
+ self.n_shared_experts = n_shared_experts
171
+ self.n_routed_experts = n_routed_experts
172
+ self.ep_size = ep_size
173
+ self.routed_scaling_factor = routed_scaling_factor
174
+ self.kv_lora_rank = kv_lora_rank
175
+ self.q_lora_rank = q_lora_rank
176
+ self.qk_rope_head_dim = qk_rope_head_dim
177
+ self.v_head_dim = v_head_dim
178
+ self.qk_nope_head_dim = qk_nope_head_dim
179
+ self.topk_method = topk_method
180
+ self.n_group = n_group
181
+ self.topk_group = topk_group
182
+ self.num_experts_per_tok = num_experts_per_tok
183
+ self.moe_layer_freq = moe_layer_freq
184
+ self.first_k_dense_replace = first_k_dense_replace
185
+ self.norm_topk_prob = norm_topk_prob
186
+ self.scoring_func = scoring_func
187
+ self.aux_loss_alpha = aux_loss_alpha
188
+ self.seq_aux = seq_aux
189
+ # for backward compatibility
190
+ if num_key_value_heads is None:
191
+ num_key_value_heads = num_attention_heads
192
+
193
+ self.num_key_value_heads = num_key_value_heads
194
+ self.hidden_act = hidden_act
195
+ self.initializer_range = initializer_range
196
+ self.rms_norm_eps = rms_norm_eps
197
+ self.pretraining_tp = pretraining_tp
198
+ self.use_cache = use_cache
199
+ self.rope_theta = rope_theta
200
+ self.rope_scaling = rope_scaling
201
+ self.attention_bias = attention_bias
202
+ self.attention_dropout = attention_dropout
203
+
204
+ super().__init__(
205
+ pad_token_id=pad_token_id,
206
+ bos_token_id=bos_token_id,
207
+ eos_token_id=eos_token_id,
208
+ tie_word_embeddings=tie_word_embeddings,
209
+ **kwargs,
210
+ )
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "do_sample": true,
6
+ "temperature": 0.6,
7
+ "top_p": 0.95,
8
+ "transformers_version": "4.39.3"
9
+ }
inference/bf16_cast_channel_int8.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from argparse import ArgumentParser
4
+ from glob import glob
5
+ from tqdm import tqdm
6
+
7
+ import torch
8
+ from safetensors.torch import load_file, save_file
9
+ from huggingface_hub import snapshot_download
10
+
11
+ def weight_quant(tensor: torch.Tensor):
12
+ assert tensor.dim() == 2
13
+ qmax = 127.0
14
+ abs_max = torch.abs(tensor).max(dim=1, keepdim=True)[0] # [rows, 1]
15
+ scale = abs_max / qmax # [rows, 1]
16
+ assert scale.shape == (tensor.shape[0], 1)
17
+ quantized = torch.round(tensor / scale)
18
+ quantized = torch.clamp(quantized, -qmax, qmax)
19
+ return quantized.to(torch.int8), scale.to(torch.float32)
20
+
21
+ def main(bf16_path, int8_path, model_name="deepseek-ai/DeepSeek-R1"):
22
+ torch.set_default_dtype(torch.bfloat16)
23
+ os.makedirs(int8_path, exist_ok=True)
24
+ model_index_file = os.path.join(int8_path, "model.safetensors.index.json")
25
+ config_file = os.path.join(int8_path, "config.json")
26
+
27
+ if not os.path.exists(model_index_file) or not os.path.exists(config_file):
28
+ snapshot_download(
29
+ repo_id=model_name,
30
+ ignore_patterns=["*.safetensors"],
31
+ local_dir=int8_path,
32
+ local_dir_use_symlinks=False
33
+ )
34
+ print(f"model index file and config file downloaded to {int8_path}")
35
+
36
+ # modify config.json and save it
37
+ config = json.load(open(config_file))
38
+ # delete quantization_config
39
+ config.pop("quantization_config", None)
40
+ with open(config_file, "w", encoding="utf-8") as f:
41
+ json.dump(config, f, indent=2, ensure_ascii=False, sort_keys=True)
42
+ print(f"config.json modified and saved to {config_file}")
43
+
44
+ with open(model_index_file, "r") as f:
45
+ model_index = json.load(f)
46
+ weight_map = model_index["weight_map"]
47
+ scale_count = len([key for key in weight_map.keys() if key.endswith("_scale_inv")])
48
+
49
+ safetensor_files = list(glob(os.path.join(bf16_path, "*.safetensors")))
50
+ safetensor_files.sort()
51
+ quant_count = 0
52
+ new_weight_map = {}
53
+ for safetensor_file in tqdm(safetensor_files):
54
+ file_name = os.path.basename(safetensor_file)
55
+ state_dict = load_file(safetensor_file, device="cuda")
56
+ new_state_dict = {}
57
+ for weight_name, weight in state_dict.items():
58
+ scale_inv_name = f"{weight_name}_scale_inv"
59
+ if scale_inv_name in weight_map:
60
+ assert weight.element_size() == 2
61
+ quant_count += 1
62
+ int8_weight, scale_inv = weight_quant(weight)
63
+ new_state_dict[weight_name] = int8_weight
64
+ new_scale_name = scale_inv_name.replace("_scale_inv", "_scale")
65
+ new_state_dict[new_scale_name] = scale_inv
66
+
67
+ new_weight_map[weight_name] = file_name
68
+ new_weight_map[new_scale_name] = file_name
69
+ else:
70
+ new_state_dict[weight_name] = weight
71
+ new_weight_map[weight_name] = file_name
72
+ new_safetensor_file = os.path.join(int8_path, file_name)
73
+ save_file(new_state_dict, new_safetensor_file)
74
+ assert quant_count == scale_count
75
+ print(f"{quant_count} weights are quantized.")
76
+
77
+ # modify model.safetensors.index.json
78
+ with open(model_index_file, "r") as f:
79
+ model_index = json.load(f)
80
+ model_index["weight_map"] = new_weight_map
81
+ with open(model_index_file, "w", encoding="utf-8") as f:
82
+ json.dump(model_index, f, indent=2, ensure_ascii=False, sort_keys=True)
83
+ print(f"model.safetensors.index.json modified and saved to {model_index_file}")
84
+
85
+
86
+ if __name__ == "__main__":
87
+ parser = ArgumentParser()
88
+ parser.add_argument("--input-bf16-hf-path", type=str, required=True)
89
+ parser.add_argument("--output-int8-hf-path", type=str, required=True)
90
+ parser.add_argument("--model-name", type=str, default="deepseek-ai/DeepSeek-R1")
91
+
92
+ args = parser.parse_args()
93
+ main(args.input_bf16_hf_path, args.output_int8_hf_path, args.model_name)
94
+ print("done")
95
+
inference/kernel.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+
3
+ import torch
4
+ import triton
5
+ import triton.language as tl
6
+ from triton import Config
7
+
8
+ @triton.jit
9
+ def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr):
10
+ pid = tl.program_id(axis=0)
11
+ offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
12
+ x = tl.load(x_ptr + offs).to(tl.float32)
13
+ s = tl.max(tl.abs(x)) / 448.
14
+ y = x / s
15
+ y = y.to(y_ptr.dtype.element_ty)
16
+ tl.store(y_ptr + offs, y)
17
+ tl.store(s_ptr + pid, s)
18
+
19
+
20
+ def act_quant(x: torch.Tensor, block_size: int = 128) -> Tuple[torch.Tensor, torch.Tensor]:
21
+ assert x.is_contiguous()
22
+ assert x.size(-1) % block_size == 0
23
+ y = torch.empty_like(x, dtype=torch.float8_e4m3fn)
24
+ s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
25
+ grid = lambda meta: (triton.cdiv(x.numel(), meta['BLOCK_SIZE']), )
26
+ act_quant_kernel[grid](x, y, s, BLOCK_SIZE=block_size)
27
+ return y, s
28
+
29
+
30
+ @triton.jit
31
+ def weight_dequant_kernel(x_ptr, s_ptr, y_ptr, M, N, BLOCK_SIZE: tl.constexpr):
32
+ pid_m = tl.program_id(axis=0)
33
+ pid_n = tl.program_id(axis=1)
34
+ n = tl.cdiv(N, BLOCK_SIZE)
35
+ offs_m = pid_m * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
36
+ offs_n = pid_n * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
37
+ offs = offs_m[:, None] * N + offs_n[None, :]
38
+ mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)
39
+ x = tl.load(x_ptr + offs, mask=mask).to(tl.float32)
40
+ s = tl.load(s_ptr + pid_m * n + pid_n)
41
+ y = x * s
42
+ tl.store(y_ptr + offs, y, mask=mask)
43
+
44
+
45
+ def weight_dequant(x: torch.Tensor, s: torch.Tensor, block_size: int = 128) -> torch.Tensor:
46
+ assert x.is_contiguous() and s.is_contiguous()
47
+ assert x.dim() == 2 and s.dim() == 2
48
+ M, N = x.size()
49
+ y = torch.empty_like(x, dtype=torch.get_default_dtype())
50
+ grid = lambda meta: (triton.cdiv(M, meta['BLOCK_SIZE']), triton.cdiv(N, meta['BLOCK_SIZE']))
51
+ weight_dequant_kernel[grid](x, s, y, M, N, BLOCK_SIZE=block_size)
52
+ return y
53
+
54
+
55
+ @triton.jit
56
+ def weight_quant_kernel(x_ptr, y_ptr, s_ptr, M, N, BLOCK_SIZE: tl.constexpr):
57
+ pid_m = tl.program_id(axis=0)
58
+ pid_n = tl.program_id(axis=1)
59
+ n = tl.cdiv(N, BLOCK_SIZE)
60
+ offs_m = pid_m * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
61
+ offs_n = pid_n * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
62
+ offs = offs_m[:, None] * N + offs_n[None, :]
63
+ mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)
64
+ x = tl.load(x_ptr + offs, mask=mask).to(tl.float32)
65
+ s = tl.max(tl.abs(x)) / 127.#int8
66
+ y = x / s
67
+ y = y.to(y_ptr.dtype.element_ty)
68
+ tl.store(y_ptr + offs, y, mask=mask)
69
+ tl.store(s_ptr + pid_m * n + pid_n, s)
70
+
71
+ # quant to block int8
72
+ def weight_quant(x: torch.Tensor, block_size: int = 128) -> Tuple[torch.Tensor, torch.Tensor]:
73
+ assert x.is_contiguous()
74
+ assert x.dim() == 2
75
+ M, N = x.size()
76
+ y = torch.empty_like(x, dtype=torch.int8)
77
+ sM, sN = torch.tensor(1.0*M/block_size).ceil().int(), torch.tensor(1.0*N/block_size).ceil().int()
78
+ s = x.new_empty(sM, sN, dtype=torch.float32)
79
+ grid = lambda meta: (triton.cdiv(M, meta['BLOCK_SIZE']), triton.cdiv(N, meta['BLOCK_SIZE']))
80
+ weight_quant_kernel[grid](x, y, s, M, N, BLOCK_SIZE=block_size)
81
+ return y, s
82
+
83
+
84
+ fp8_gemm_configs = [
85
+ Config({'BLOCK_SIZE_M': block_m, 'BLOCK_SIZE_N': block_n, 'BLOCK_SIZE_K': 128}, num_stages=num_stages, num_warps=8)
86
+ for block_m in [16, 32, 64] for block_n in [32, 64, 128] for num_stages in [3, 4, 5, 6]
87
+ ]
88
+
89
+ @triton.autotune(configs=fp8_gemm_configs, key=['N', 'K'])
90
+ @triton.jit
91
+ def fp8_gemm_kernel(a_ptr, b_ptr, c_ptr,
92
+ a_s_ptr, b_s_ptr,
93
+ M, N: tl.constexpr, K: tl.constexpr,
94
+ BLOCK_SIZE_M: tl.constexpr,
95
+ BLOCK_SIZE_N: tl.constexpr,
96
+ BLOCK_SIZE_K: tl.constexpr):
97
+ pid_m = tl.program_id(axis=0)
98
+ pid_n = tl.program_id(axis=1)
99
+ k = tl.cdiv(K, BLOCK_SIZE_K)
100
+ offs_m = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
101
+ offs_n = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
102
+ offs_k = tl.arange(0, BLOCK_SIZE_K)
103
+ a_ptrs = a_ptr + offs_m[:, None] * K + offs_k[None, :]
104
+ b_ptrs = b_ptr + offs_n[None, :] * K + offs_k[:, None]
105
+ a_s_ptrs = a_s_ptr + offs_m * k
106
+ b_s_ptrs = b_s_ptr + (offs_n // BLOCK_SIZE_K) * k
107
+
108
+ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
109
+ for i in range(k):
110
+ a = tl.load(a_ptrs, mask=offs_k[None, :] < K - i * BLOCK_SIZE_K, other=0.0)
111
+ b = tl.load(b_ptrs, mask=offs_k[:, None] < K - i * BLOCK_SIZE_K, other=0.0)
112
+ a_s = tl.load(a_s_ptrs)
113
+ b_s = tl.load(b_s_ptrs)
114
+ accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
115
+ a_ptrs += BLOCK_SIZE_K
116
+ b_ptrs += BLOCK_SIZE_K
117
+ a_s_ptrs += 1
118
+ b_s_ptrs += 1
119
+ c = accumulator.to(c_ptr.dtype.element_ty)
120
+ offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
121
+ offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
122
+ c_ptrs = c_ptr + offs_m[:, None] * N + offs_n[None, :]
123
+ mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)
124
+ tl.store(c_ptrs, c, mask=mask)
125
+
126
+
127
+ def fp8_gemm(a: torch.Tensor, a_s: torch.Tensor, b: torch.Tensor, b_s: torch.Tensor):
128
+ assert a.is_contiguous() and b.is_contiguous()
129
+ assert a_s.is_contiguous() and b_s.is_contiguous()
130
+ K = a.size(-1)
131
+ M = a.numel() // K
132
+ N = b.size(0)
133
+ c = a.new_empty(*a.size()[:-1], N, dtype=torch.get_default_dtype())
134
+ grid = lambda META: (triton.cdiv(M, META['BLOCK_SIZE_M']), triton.cdiv(N, META['BLOCK_SIZE_N']))
135
+ fp8_gemm_kernel[grid](a, b, c, a_s, b_s, M, N, K)
136
+ return c
model-00001-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef3d88cf1e73ba0e44802173f9bc60a578e320b79c80373ed9ab467377d3d772
3
+ size 5236369040
model-00002-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:277c11384b925bc7652a98134b1d68f505d53a1635abbe9bfa8b01d811b8a491
3
+ size 4305737040
model-00003-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f6a815fe689d3eb14ae9414ed230d812f45c1d9c38fe15a4461e82e301cf2bb2
3
+ size 4305737448
model-00004-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9284af3d323dbdc7141af71f7336c2f7ca67eeb7e54f0149d6cc6a6ad5f880c6
3
+ size 4305761544
model-00005-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d670c22cabc3f3b69a04f92699f7ffdb602c4a4a332cf9118eefaa28cc04eaa
3
+ size 4305737224
model-00006-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b903c0a69d6284d8001a7ad72a5dd7a558140d795692c249b1fb56330ab05b4
3
+ size 4375574176
model-00007-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03667366eacf64046970c05294e2171f8343120c9f7fe83507fde10dd85c8e6e
3
+ size 4309387600
model-00009-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7152b5c650d6adebe13b6f68e4d182535358dc44629cede514ba6ad3858abbe0
3
+ size 4305761736
model-00010-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9dbc77a021e7c0299df3f7b3ed414155af5fca1742f2373af9968f34437bec09
3
+ size 4305737032
model-00011-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a55e03e8c5a7368345b235d20b5006f44195a27ae3200b4e6db36375e4f9e05
3
+ size 4305737448
model-00012-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f51f32f5bf75fe53880b93016a94408c2626239e850228d1125e36050dceff3
3
+ size 1322608064
model-00013-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:838eaee61e21b5109c4c469ed953f2894032719bb455f012bfe420635472d7c6
3
+ size 4305732480
model-00014-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51752907be40b93818fa69fd20a976b672afe9346631cc6f7049ef0559f8d9aa
3
+ size 4305737400
model-00015-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19d6da768e75ff7b22d3a74f6e442fefa4926244bf627f218b9d2442333ed0c8
3
+ size 4305761768
model-00016-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdc10437b7b8e42c8c73ccd7a09928ad9b7a8dd5d7f03de09814af35e77ebc9a
3
+ size 4305737008
model-00017-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81314e223ab55baeacb7f147ad4a6685b07b82936ef454e9683e457740d3f585
3
+ size 4305716968
model-00019-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7986c4c7674e8d4e9177e3a0791af9bfbf698fcd8f3456ecbef03329815c7ab
3
+ size 4305716712
model-00020-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0268ccee978a221951350cc1e26b1b55682cecafc7165f5efd9ba9006390b16f
3
+ size 4305737456
model-00021-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:581755da204ebfd20b2819aa957ec7d036125a5716e6f114cb3e6a44fe1973e8
3
+ size 4305761936
model-00022-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39d03d2500d8672eb14c46e3a62af72a796deadd2c4d080580679ff4b14625c7
3
+ size 4305737976
model-00023-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19f81a27ac3a69534bf9d5aa39e65280cd398af747de2ccb00dbef3be5499131
3
+ size 4305762360
model-00026-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:831b6add17f7ddb62d55fd9a95551afe5be881f2c692e01004fea39cd6890d73
3
+ size 4305762168
model-00029-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5cb1244f84384eb3a2360f92184392411afd152645f708704a4938e1c028f67a
3
+ size 4305782464
model-00030-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17c3c0b970e82f2ec9438d3cf08064c6f3ea127ea2ebce7c970b617c7cd8ed44
3
+ size 4305717472
model-00031-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06f0ed9040ecb4a4ecb8585bf1ab0f59b11dc3e6a23e2b2f9b3c5c24f42c9822
3
+ size 4305782864
model-00032-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e016a3c73eb6132eae5cb8b8da53731655e0ccd50befee8272a6f9439800b1c7
3
+ size 4305717080
model-00033-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0764e8d2690cd938100933087699e219ea7fd6339ed38a25890910d4ed872a7a
3
+ size 4305738048
model-00034-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:227a4ac45a97716ce59380dba0bd29040ed02021dff6ed9878c68590fb45b456
3
+ size 1748779624
model-00035-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b15c237b61c9c59c2799c7939156d7d8ee87d219988ac2b44395e1d645bcd6b
3
+ size 4305733056
model-00037-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0b2e8738aa549b96a3a41fc83ef5bcd973d4fa47c9de31b2d487ee544e20c72
3
+ size 4305762344
model-00038-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b33277d423c67a62b0cc5a4d7d07c3a855f666e3291cdd497dd208a5e899b2c9
3
+ size 4305737592
model-00039-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ccb350d98b7bc6b4312188927ae344c199a2b48278bd0b83443676eca3173ea
3
+ size 4305717552
model-00040-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9409c38307db9adf25364abe8938563200a94ad00a98cefb67f246b234c8513d
3
+ size 4305782640
model-00041-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:960e508b1a691476882b7f47fa20ec705b1850ac1546e4a26033a561c925b4d6
3
+ size 4305717304
model-00042-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5cb39dc86cbba28307393407816e20b053a5e61d9fa80ab43fb2db378583bb3a
3
+ size 4305738048
model-00043-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f40870f7a995013ec48e7ab949a914801d0377e2b449e2dec1d29a60a999a34c
3
+ size 4305761960
model-00045-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfd272252d354788fed1896b74f2c8fc0f8cb451e6f217467240f9b16bf14339
3
+ size 4305762360
model-00046-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07ad34a51ba6605a83f6d0f164d7e4b503f9dd3d549a2577a395175ac885829b
3
+ size 4305737584
model-00047-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:940176847c29e872eaa78257d8dd9f47cd481b38cbb49ef4fd2058558360c784
3
+ size 4305738040
model-00048-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e40de3791a213a24f82e7a2f3de520899c86888c022152bc16fef6569c7db0e7
3
+ size 4305762168
model-00049-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e53a5cc9aeed9d754de147d07a35e89362cd8322a09b8f6c1562d7d2cb31e2b
3
+ size 4305737768
model-00050-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e3bd58a24a44fa81e9dc7350ef7f18358644df5e169a3f8b781ff298dd239f4
3
+ size 4305717552
model-00051-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:001537af8037b19b5f4fa89769d9999e7b144da634188a07cffad4ba83df459e
3
+ size 4305782464