AlphaGaO commited on
Commit
5b10ba1
·
verified ·
1 Parent(s): 7000893

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ ---
4
+ <!-- markdownlint-disable first-line-h1 -->
5
+ <!-- markdownlint-disable html -->
6
+ <!-- markdownlint-disable no-duplicate-header -->
7
+
8
+ README.md
9
+ # Unhealed DeepSeek-v3-0324-Instruct Fused Models (Research Release)
10
+
11
+ ## CRITICAL NOTE: Untrained Fusion - Requires Healing!
12
+
13
+ **These are *unhealed*, experimental versions of DeepSeek-v3-0324-instruct created through model fusion. They are *not* ready for direct use and will exhibit unpredictable behavior without significant post-training.** These models are released *exclusively* for research purposes and require a specific "healing" process to restore functionality. Do *not* use these models without understanding and applying the healing procedure.
14
+
15
+ **Preview Models: Exploring Compression Levels**
16
+
17
+ The DeepSeek-V3-0324 model, which utilizes 256 experts, forms the foundation for these preview models. We offer four variations, each with a different level of compression:
18
+
19
+ * **8 Fused Experts, rank 4 (~33B parameters):** 1/20 size reduction.
20
+ * **4 Fused Experts, rank 4 (~29B parameters):** 1/23 size reduction.
21
+
22
+ Despite their significantly reduced size, these models demonstrate surprisingly strong performance, exceeding expectations for their parameter counts. Further, more comprehensive testing is planned.
23
+
24
+ ## What to Expect (Before Healing)
25
+
26
+ These models are in an initial, unstable state after the fusion process. Expect significantly degraded performance and unpredictable outputs. They are *not* representative of the final capabilities of a properly trained fused model. This is a very early iteration of the fusion and distillation technique, using a small sample size for distillation. Significant room for improvement remains in the distillation process.
27
+
28
+ ## Healing Instructions (Required)
29
+
30
+ **Crucially, you *must* perform post-training to make these models usable.** The necessary scripts and detailed instructions are available in the **moe-pruner** repository:
31
+
32
+ **[https://github.com/gabrielolympie/moe-pruner](https://github.com/gabrielolympie/moe-pruner)**
33
+
34
+ Follow the instructions in that repository *carefully* to "heal" the pruned model. This process is essential to recover performance.
35
+
36
+ ## Contributing and Future Improvements
37
+
38
+ This release represents an initial exploration of model fusion and distillation. Due to hardware limitations, significant compromises were made during development.
39
+
40
+ We welcome contributions to improve this work! There are two primary ways to help:
41
+
42
+ 1. **Financial Support:** Larger-scale experiments require significant compute resources. If you'd like to support future versions with a higher compute budget, you can donate here: [https://gofund.me/1516dccd](https://gofund.me/1516dccd)
43
+
44
+ 2. **Code Contributions:** Suggest improvements, bug fixes, or new features directly on the GitHub repository.
45
+
46
+ We are actively working to improve the fusion and distillation techniques, and your contributions are greatly appreciated.
47
+
48
+ ## Disclaimer
49
+
50
+ These models are provided "as is" for research purposes only. No guarantees are made regarding their performance or stability before the healing process is completed. Use at your own risk.
51
+
52
+ #
53
+ #
54
+ #
55
+ #
56
+
57
+
58
+ ## Original Model Card
59
+
60
+ ---
61
+ license: mit
62
+ library_name: transformers
63
+ ---
64
+ # DeepSeek-V3-0324
65
+ <!-- markdownlint-disable first-line-h1 -->
66
+ <!-- markdownlint-disable html -->
67
+ <!-- markdownlint-disable no-duplicate-header -->
68
+
69
+ <div align="center">
70
+ <img src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/logo.svg?raw=true" width="60%" alt="DeepSeek-V3" />
71
+ </div>
72
+ <hr>
73
+ <div align="center" style="line-height: 1;">
74
+ <a href="https://www.deepseek.com/" target="_blank" style="margin: 2px;">
75
+ <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;"/>
76
+ </a>
77
+ <a href="https://chat.deepseek.com/" target="_blank" style="margin: 2px;">
78
+ <img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-DeepSeek%20V3-536af5?color=536af5&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
79
+ </a>
80
+ <a href="https://huggingface.co/deepseek-ai" target="_blank" style="margin: 2px;">
81
+ <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;"/>
82
+ </a>
83
+ </div>
84
+
85
+ <div align="center" style="line-height: 1;">
86
+ <a href="https://discord.gg/Tc7c45Zzu5" target="_blank" style="margin: 2px;">
87
+ <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;"/>
88
+ </a>
89
+ <a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/qr.jpeg?raw=true" target="_blank" style="margin: 2px;">
90
+ <img alt="Wechat" src="https://img.shields.io/badge/WeChat-DeepSeek%20AI-brightgreen?logo=wechat&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
91
+ </a>
92
+ <a href="https://twitter.com/deepseek_ai" target="_blank" style="margin: 2px;">
93
+ <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;"/>
94
+ </a>
95
+ </div>
96
+
97
+ <div align="center" style="line-height: 1;">
98
+ <a href="LICENSE" style="margin: 2px;">
99
+ <img alt="License" src="https://img.shields.io/badge/License-MIT-f5de53?&color=f5de53" style="display: inline-block; vertical-align: middle;"/>
100
+ </a>
101
+ </div>
102
+
103
+ ## Features
104
+
105
+ DeepSeek-V3-0324 demonstrates notable improvements over its predecessor, DeepSeek-V3, in several key aspects.
106
+
107
+ ![Model Performance](figures/0324_comparison.png)
108
+
109
+ ### Reasoning Capabilities
110
+
111
+ - Significant improvements in benchmark performance:
112
+ - MMLU-Pro: 75.9 → 81.2 (+5.3)
113
+ - GPQA: 59.1 → 68.4 (+9.3)
114
+ - AIME: 39.6 → 59.4 (+19.8)
115
+ - LiveCodeBench: 39.2 → 49.2 (+10.0)
116
+
117
+ ### Front-End Web Development
118
+
119
+ - Improved the executability of the code
120
+ - More aesthetically pleasing web pages and game front-ends
121
+
122
+ ### Chinese Writing Proficiency
123
+
124
+ - Enhanced style and content quality:
125
+ - Aligned with the R1 writing style
126
+ - Better quality in medium-to-long-form writing
127
+
128
+ - Feature Enhancements
129
+ - Improved multi-turn interactive rewriting
130
+ - Optimized translation quality and letter writing
131
+
132
+ ### Chinese Search Capabilities
133
+
134
+ - Enhanced report analysis requests with more detailed outputs
135
+
136
+ ### Function Calling Improvements
137
+
138
+ - Increased accuracy in Function Calling, fixing issues from previous V3 versions
139
+
140
+ ---
141
+
142
+ ## Usage Recommendations
143
+
144
+ ### System Prompt
145
+
146
+ In the official DeepSeek web/app, we use the same system prompt with a specific date.
147
+
148
+ ```
149
+ 该助手为DeepSeek Chat,由深度求索公司创造。
150
+ 今天是{current date}。
151
+ ```
152
+
153
+ For example,
154
+
155
+ ```
156
+ 该助手为DeepSeek Chat,由深度求索公司创造。
157
+ 今天是3月24日,星期一。
158
+ ```
159
+
160
+ ### Temperature
161
+
162
+ In our web and application environments, the temperature parameter $T_{model}$ is set to 0.3. Because many users use the default temperature 1.0 in API call, we have implemented an API temperature $T_{api}$ mapping mechanism that adjusts the input API temperature value of 1.0 to the most suitable model temperature setting of 0.3.
163
+
164
+ $$
165
+ T_{model} = T_{api} \times 0.3 \quad (0 \leq T_{api} \leq 1)
166
+ $$
167
+
168
+ $$
169
+ T_{model} = T_{api} - 0.7 \quad (1 < T_{api} \leq 2)
170
+ $$
171
+
172
+ Thus, if you call V3 via API, temperature 1.0 equals to the model temperature 0.3.
173
+
174
+ ### Prompts for File Uploading and Web Search
175
+
176
+ For file uploading, please follow the template to create prompts, where {file_name}, {file_content} and {question} are arguments.
177
+
178
+ ```
179
+ file_template = \
180
+ """[file name]: {file_name}
181
+ [file content begin]
182
+ {file_content}
183
+ [file content end]
184
+ {question}"""
185
+ ```
186
+
187
+ For Web Search, {search_results}, {cur_date}, and {question} are arguments.
188
+
189
+ For Chinese query, we use the prompt:
190
+
191
+ ```
192
+ search_answer_zh_template = \
193
+ '''# 以下内容是基于用户发送的消息的搜索结果:
194
+ {search_results}
195
+ 在我给你的搜索结果中,每个结果都是[webpage X begin]...[webpage X end]格式的,X代表每篇文章的数字索引。请在适当的情况下在句子末尾引用上下文。请按照引用编号[citation:X]的格式在答案中对应部分引用上下文。如果一句话源自多个上下文,请列出所有相关的引用编号,例如[citation:3][citation:5],切记不要将引用集中在最后返回引用编号,而是在答案对应部分列出。
196
+ 在回答时,请注意以下几点:
197
+ - 今天是{cur_date}。
198
+ - 并非搜索结果的所有内容都与用户的问题密切相关,你需要结合问题,对搜索结果进行甄别、筛选。
199
+ - 对于列举类的问题(如列举所有航班信息),尽量将答案控制在10个要点以内,并告诉用户可以查看搜索来源、获得完整信息。优先提供信息完整、最相关的列举项;如非必要,不要主动告诉用户搜索结果未提供的内容。
200
+ - 对于创作类的问题(如写论文),请务必在正文的段落中引用对应的参考编号,例如[citation:3][citation:5],不能只在文章末尾引用。你需要解读并概括用户的题目要求,选择合适的格式,充分利用搜索结果并抽取重要信息,生成符合用户要求、极具思想深度、富有创造力与专业性的答案。你的创作篇幅需要尽可能延长,对于每一个要点的论述要推测用户的意图,给出尽可能多角度的回答要点,且务必信息量大、论述详尽。
201
+ - 如果回答很长,请尽量结构化、分段落总结。如果需要分点作答,尽量控制在5个点以内,并合并相关的内容。
202
+ - 对于客观类的问答,如果问题的答案非常简短,可以适当补充一到两句相关信息,以丰富内容。
203
+ - 你需要根据用户要求和回答内容选择合适、美观的回答格式,确保可读性强。
204
+ - 你的回答应该综合多个相关网页来回答,不��重复引用一个网页。
205
+ - 除非用户要求,否则你回答的语言需要和用户提问的语言保持一致。
206
+
207
+ # 用户消息为:
208
+ {question}'''
209
+ ```
210
+
211
+ For English query, we use the prompt:
212
+
213
+ ```
214
+ search_answer_en_template = \
215
+ '''# The following contents are the search results related to the user's message:
216
+ {search_results}
217
+ In the search results I provide to you, each result is formatted as [webpage X begin]...[webpage X end], where X represents the numerical index of each article. Please cite the context at the end of the relevant sentence when appropriate. Use the citation format [citation:X] in the corresponding part of your answer. If a sentence is derived from multiple contexts, list all relevant citation numbers, such as [citation:3][citation:5]. Be sure not to cluster all citations at the end; instead, include them in the corresponding parts of the answer.
218
+ When responding, please keep the following points in mind:
219
+ - Today is {cur_date}.
220
+ - Not all content in the search results is closely related to the user's question. You need to evaluate and filter the search results based on the question.
221
+ - For listing-type questions (e.g., listing all flight information), try to limit the answer to 10 key points and inform the user that they can refer to the search sources for complete information. Prioritize providing the most complete and relevant items in the list. Avoid mentioning content not provided in the search results unless necessary.
222
+ - For creative tasks (e.g., writing an essay), ensure that references are cited within the body of the text, such as [citation:3][citation:5], rather than only at the end of the text. You need to interpret and summarize the user's requirements, choose an appropriate format, fully utilize the search results, extract key information, and generate an answer that is insightful, creative, and professional. Extend the length of your response as much as possible, addressing each point in detail and from multiple perspectives, ensuring the content is rich and thorough.
223
+ - If the response is lengthy, structure it well and summarize it in paragraphs. If a point-by-point format is needed, try to limit it to 5 points and merge related content.
224
+ - For objective Q&A, if the answer is very brief, you may add one or two related sentences to enrich the content.
225
+ - Choose an appropriate and visually appealing format for your response based on the user's requirements and the content of the answer, ensuring strong readability.
226
+ - Your answer should synthesize information from multiple relevant webpages and avoid repeatedly citing the same webpage.
227
+ - Unless the user requests otherwise, your response should be in the same language as the user's question.
228
+
229
+ # The user's message is:
230
+ {question}'''
231
+ ```
232
+
233
+ ## How to Run Locally
234
+
235
+ The model structure of DeepSeek-V3-0324 is exactly the same as DeepSeek-V3. Please visit [DeepSeek-V3](https://github.com/deepseek-ai/DeepSeek-V3) repo for more information about running this model locally.
236
+
237
+ **This model supports features such as function calling, JSON output, and FIM completion. For instructions on how to construct prompts to use these features, please refer to [DeepSeek-V2.5](https://huggingface.co/deepseek-ai/DeepSeek-V2.5#function-calling) repo.**
238
+
239
+ **NOTE: Hugging Face's Transformers has not been directly supported yet.**
240
+
241
+ ## License
242
+
243
+ This repository and the model weights are licensed under the [MIT License](LICENSE).
244
+
245
+ ## Citation
246
+
247
+ ```
248
+ @misc{deepseekai2024deepseekv3technicalreport,
249
+ title={DeepSeek-V3 Technical Report},
250
+ author={DeepSeek-AI},
251
+ year={2024},
252
+ eprint={2412.19437},
253
+ archivePrefix={arXiv},
254
+ primaryClass={cs.CL},
255
+ url={https://arxiv.org/abs/2412.19437},
256
+ }
257
+ ```
258
+
259
+ ## Contact
260
+ If you have any questions, please raise an issue or contact us at [[email protected]]([email protected]).
config.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "../patched_modules/",
3
+ "architectures": [
4
+ "DeepseekV3ForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_deepseek.DeepseekV3Config",
10
+ "AutoModel": "modeling_deepseek.DeepseekV3Model",
11
+ "AutoModelForCausalLM": "modeling_deepseek.DeepseekV3ForCausalLM"
12
+ },
13
+ "aux_loss_alpha": 0.001,
14
+ "bos_token_id": 0,
15
+ "eos_token_id": 1,
16
+ "ep_size": 1,
17
+ "first_k_dense_replace": 3,
18
+ "fused_expert_dora_rank": 4,
19
+ "fused_expert_method": "mixture",
20
+ "hidden_act": "silu",
21
+ "hidden_size": 7168,
22
+ "initializer_range": 0.02,
23
+ "intermediate_size": 18432,
24
+ "kv_lora_rank": 512,
25
+ "max_position_embeddings": 163840,
26
+ "model_type": "deepseek_v3",
27
+ "moe_intermediate_size": 2048,
28
+ "moe_layer_freq": 1,
29
+ "n_fused_experts": 4,
30
+ "n_group": 8,
31
+ "n_routed_experts": 256,
32
+ "n_shared_experts": 1,
33
+ "norm_topk_prob": true,
34
+ "num_attention_heads": 128,
35
+ "num_experts_per_tok": 8,
36
+ "num_hidden_layers": 61,
37
+ "num_key_value_heads": 128,
38
+ "num_nextn_predict_layers": 1,
39
+ "pretraining_tp": 1,
40
+ "q_lora_rank": 1536,
41
+ "qk_nope_head_dim": 128,
42
+ "qk_rope_head_dim": 64,
43
+ "rms_norm_eps": 1e-06,
44
+ "rope_scaling": {
45
+ "beta_fast": 32,
46
+ "beta_slow": 1,
47
+ "factor": 40,
48
+ "mscale": 1.0,
49
+ "mscale_all_dim": 1.0,
50
+ "original_max_position_embeddings": 4096,
51
+ "type": "yarn"
52
+ },
53
+ "rope_theta": 10000,
54
+ "routed_scaling_factor": 2.5,
55
+ "scoring_func": "sigmoid",
56
+ "seq_aux": true,
57
+ "tie_word_embeddings": false,
58
+ "topk_group": 4,
59
+ "topk_method": "noaux_tc",
60
+ "torch_dtype": "bfloat16",
61
+ "transformers_version": "4.45.1",
62
+ "use_cache": true,
63
+ "v_head_dim": 128,
64
+ "vocab_size": 129280
65
+ }
configuration_deepseek.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ n_fused_experts = None,
130
+ fused_expert_dora_rank = None,
131
+ fused_expert_method = "mixture",
132
+ ep_size = 1,
133
+ routed_scaling_factor = 2.5,
134
+ kv_lora_rank = 512,
135
+ q_lora_rank = 1536,
136
+ qk_rope_head_dim = 64,
137
+ v_head_dim = 128,
138
+ qk_nope_head_dim = 128,
139
+ topk_method = 'noaux_tc',
140
+ n_group = 8,
141
+ topk_group = 4,
142
+ num_experts_per_tok = 8,
143
+ moe_layer_freq = 1,
144
+ first_k_dense_replace = 3,
145
+ norm_topk_prob = True,
146
+ scoring_func = 'sigmoid',
147
+ aux_loss_alpha = 0.001,
148
+ seq_aux = True,
149
+ hidden_act="silu",
150
+ max_position_embeddings=4096,
151
+ initializer_range=0.02,
152
+ rms_norm_eps=1e-6,
153
+ use_cache=True,
154
+ pad_token_id=None,
155
+ bos_token_id=0,
156
+ eos_token_id=1,
157
+ pretraining_tp=1,
158
+ tie_word_embeddings=False,
159
+ rope_theta=10000.0,
160
+ rope_scaling=None,
161
+ attention_bias=False,
162
+ attention_dropout=0.0,
163
+ **kwargs,
164
+ ):
165
+ self.vocab_size = vocab_size
166
+ self.max_position_embeddings = max_position_embeddings
167
+ self.hidden_size = hidden_size
168
+ self.intermediate_size = intermediate_size
169
+ self.moe_intermediate_size = moe_intermediate_size
170
+ self.num_hidden_layers = num_hidden_layers
171
+ self.num_nextn_predict_layers = num_nextn_predict_layers
172
+ self.num_attention_heads = num_attention_heads
173
+ self.n_shared_experts = n_shared_experts
174
+ self.n_routed_experts = n_routed_experts
175
+ self.n_fused_experts = n_fused_experts
176
+ self.fused_expert_dora_rank = fused_expert_dora_rank
177
+ self.fused_expert_method=fused_expert_method
178
+ self.ep_size = ep_size
179
+ self.routed_scaling_factor = routed_scaling_factor
180
+ self.kv_lora_rank = kv_lora_rank
181
+ self.q_lora_rank = q_lora_rank
182
+ self.qk_rope_head_dim = qk_rope_head_dim
183
+ self.v_head_dim = v_head_dim
184
+ self.qk_nope_head_dim = qk_nope_head_dim
185
+ self.topk_method = topk_method
186
+ self.n_group = n_group
187
+ self.topk_group = topk_group
188
+ self.num_experts_per_tok = num_experts_per_tok
189
+ self.moe_layer_freq = moe_layer_freq
190
+ self.first_k_dense_replace = first_k_dense_replace
191
+ self.norm_topk_prob = norm_topk_prob
192
+ self.scoring_func = scoring_func
193
+ self.aux_loss_alpha = aux_loss_alpha
194
+ self.seq_aux = seq_aux
195
+ # for backward compatibility
196
+ if num_key_value_heads is None:
197
+ num_key_value_heads = num_attention_heads
198
+
199
+ self.num_key_value_heads = num_key_value_heads
200
+ self.hidden_act = hidden_act
201
+ self.initializer_range = initializer_range
202
+ self.rms_norm_eps = rms_norm_eps
203
+ self.pretraining_tp = pretraining_tp
204
+ self.use_cache = use_cache
205
+ self.rope_theta = rope_theta
206
+ self.rope_scaling = rope_scaling
207
+ self.attention_bias = attention_bias
208
+ self.attention_dropout = attention_dropout
209
+
210
+ super().__init__(
211
+ pad_token_id=pad_token_id,
212
+ bos_token_id=bos_token_id,
213
+ eos_token_id=eos_token_id,
214
+ tie_word_embeddings=tie_word_embeddings,
215
+ **kwargs,
216
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "transformers_version": "4.45.1",
6
+ "use_cache": false
7
+ }
model-00001-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f5309d36af9a0d97cb87b41492feccddf37b2a75b0f3c3649fc703f8de9530a
3
+ size 4825751392
model-00002-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9c0d3cb76ee8c762e0938502a7a790ffae8e6b0b7cbd894714ce67a521fb0a2
3
+ size 4970678760
model-00003-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1fa41f3024deca9bdc19c56e7dc3903ce5b802232ca574194176c4e5e763f216
3
+ size 4842232232
model-00004-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a67983c10696efc78bc66f25b24e91e06991314f5506eb86285fb1ce0bb8f69
3
+ size 4998307776
model-00005-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:752a0d5087cffa1c365d477071f837a77b5ebb5127a5f899617134095cfd01de
3
+ size 4948662416
model-00006-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eacec5e732f7f6dd41c92e1322cd047684aaa4362e82e69ed14203af4fb0ba8f
3
+ size 4946566264
model-00007-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35497d3ec82b795013a6436e39619c5b3e8587950d7361a155c223101ef9d960
3
+ size 4947876984
model-00008-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c8282557199e2ae5ebc5551d225e940f54af490eb7e645e57ac0c457b731415
3
+ size 4980907696
model-00009-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:13dda2e883fd27b51a07af98f87a9489b2d5093c0d4475212d4ba36d82aa0c85
3
+ size 4998307776
model-00010-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8702432807c207a26fe255f392c919a3a9f7a83246d581b434a1b3a8e66e17ce
3
+ size 4948662416
model-00011-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c6e7c39f20b14e3b6cb120b5e959562388100ede08a432ab54174cdb5e53e98
3
+ size 4946566264
model-00012-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a773a7fa3def167aa6bd79e06ac0d8402498960763b0a2c1a9e3340e48459c8
3
+ size 4947876984
model-00013-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d277ea29d65c246764f1a4afe36368b2ccd4f1e8af12e28f140e678169ce1468
3
+ size 4980907696
model-00014-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:441197213b116ea7440e029ca626ca6207c984c2bddb20ed798a9dcf1173f5b8
3
+ size 4998307776
model-00015-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77c4d6ba1751bc9a118794e9697e9c93181416ebb983d9e6b69defe0f9ba3997
3
+ size 4948662416
model-00016-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd33d529f35a1c376bd789a47e92de7a8e67c7eecba4272351c2bd7296c94051
3
+ size 4946566264
model-00017-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa91b0a24bbf498e4c4fbab2d733cfbf862c6a177abdd0bb8f1d930ea74d4e4a
3
+ size 3804195128
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,2061 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )
47
+ from transformers.utils import (
48
+ add_start_docstrings,
49
+ add_start_docstrings_to_model_forward,
50
+ is_flash_attn_2_available,
51
+ is_flash_attn_greater_or_equal_2_10,
52
+ logging,
53
+ replace_return_docstrings,
54
+ )
55
+ from transformers.utils.import_utils import is_torch_fx_available
56
+
57
+ from .configuration_deepseek import DeepseekV3Config
58
+
59
+
60
+ import torch.distributed as dist
61
+ import numpy as np
62
+
63
+ if is_flash_attn_2_available():
64
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
65
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
66
+
67
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
68
+ # It means that the function will not be traced through and simply appear as a node in the graph.
69
+ if is_torch_fx_available():
70
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
71
+
72
+
73
+ logger = logging.get_logger(__name__)
74
+
75
+ _CONFIG_FOR_DOC = "DeepseekV3Config"
76
+
77
+
78
+ def _get_unpad_data(attention_mask):
79
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
80
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
81
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
82
+ cu_seqlens = F.pad(
83
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
84
+ )
85
+ return (
86
+ indices,
87
+ cu_seqlens,
88
+ max_seqlen_in_batch,
89
+ )
90
+
91
+
92
+ class DeepseekV3RMSNorm(nn.Module):
93
+ def __init__(self, hidden_size, eps=1e-6):
94
+ """
95
+ DeepseekV3RMSNorm is equivalent to T5LayerNorm
96
+ """
97
+ super().__init__()
98
+ self.weight = nn.Parameter(torch.ones(hidden_size))
99
+ self.variance_epsilon = eps
100
+
101
+ def forward(self, hidden_states):
102
+ input_dtype = hidden_states.dtype
103
+ hidden_states = hidden_states.to(torch.float32)
104
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
105
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
106
+ return self.weight * hidden_states.to(input_dtype)
107
+
108
+
109
+ ALL_LAYERNORM_LAYERS.append(DeepseekV3RMSNorm)
110
+
111
+
112
+ class DeepseekV3RotaryEmbedding(nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ inv_freq = 1.0 / (
120
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
121
+ )
122
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
123
+
124
+ # Build here to make `torch.jit.trace` work.
125
+ self._set_cos_sin_cache(
126
+ seq_len=max_position_embeddings,
127
+ device=self.inv_freq.device,
128
+ dtype=torch.get_default_dtype(),
129
+ )
130
+ self.max_seq_len_cached = None
131
+
132
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
133
+ self.max_seq_len_cached = seq_len
134
+ t = torch.arange(
135
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
136
+ )
137
+
138
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
139
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
140
+ emb = torch.cat((freqs, freqs), dim=-1)
141
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
142
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
143
+
144
+ def forward(self, x, seq_len=None):
145
+ # x: [bs, num_attention_heads, seq_len, head_size]
146
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
147
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
148
+
149
+ return (
150
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
151
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
152
+ )
153
+
154
+
155
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV3
156
+ class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
157
+ """DeepseekV3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
158
+
159
+ def __init__(
160
+ self,
161
+ dim,
162
+ max_position_embeddings=2048,
163
+ base=10000,
164
+ device=None,
165
+ scaling_factor=1.0,
166
+ ):
167
+ self.scaling_factor = scaling_factor
168
+ super().__init__(dim, max_position_embeddings, base, device)
169
+
170
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
171
+ self.max_seq_len_cached = seq_len
172
+ t = torch.arange(
173
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
174
+ )
175
+ t = t / self.scaling_factor
176
+
177
+ freqs = torch.outer(t, self.inv_freq)
178
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
179
+ emb = torch.cat((freqs, freqs), dim=-1)
180
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
181
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
182
+
183
+
184
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV3
185
+ class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
186
+ """DeepseekV3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
187
+
188
+ def __init__(
189
+ self,
190
+ dim,
191
+ max_position_embeddings=2048,
192
+ base=10000,
193
+ device=None,
194
+ scaling_factor=1.0,
195
+ ):
196
+ self.scaling_factor = scaling_factor
197
+ super().__init__(dim, max_position_embeddings, base, device)
198
+
199
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
200
+ self.max_seq_len_cached = seq_len
201
+
202
+ if seq_len > self.max_position_embeddings:
203
+ base = self.base * (
204
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
205
+ - (self.scaling_factor - 1)
206
+ ) ** (self.dim / (self.dim - 2))
207
+ inv_freq = 1.0 / (
208
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
209
+ )
210
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
211
+
212
+ t = torch.arange(
213
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
214
+ )
215
+
216
+ freqs = torch.outer(t, self.inv_freq)
217
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
218
+ emb = torch.cat((freqs, freqs), dim=-1)
219
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
220
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
221
+
222
+
223
+ # Inverse dim formula to find dim based on number of rotations
224
+ def yarn_find_correction_dim(
225
+ num_rotations, dim, base=10000, max_position_embeddings=2048
226
+ ):
227
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
228
+ 2 * math.log(base)
229
+ )
230
+
231
+
232
+ # Find dim range bounds based on rotations
233
+ def yarn_find_correction_range(
234
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
235
+ ):
236
+ low = math.floor(
237
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
238
+ )
239
+ high = math.ceil(
240
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
241
+ )
242
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
243
+
244
+
245
+ def yarn_get_mscale(scale=1, mscale=1):
246
+ if scale <= 1:
247
+ return 1.0
248
+ return 0.1 * mscale * math.log(scale) + 1.0
249
+
250
+
251
+ def yarn_linear_ramp_mask(min, max, dim):
252
+ if min == max:
253
+ max += 0.001 # Prevent singularity
254
+
255
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
256
+ ramp_func = torch.clamp(linear_func, 0, 1)
257
+ return ramp_func
258
+
259
+
260
+ class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding):
261
+
262
+ def __init__(
263
+ self,
264
+ dim,
265
+ max_position_embeddings=2048,
266
+ base=10000,
267
+ device=None,
268
+ scaling_factor=1.0,
269
+ original_max_position_embeddings=4096,
270
+ beta_fast=32,
271
+ beta_slow=1,
272
+ mscale=1,
273
+ mscale_all_dim=0,
274
+ ):
275
+ self.scaling_factor = scaling_factor
276
+ self.original_max_position_embeddings = original_max_position_embeddings
277
+ self.beta_fast = beta_fast
278
+ self.beta_slow = beta_slow
279
+ self.mscale = mscale
280
+ self.mscale_all_dim = mscale_all_dim
281
+ super().__init__(dim, max_position_embeddings, base, device)
282
+
283
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
284
+ self.max_seq_len_cached = seq_len
285
+ dim = self.dim
286
+
287
+ freq_extra = 1.0 / (
288
+ self.base
289
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
290
+ )
291
+ freq_inter = 1.0 / (
292
+ self.scaling_factor
293
+ * self.base
294
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
295
+ )
296
+
297
+ low, high = yarn_find_correction_range(
298
+ self.beta_fast,
299
+ self.beta_slow,
300
+ dim,
301
+ self.base,
302
+ self.original_max_position_embeddings,
303
+ )
304
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
305
+ device=device, dtype=torch.float32
306
+ )
307
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
308
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
309
+
310
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
311
+
312
+ freqs = torch.outer(t, inv_freq)
313
+
314
+ _mscale = float(
315
+ yarn_get_mscale(self.scaling_factor, self.mscale)
316
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
317
+ )
318
+
319
+ emb = torch.cat((freqs, freqs), dim=-1)
320
+ self.register_buffer(
321
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
322
+ )
323
+ self.register_buffer(
324
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
325
+ )
326
+
327
+
328
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
329
+ def rotate_half(x):
330
+ """Rotates half the hidden dims of the input."""
331
+ x1 = x[..., : x.shape[-1] // 2]
332
+ x2 = x[..., x.shape[-1] // 2 :]
333
+ return torch.cat((-x2, x1), dim=-1)
334
+
335
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
336
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
337
+ """Applies Rotary Position Embedding to the query and key tensors.
338
+
339
+ Args:
340
+ q (`torch.Tensor`): The query tensor.
341
+ k (`torch.Tensor`): The key tensor.
342
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
343
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
344
+ position_ids (`torch.Tensor`):
345
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
346
+ used to pass offsetted position ids when working with a KV-cache.
347
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
348
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
349
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
350
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
351
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
352
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
353
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
354
+ Returns:
355
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
356
+ """
357
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
358
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
359
+
360
+ b, h, s, d = q.shape
361
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
362
+
363
+ b, h, s, d = k.shape
364
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
365
+
366
+ q_embed = (q * cos) + (rotate_half(q) * sin)
367
+ k_embed = (k * cos) + (rotate_half(k) * sin)
368
+ return q_embed, k_embed
369
+
370
+
371
+ class DeepseekV3MLP(nn.Module):
372
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
373
+ super().__init__()
374
+ self.config = config
375
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
376
+ self.intermediate_size = (
377
+ config.intermediate_size if intermediate_size is None else intermediate_size
378
+ )
379
+
380
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
381
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
382
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
383
+ self.act_fn = ACT2FN[config.hidden_act]
384
+
385
+ def forward(self, x):
386
+ x_dtype = x.dtype
387
+ x_dtype_min = torch.finfo(x_dtype).min
388
+ x_dtype_max = torch.finfo(x_dtype).max
389
+ intermetiate = self.act_fn(self.gate_proj(x)) * self.up_proj(x)
390
+ intermetiate = intermetiate.clip(x_dtype_min, x_dtype_max)
391
+ down_proj = self.down_proj(intermetiate)
392
+ down_proj = down_proj.clip(x_dtype_min, x_dtype_max)
393
+ return down_proj
394
+
395
+ class FusedLinear(nn.Module):
396
+ def __init__(self, in_features, out_features, rank=8, n_fused=4, bias=False, **kwargs):
397
+ super().__init__()
398
+
399
+ self.in_features = in_features
400
+ self.out_features = out_features
401
+ self.rank = rank
402
+ self.n_fused = n_fused
403
+
404
+ # Linear layer
405
+ self.fused_layer = nn.Linear(in_features, out_features, bias=bias)
406
+
407
+ # Adapter weights
408
+ self.qa_weights = nn.Parameter(torch.randn(n_fused, rank, in_features) * 0.02)
409
+ self.qb_weights = nn.Parameter(torch.randn(n_fused, out_features, rank) * 0.02)
410
+
411
+ # Scaling factor
412
+ self.scaling_factor = nn.Parameter(torch.ones(n_fused, out_features))
413
+
414
+ # Flag to check if scaling factor has been computed
415
+ self.scaling_factor_computed = [False] * n_fused
416
+
417
+ def forward(self, x, top_k_weights):
418
+ # Linear transformation
419
+ output = self.fused_layer(x)
420
+
421
+ # Adapter mechanism
422
+ if torch.all(torch.abs(top_k_weights) < 1e-6):
423
+ return output
424
+
425
+ adapter_output = torch.zeros_like(output)
426
+ batch_size = x.shape[0]
427
+
428
+
429
+ if len(x.shape) == 2: # for some reasons there are errors here
430
+ for i in range(self.n_fused):
431
+ # Find batch items where this adapter is active
432
+ active_mask = torch.abs(top_k_weights[:, i]) > 1e-6
433
+ active_count = active_mask.sum().item()
434
+
435
+ if active_count > 0:
436
+ # Only process if there are any active items for this adapter
437
+ active_indices = torch.nonzero(active_mask).squeeze(-1)
438
+ active_x = x[active_indices]
439
+ active_weights = top_k_weights[active_indices, i:i+1]
440
+
441
+ # Compute adapter output for active batch items
442
+ intermediate = F.linear(active_x, self.qa_weights[i])
443
+ active_output = F.linear(intermediate, self.qb_weights[i])
444
+
445
+ active_output = active_output * active_weights
446
+
447
+ # Add to the corresponding positions in adapter_output
448
+ adapter_output[active_indices] = adapter_output[active_indices] + 0.1 * active_output * self.scaling_factor[i][None]
449
+
450
+ return output + adapter_output
451
+
452
+ class FusedMLP(torch.nn.Module):
453
+ def __init__(self, config, hidden_size=None, intermediate_size=None, n_fused=4, rank=8, adapter_type='mixture'):
454
+ super().__init__()
455
+ self.config = config
456
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
457
+ self.intermediate_size = (
458
+ config.moe_intermediate_size if intermediate_size is None else intermediate_size
459
+ )
460
+ self.n_fused=n_fused
461
+ self.gate_proj = FusedLinear(self.hidden_size, self.intermediate_size, bias=False, rank=rank, n_fused=n_fused, adapter_type=adapter_type)
462
+ self.up_proj = FusedLinear(self.hidden_size, self.intermediate_size, bias=False, rank=rank, n_fused=n_fused, adapter_type=adapter_type)
463
+ self.down_proj = FusedLinear(self.intermediate_size, self.hidden_size, bias=False, rank=rank, n_fused=n_fused, adapter_type=adapter_type)
464
+ self.mask_up_proj = torch.nn.Linear(self.n_fused, self.hidden_size, bias=False)
465
+ self.act_fn = ACT2FN[config.hidden_act]
466
+ self.adapter_type=adapter_type
467
+
468
+ def forward(self, x, top_k_weights):
469
+ x = x + self.mask_up_proj(top_k_weights)
470
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x, top_k_weights)) * self.up_proj(x, top_k_weights), top_k_weights)
471
+ return down_proj
472
+
473
+ class MoEGate(nn.Module):
474
+ def __init__(self, config):
475
+ super().__init__()
476
+ self.config = config
477
+ self.top_k = config.num_experts_per_tok
478
+ self.n_routed_experts = config.n_routed_experts
479
+ self.routed_scaling_factor = config.routed_scaling_factor
480
+ self.scoring_func = config.scoring_func
481
+ self.seq_aux = config.seq_aux
482
+ self.topk_method = config.topk_method
483
+ self.n_group = config.n_group
484
+ self.topk_group = config.topk_group
485
+
486
+ # topk selection algorithm
487
+ self.norm_topk_prob = config.norm_topk_prob
488
+ self.gating_dim = config.hidden_size
489
+ self.weight = nn.Parameter(
490
+ torch.empty((self.n_routed_experts, self.gating_dim))
491
+ )
492
+ if self.topk_method == "noaux_tc":
493
+ self.e_score_correction_bias = nn.Parameter(
494
+ torch.empty((self.n_routed_experts))
495
+ )
496
+ self.reset_parameters()
497
+
498
+ def reset_parameters(self) -> None:
499
+ import torch.nn.init as init
500
+
501
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
502
+
503
+ def forward(self, hidden_states):
504
+ bsz, seq_len, h = hidden_states.shape
505
+ ### compute gating score
506
+ hidden_states = hidden_states.view(-1, h)
507
+ logits = F.linear(
508
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
509
+ )
510
+ if self.scoring_func == "sigmoid":
511
+ scores = logits.sigmoid()
512
+ else:
513
+ raise NotImplementedError(
514
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
515
+ )
516
+
517
+ ### select top-k experts
518
+ if self.topk_method == "noaux_tc":
519
+ if self.training:
520
+ topk_weight, topk_idx = torch.topk(
521
+ scores, k=self.top_k, dim=-1, sorted=False
522
+ )
523
+ else:
524
+ assert not self.training
525
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
526
+ group_scores = (
527
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
528
+ ) # [n, n_group]
529
+ group_idx = torch.topk(
530
+ group_scores, k=self.topk_group, dim=-1, sorted=False
531
+ )[
532
+ 1
533
+ ] # [n, top_k_group]
534
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
535
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
536
+ score_mask = (
537
+ group_mask.unsqueeze(-1)
538
+ .expand(
539
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
540
+ )
541
+ .reshape(bsz * seq_len, -1)
542
+ ) # [n, e]
543
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
544
+ _, topk_idx = torch.topk(
545
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
546
+ )
547
+ topk_weight = scores.gather(1, topk_idx)
548
+ else:
549
+ raise NotImplementedError(
550
+ f"insupportable TopK function for MoE gating: {self.topk_method}"
551
+ )
552
+
553
+ ### norm gate to sum 1
554
+ if self.top_k > 1 and self.norm_topk_prob:
555
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
556
+ topk_weight = topk_weight / denominator
557
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
558
+
559
+ return topk_idx, topk_weight
560
+
561
+ class FusedMOE(torch.nn.Module):
562
+ def __init__(self, config):
563
+ super().__init__()
564
+ self.config = config
565
+ self.num_experts_per_tok = config.num_experts_per_tok
566
+
567
+ if hasattr(config, "ep_size") and config.ep_size > 1:
568
+ assert config.ep_size == dist.get_world_size()
569
+ self.ep_size = config.ep_size
570
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
571
+ self.ep_rank = dist.get_rank()
572
+ self.experts = nn.ModuleList(
573
+ [
574
+ (
575
+ FusedMLP(
576
+ config,
577
+ intermediate_size=config.moe_intermediate_size,
578
+ n_fused=config.n_routed_experts // config.n_fused_experts,
579
+ rank=config.fused_expert_dora_rank,
580
+ adapter_type=config.fused_expert_method
581
+ )
582
+ if i >= self.ep_rank * self.experts_per_rank
583
+ and i < (self.ep_rank + 1) * self.experts_per_rank
584
+ else None
585
+ )
586
+ for i in range(config.n_fused_experts)
587
+ ]
588
+ )
589
+ else:
590
+ self.ep_size = 1
591
+ self.experts_per_rank = config.n_routed_experts
592
+ self.ep_rank = 0
593
+ self.experts = nn.ModuleList(
594
+ [
595
+ FusedMLP(
596
+ config,
597
+ intermediate_size=config.moe_intermediate_size,
598
+ n_fused=config.n_routed_experts // config.n_fused_experts,
599
+ rank=config.fused_expert_dora_rank,
600
+ adapter_type=config.fused_expert_method
601
+ )
602
+ for i in range(config.n_fused_experts)
603
+ ]
604
+ )
605
+ self.gate = MoEGate(config)
606
+ if config.n_shared_experts is not None:
607
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
608
+ self.shared_experts = DeepseekV3MLP(
609
+ config=config, intermediate_size=intermediate_size
610
+ )
611
+
612
+ # Register inv_mapping_dict as a buffer
613
+ self.register_buffer('inv_mapping_dict', torch.zeros(config.n_fused_experts, config.n_routed_experts // config.n_fused_experts), persistent=True)
614
+
615
+
616
+ def set_ready(self):
617
+ self.experts.to_empty(device="meta")
618
+ del self.experts
619
+ self.ready = True
620
+
621
+ def forward(self, hidden_states):
622
+ identity, orig_shape, hidden_states, topk_idx, topk_weight, aux_loss = self.forward_gate(hidden_states)
623
+
624
+ y = torch.zeros_like(hidden_states, device=hidden_states.device, dtype=hidden_states.dtype)
625
+
626
+ for idx in range(self.inv_mapping_dict.size(0)):
627
+ y += self.forward_fused_expert(idx, hidden_states, topk_idx, topk_weight)
628
+
629
+ y = y.view(*orig_shape)
630
+
631
+ if self.config.n_shared_experts is not None:
632
+ y = y + self.shared_experts(identity)
633
+ return y
634
+
635
+ def forward_gate(self, hidden_states):
636
+ identity = hidden_states
637
+ orig_shape = hidden_states.shape
638
+
639
+ gate_output = self.gate(hidden_states)
640
+ if len(gate_output) == 2:
641
+ topk_idx, topk_weight=gate_output
642
+ aux_loss=None
643
+ else:
644
+ topk_idx, topk_weight, aux_loss=gate_output
645
+
646
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
647
+
648
+ return identity, orig_shape, hidden_states, topk_idx, topk_weight, aux_loss
649
+
650
+ def forward_fused_expert(self, idx, hidden_states, topk_idx, topk_weight):
651
+ indexes = self.inv_mapping_dict[idx].tolist()
652
+
653
+ flat_topk_weight = torch.zeros((hidden_states.shape[0], len(indexes)), device=hidden_states.device, dtype=hidden_states.dtype)
654
+
655
+ for i, index in enumerate(indexes):
656
+ flat_topk_weight[:, i] = torch.sum(topk_weight * (topk_idx == index), axis=-1)
657
+
658
+ scalar = torch.sum(flat_topk_weight, axis=-1, keepdim=True) # keeping the total weight of the experts
659
+
660
+ flat_topk_weight[flat_topk_weight == 0] = -1e9
661
+ flat_topk_weight = torch.softmax(flat_topk_weight, dim=-1)
662
+
663
+ output = torch.zeros_like(hidden_states, device=hidden_states.device, dtype=hidden_states.dtype)
664
+
665
+ output[scalar.squeeze() != 0] = self.experts[idx](hidden_states[scalar.squeeze() != 0], flat_topk_weight[scalar.squeeze() != 0]) # Process only if at least one weight is required, should be much faster
666
+
667
+ return scalar * output # Weighting is already taken into account by how the Fused is trained
668
+
669
+ class DeepseekV3MoE(nn.Module):
670
+ """
671
+ A mixed expert module containing shared experts.
672
+ """
673
+
674
+ def __init__(self, config):
675
+ super().__init__()
676
+ self.config = config
677
+ self.num_experts_per_tok = config.num_experts_per_tok
678
+
679
+ if hasattr(config, "ep_size") and config.ep_size > 1:
680
+ assert config.ep_size == dist.get_world_size()
681
+ self.ep_size = config.ep_size
682
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
683
+ self.ep_rank = dist.get_rank()
684
+ self.experts = nn.ModuleList(
685
+ [
686
+ (
687
+ DeepseekV3MLP(
688
+ config, intermediate_size=config.moe_intermediate_size
689
+ )
690
+ if i >= self.ep_rank * self.experts_per_rank
691
+ and i < (self.ep_rank + 1) * self.experts_per_rank
692
+ else None
693
+ )
694
+ for i in range(config.n_routed_experts)
695
+ ]
696
+ )
697
+ else:
698
+ self.ep_size = 1
699
+ self.experts_per_rank = config.n_routed_experts
700
+ self.ep_rank = 0
701
+ self.experts = nn.ModuleList(
702
+ [
703
+ DeepseekV3MLP(
704
+ config, intermediate_size=config.moe_intermediate_size
705
+ )
706
+ for i in range(config.n_routed_experts)
707
+ ]
708
+ )
709
+ self.gate = MoEGate(config)
710
+ if config.n_shared_experts is not None:
711
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
712
+ self.shared_experts = DeepseekV3MLP(
713
+ config=config, intermediate_size=intermediate_size
714
+ )
715
+
716
+ def forward(self, hidden_states):
717
+ identity = hidden_states
718
+ orig_shape = hidden_states.shape
719
+ topk_idx, topk_weight = self.gate(hidden_states)
720
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
721
+ flat_topk_idx = topk_idx.view(-1)
722
+ if not self.training:
723
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
724
+ else:
725
+ hidden_states = hidden_states.repeat_interleave(
726
+ self.num_experts_per_tok, dim=0
727
+ )
728
+
729
+ y = torch.empty_like(hidden_states)
730
+ for i, expert in enumerate(self.experts):
731
+ expert_output=expert(hidden_states[flat_topk_idx == i])
732
+ try:
733
+ y[flat_topk_idx == i] = expert_output.to(y.dtype)
734
+ except:
735
+ pass
736
+
737
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
738
+ y = y.view(*orig_shape)
739
+
740
+ if self.config.n_shared_experts is not None:
741
+ y = y + self.shared_experts(identity)
742
+ y = y.clip(torch.finfo(y.dtype).min, torch.finfo(y.dtype).max)
743
+ return y
744
+
745
+ @torch.no_grad()
746
+ def moe_infer(self, x, topk_ids, topk_weight):
747
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
748
+ cnts.scatter_(1, topk_ids, 1)
749
+ tokens_per_expert = cnts.sum(dim=0)
750
+ idxs = topk_ids.view(-1).argsort()
751
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
752
+ sorted_tokens_shape = sorted_tokens.shape
753
+ if self.ep_size > 1:
754
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
755
+ tokens_per_expert_group = tokens_per_expert.new_empty(
756
+ tokens_per_expert.shape[0]
757
+ )
758
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
759
+ output_splits = (
760
+ tokens_per_expert_group.view(self.ep_size, -1)
761
+ .sum(1)
762
+ .cpu()
763
+ .numpy()
764
+ .tolist()
765
+ )
766
+ gathered_tokens = sorted_tokens.new_empty(
767
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
768
+ )
769
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
770
+ dist.all_to_all(
771
+ list(gathered_tokens.split(output_splits)),
772
+ list(sorted_tokens.split(input_split_sizes)),
773
+ )
774
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
775
+ self.ep_size, self.experts_per_rank
776
+ ).sum(dim=0)
777
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
778
+ s = 0
779
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
780
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
781
+ s += k
782
+ gatherd_idxs = gatherd_idxs.argsort()
783
+ sorted_tokens = gathered_tokens[gatherd_idxs]
784
+ tokens_per_expert = tokens_per_expert_post_gather
785
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
786
+
787
+ outputs = []
788
+ start_idx = 0
789
+ for i, num_tokens in enumerate(tokens_per_expert):
790
+ end_idx = start_idx + num_tokens
791
+ if num_tokens == 0:
792
+ continue
793
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
794
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
795
+ expert_out = expert(tokens_for_this_expert)
796
+ outputs.append(expert_out)
797
+ start_idx = end_idx
798
+
799
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
800
+ if self.ep_size > 1:
801
+ new_x = torch.empty_like(outs)
802
+ new_x[gatherd_idxs] = outs
803
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
804
+ dist.all_to_all(
805
+ list(gathered_tokens.split(input_split_sizes)),
806
+ list(new_x.split(output_splits)),
807
+ )
808
+ outs = gathered_tokens
809
+
810
+ new_x = torch.empty_like(outs)
811
+ new_x[idxs] = outs
812
+ final_out = (
813
+ new_x.view(*topk_ids.shape, -1)
814
+ .type(topk_weight.dtype)
815
+ .mul_(topk_weight.unsqueeze(dim=-1))
816
+ .sum(dim=1)
817
+ .type(new_x.dtype)
818
+ )
819
+ return final_out
820
+
821
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
822
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
823
+ """
824
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
825
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
826
+ """
827
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
828
+ if n_rep == 1:
829
+ return hidden_states
830
+ hidden_states = hidden_states[:, :, None, :, :].expand(
831
+ batch, num_key_value_heads, n_rep, slen, head_dim
832
+ )
833
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
834
+
835
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV3
836
+ class DeepseekV3Attention(nn.Module):
837
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
838
+
839
+ def __init__(self, config: DeepseekV3Config, layer_idx: Optional[int] = None):
840
+ super().__init__()
841
+ self.config = config
842
+ self.layer_idx = layer_idx
843
+ if layer_idx is None:
844
+ logger.warning_once(
845
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
846
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
847
+ "when creating this class."
848
+ )
849
+
850
+ self.attention_dropout = config.attention_dropout
851
+ self.hidden_size = config.hidden_size
852
+ self.num_heads = config.num_attention_heads
853
+
854
+ self.max_position_embeddings = config.max_position_embeddings
855
+ self.rope_theta = config.rope_theta
856
+ self.q_lora_rank = config.q_lora_rank
857
+ self.qk_rope_head_dim = config.qk_rope_head_dim
858
+ self.kv_lora_rank = config.kv_lora_rank
859
+ self.v_head_dim = config.v_head_dim
860
+ self.qk_nope_head_dim = config.qk_nope_head_dim
861
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
862
+
863
+ self.is_causal = True
864
+
865
+ if self.q_lora_rank is None:
866
+ self.q_proj = nn.Linear(
867
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
868
+ )
869
+ else:
870
+ self.q_a_proj = nn.Linear(
871
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
872
+ )
873
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
874
+ self.q_b_proj = nn.Linear(
875
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
876
+ )
877
+
878
+ self.kv_a_proj_with_mqa = nn.Linear(
879
+ self.hidden_size,
880
+ config.kv_lora_rank + config.qk_rope_head_dim,
881
+ bias=config.attention_bias,
882
+ )
883
+ self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank)
884
+ self.kv_b_proj = nn.Linear(
885
+ config.kv_lora_rank,
886
+ self.num_heads
887
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
888
+ bias=False,
889
+ )
890
+
891
+ self.o_proj = nn.Linear(
892
+ self.num_heads * self.v_head_dim,
893
+ self.hidden_size,
894
+ bias=config.attention_bias,
895
+ )
896
+ self._init_rope()
897
+
898
+ self.softmax_scale = self.q_head_dim ** (-0.5)
899
+ if self.config.rope_scaling is not None:
900
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
901
+ scaling_factor = self.config.rope_scaling["factor"]
902
+ if mscale_all_dim:
903
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
904
+ self.softmax_scale = self.softmax_scale * mscale * mscale
905
+
906
+ def _init_rope(self):
907
+ if self.config.rope_scaling is None:
908
+ self.rotary_emb = DeepseekV3RotaryEmbedding(
909
+ self.qk_rope_head_dim,
910
+ max_position_embeddings=self.max_position_embeddings,
911
+ base=self.rope_theta,
912
+ )
913
+ else:
914
+ scaling_type = self.config.rope_scaling["type"]
915
+ scaling_factor = self.config.rope_scaling["factor"]
916
+ if scaling_type == "linear":
917
+ self.rotary_emb = DeepseekV3LinearScalingRotaryEmbedding(
918
+ self.qk_rope_head_dim,
919
+ max_position_embeddings=self.max_position_embeddings,
920
+ scaling_factor=scaling_factor,
921
+ base=self.rope_theta,
922
+ )
923
+ elif scaling_type == "dynamic":
924
+ self.rotary_emb = DeepseekV3DynamicNTKScalingRotaryEmbedding(
925
+ self.qk_rope_head_dim,
926
+ max_position_embeddings=self.max_position_embeddings,
927
+ scaling_factor=scaling_factor,
928
+ base=self.rope_theta,
929
+ )
930
+ elif scaling_type == "yarn":
931
+ kwargs = {
932
+ key: self.config.rope_scaling[key]
933
+ for key in [
934
+ "original_max_position_embeddings",
935
+ "beta_fast",
936
+ "beta_slow",
937
+ "mscale",
938
+ "mscale_all_dim",
939
+ ]
940
+ if key in self.config.rope_scaling
941
+ }
942
+ self.rotary_emb = DeepseekV3YarnRotaryEmbedding(
943
+ self.qk_rope_head_dim,
944
+ max_position_embeddings=self.max_position_embeddings,
945
+ scaling_factor=scaling_factor,
946
+ base=self.rope_theta,
947
+ **kwargs,
948
+ )
949
+ else:
950
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
951
+
952
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
953
+ return (
954
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
955
+ .transpose(1, 2)
956
+ .contiguous()
957
+ )
958
+
959
+ def forward(
960
+ self,
961
+ hidden_states: torch.Tensor,
962
+ attention_mask: Optional[torch.Tensor] = None,
963
+ position_ids: Optional[torch.LongTensor] = None,
964
+ past_key_value: Optional[Cache] = None,
965
+ output_attentions: bool = False,
966
+ use_cache: bool = False,
967
+ **kwargs,
968
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
969
+ if "padding_mask" in kwargs:
970
+ warnings.warn(
971
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
972
+ )
973
+ bsz, q_len, _ = hidden_states.size()
974
+
975
+ if self.q_lora_rank is None:
976
+ q = self.q_proj(hidden_states)
977
+ else:
978
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
979
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
980
+ q_nope, q_pe = torch.split(
981
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
982
+ )
983
+
984
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
985
+ compressed_kv, k_pe = torch.split(
986
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
987
+ )
988
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
989
+ kv = (
990
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
991
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
992
+ .transpose(1, 2)
993
+ )
994
+
995
+ k_nope, value_states = torch.split(
996
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
997
+ )
998
+ kv_seq_len = value_states.shape[-2]
999
+ if past_key_value is not None:
1000
+ if self.layer_idx is None:
1001
+ raise ValueError(
1002
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
1003
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
1004
+ "with a layer index."
1005
+ )
1006
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1007
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1008
+
1009
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1010
+
1011
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1012
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1013
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1014
+
1015
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1016
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1017
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1018
+ if past_key_value is not None:
1019
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1020
+ key_states, value_states = past_key_value.update(
1021
+ key_states, value_states, self.layer_idx, cache_kwargs
1022
+ )
1023
+
1024
+ attn_weights = (
1025
+ torch.matmul(query_states * self.softmax_scale, key_states.transpose(2, 3))
1026
+ )
1027
+
1028
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
1029
+ raise ValueError(
1030
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
1031
+ f" {attn_weights.size()}"
1032
+ )
1033
+ assert attention_mask is not None
1034
+ if attention_mask is not None:
1035
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1036
+ raise ValueError(
1037
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1038
+ )
1039
+ attn_weights = attn_weights + attention_mask
1040
+
1041
+ # upcast attention to fp32
1042
+ attn_weights = attn_weights.clip(torch.finfo(attn_weights.dtype).min, torch.finfo(attn_weights.dtype).max)
1043
+ attn_weights = nn.functional.softmax(
1044
+ attn_weights, dim=-1, dtype=torch.float32
1045
+ ).to(query_states.dtype)
1046
+ attn_weights = nn.functional.dropout(
1047
+ attn_weights, p=self.attention_dropout, training=self.training
1048
+ )
1049
+ attn_output = torch.matmul(attn_weights, value_states)
1050
+
1051
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
1052
+ raise ValueError(
1053
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
1054
+ f" {attn_output.size()}"
1055
+ )
1056
+
1057
+ attn_output = attn_output.transpose(1, 2).contiguous()
1058
+
1059
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
1060
+
1061
+ attn_output = self.o_proj(attn_output)
1062
+
1063
+ if not output_attentions:
1064
+ attn_weights = None
1065
+
1066
+ return attn_output, attn_weights, past_key_value
1067
+
1068
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV3
1069
+ class DeepseekV3FlashAttention2(DeepseekV3Attention):
1070
+ """
1071
+ DeepseekV3 flash attention module. This module inherits from `DeepseekV3Attention` as the weights of the module stays
1072
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
1073
+ flash attention and deal with padding tokens in case the input contains any of them.
1074
+ """
1075
+
1076
+ def __init__(self, *args, **kwargs):
1077
+ super().__init__(*args, **kwargs)
1078
+
1079
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1080
+ # 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.
1081
+ # 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).
1082
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1083
+
1084
+ def forward(
1085
+ self,
1086
+ hidden_states: torch.Tensor,
1087
+ attention_mask: Optional[torch.LongTensor] = None,
1088
+ position_ids: Optional[torch.LongTensor] = None,
1089
+ past_key_value: Optional[Cache] = None,
1090
+ output_attentions: bool = False,
1091
+ use_cache: bool = False,
1092
+ **kwargs,
1093
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1094
+ # DeepseekV3FlashAttention2 attention does not support output_attentions
1095
+ if "padding_mask" in kwargs:
1096
+ warnings.warn(
1097
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1098
+ )
1099
+
1100
+ # overwrite attention_mask with padding_mask
1101
+ attention_mask = kwargs.pop("padding_mask")
1102
+
1103
+ output_attentions = False
1104
+
1105
+ bsz, q_len, _ = hidden_states.size()
1106
+
1107
+ if self.q_lora_rank is None:
1108
+ q = self.q_proj(hidden_states)
1109
+ else:
1110
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1111
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1112
+ q_nope, q_pe = torch.split(
1113
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1114
+ )
1115
+
1116
+ # Flash attention requires the input to have the shape
1117
+ # batch_size x seq_length x head_dim x hidden_dim
1118
+ # therefore we just need to keep the original shape
1119
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1120
+ compressed_kv, k_pe = torch.split(
1121
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1122
+ )
1123
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1124
+ kv = (
1125
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1126
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1127
+ .transpose(1, 2)
1128
+ )
1129
+
1130
+ k_nope, value_states = torch.split(
1131
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1132
+ )
1133
+ kv_seq_len = value_states.shape[-2]
1134
+
1135
+ kv_seq_len = value_states.shape[-2]
1136
+ if past_key_value is not None:
1137
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1138
+
1139
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1140
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1141
+
1142
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1143
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1144
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1145
+
1146
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1147
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1148
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1149
+
1150
+ if self.q_head_dim != self.v_head_dim:
1151
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1152
+
1153
+ if past_key_value is not None:
1154
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1155
+ key_states, value_states = past_key_value.update(
1156
+ key_states, value_states, self.layer_idx, cache_kwargs
1157
+ )
1158
+
1159
+ # 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
1160
+ # to be able to avoid many of these transpose/reshape/view.
1161
+ query_states = query_states.transpose(1, 2)
1162
+ key_states = key_states.transpose(1, 2)
1163
+ value_states = value_states.transpose(1, 2)
1164
+
1165
+ dropout_rate = self.attention_dropout if self.training else 0.0
1166
+
1167
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1168
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1169
+ # cast them back in the correct dtype just to be sure everything works as expected.
1170
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1171
+ # in fp32. (DeepseekV3RMSNorm handles it correctly)
1172
+
1173
+ input_dtype = query_states.dtype
1174
+ if input_dtype == torch.float32:
1175
+ # Handle the case where the model is quantized
1176
+ if hasattr(self.config, "_pre_quantization_dtype"):
1177
+ target_dtype = self.config._pre_quantization_dtype
1178
+ elif torch.is_autocast_enabled():
1179
+ target_dtype = torch.get_autocast_gpu_dtype()
1180
+ else:
1181
+ target_dtype = (
1182
+ self.q_proj.weight.dtype
1183
+ if self.q_lora_rank is None
1184
+ else self.q_a_proj.weight.dtype
1185
+ )
1186
+
1187
+ logger.warning_once(
1188
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1189
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1190
+ f" {target_dtype}."
1191
+ )
1192
+
1193
+ query_states = query_states.to(target_dtype)
1194
+ key_states = key_states.to(target_dtype)
1195
+ value_states = value_states.to(target_dtype)
1196
+
1197
+ attn_output = self._flash_attention_forward(
1198
+ query_states,
1199
+ key_states,
1200
+ value_states,
1201
+ attention_mask,
1202
+ q_len,
1203
+ dropout=dropout_rate,
1204
+ softmax_scale=self.softmax_scale,
1205
+ )
1206
+ if self.q_head_dim != self.v_head_dim:
1207
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1208
+
1209
+ attn_output = attn_output.reshape(
1210
+ bsz, q_len, self.num_heads * self.v_head_dim
1211
+ ).contiguous()
1212
+ attn_output = self.o_proj(attn_output)
1213
+
1214
+ if not output_attentions:
1215
+ attn_weights = None
1216
+
1217
+ return attn_output, attn_weights, past_key_value
1218
+
1219
+ def _flash_attention_forward(
1220
+ self,
1221
+ query_states,
1222
+ key_states,
1223
+ value_states,
1224
+ attention_mask,
1225
+ query_length,
1226
+ dropout=0.0,
1227
+ softmax_scale=None,
1228
+ ):
1229
+ """
1230
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1231
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1232
+
1233
+ Args:
1234
+ query_states (`torch.Tensor`):
1235
+ Input query states to be passed to Flash Attention API
1236
+ key_states (`torch.Tensor`):
1237
+ Input key states to be passed to Flash Attention API
1238
+ value_states (`torch.Tensor`):
1239
+ Input value states to be passed to Flash Attention API
1240
+ attention_mask (`torch.Tensor`):
1241
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1242
+ position of padding tokens and 1 for the position of non-padding tokens.
1243
+ dropout (`int`, *optional*):
1244
+ Attention dropout
1245
+ softmax_scale (`float`, *optional*):
1246
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1247
+ """
1248
+ if not self._flash_attn_uses_top_left_mask:
1249
+ causal = self.is_causal
1250
+ else:
1251
+ # 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__.
1252
+ causal = self.is_causal and query_length != 1
1253
+
1254
+ # Contains at least one padding token in the sequence
1255
+ if attention_mask is not None:
1256
+ batch_size = query_states.shape[0]
1257
+ (
1258
+ query_states,
1259
+ key_states,
1260
+ value_states,
1261
+ indices_q,
1262
+ cu_seq_lens,
1263
+ max_seq_lens,
1264
+ ) = self._upad_input(
1265
+ query_states, key_states, value_states, attention_mask, query_length
1266
+ )
1267
+
1268
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1269
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1270
+
1271
+ attn_output_unpad = flash_attn_varlen_func(
1272
+ query_states,
1273
+ key_states,
1274
+ value_states,
1275
+ cu_seqlens_q=cu_seqlens_q,
1276
+ cu_seqlens_k=cu_seqlens_k,
1277
+ max_seqlen_q=max_seqlen_in_batch_q,
1278
+ max_seqlen_k=max_seqlen_in_batch_k,
1279
+ dropout_p=dropout,
1280
+ softmax_scale=softmax_scale,
1281
+ causal=causal,
1282
+ )
1283
+
1284
+ attn_output = pad_input(
1285
+ attn_output_unpad, indices_q, batch_size, query_length
1286
+ )
1287
+ else:
1288
+ attn_output = flash_attn_func(
1289
+ query_states,
1290
+ key_states,
1291
+ value_states,
1292
+ dropout,
1293
+ softmax_scale=softmax_scale,
1294
+ causal=causal,
1295
+ )
1296
+
1297
+ return attn_output
1298
+
1299
+ def _upad_input(
1300
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1301
+ ):
1302
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1303
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1304
+
1305
+ key_layer = index_first_axis(
1306
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1307
+ indices_k,
1308
+ )
1309
+ value_layer = index_first_axis(
1310
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1311
+ indices_k,
1312
+ )
1313
+ if query_length == kv_seq_len:
1314
+ query_layer = index_first_axis(
1315
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1316
+ indices_k,
1317
+ )
1318
+ cu_seqlens_q = cu_seqlens_k
1319
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1320
+ indices_q = indices_k
1321
+ elif query_length == 1:
1322
+ max_seqlen_in_batch_q = 1
1323
+ cu_seqlens_q = torch.arange(
1324
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1325
+ ) # There is a memcpy here, that is very bad.
1326
+ indices_q = cu_seqlens_q[:-1]
1327
+ query_layer = query_layer.squeeze(1)
1328
+ else:
1329
+ # The -q_len: slice assumes left padding.
1330
+ attention_mask = attention_mask[:, -query_length:]
1331
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1332
+ query_layer, attention_mask
1333
+ )
1334
+
1335
+ return (
1336
+ query_layer,
1337
+ key_layer,
1338
+ value_layer,
1339
+ indices_q,
1340
+ (cu_seqlens_q, cu_seqlens_k),
1341
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1342
+ )
1343
+
1344
+ ATTENTION_CLASSES = {
1345
+ "eager": DeepseekV3Attention,
1346
+ "flash_attention_2": DeepseekV3FlashAttention2,
1347
+ }
1348
+
1349
+ class DeepseekV3DecoderLayer(nn.Module):
1350
+ def __init__(self, config: DeepseekV3Config, layer_idx: int):
1351
+ super().__init__()
1352
+ self.hidden_size = config.hidden_size
1353
+
1354
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1355
+ config=config, layer_idx=layer_idx
1356
+ )
1357
+
1358
+ self.mlp = (
1359
+ FusedMOE(config)
1360
+ if (
1361
+ config.n_routed_experts is not None
1362
+ and layer_idx >= config.first_k_dense_replace
1363
+ and layer_idx % config.moe_layer_freq == 0
1364
+ )
1365
+ else DeepseekV3MLP(config)
1366
+ )
1367
+ self.input_layernorm = DeepseekV3RMSNorm(
1368
+ config.hidden_size, eps=config.rms_norm_eps
1369
+ )
1370
+ self.post_attention_layernorm = DeepseekV3RMSNorm(
1371
+ config.hidden_size, eps=config.rms_norm_eps
1372
+ )
1373
+
1374
+ def forward(
1375
+ self,
1376
+ hidden_states: torch.Tensor,
1377
+ attention_mask: Optional[torch.Tensor] = None,
1378
+ position_ids: Optional[torch.LongTensor] = None,
1379
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1380
+ output_attentions: Optional[bool] = False,
1381
+ use_cache: Optional[bool] = False,
1382
+ **kwargs,
1383
+ ) -> Tuple[
1384
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1385
+ ]:
1386
+ """
1387
+ Args:
1388
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1389
+ attention_mask (`torch.FloatTensor`, *optional*):
1390
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1391
+ query_sequence_length, key_sequence_length)` if default attention is used.
1392
+ output_attentions (`bool`, *optional*):
1393
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1394
+ returned tensors for more detail.
1395
+ use_cache (`bool`, *optional*):
1396
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1397
+ (see `past_key_values`).
1398
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1399
+ """
1400
+ if "padding_mask" in kwargs:
1401
+ warnings.warn(
1402
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1403
+ )
1404
+
1405
+
1406
+ residual = hidden_states
1407
+
1408
+ hidden_states = self.input_layernorm(hidden_states)
1409
+
1410
+ # Self Attention
1411
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1412
+ hidden_states=hidden_states,
1413
+ attention_mask=attention_mask,
1414
+ position_ids=position_ids,
1415
+ past_key_value=past_key_value,
1416
+ output_attentions=output_attentions,
1417
+ use_cache=use_cache,
1418
+ **kwargs,
1419
+ )
1420
+ hidden_states = residual + hidden_states
1421
+
1422
+ # Fully Connected
1423
+ residual = hidden_states
1424
+ hidden_states = self.post_attention_layernorm(hidden_states)
1425
+ hidden_states = self.mlp(hidden_states)
1426
+ hidden_states = residual + hidden_states
1427
+ hidden_states = hidden_states.clip(torch.finfo(hidden_states.dtype).min, torch.finfo(hidden_states.dtype).max)
1428
+
1429
+ outputs = (hidden_states,)
1430
+
1431
+ if output_attentions:
1432
+ outputs += (self_attn_weights,)
1433
+
1434
+ if use_cache:
1435
+ outputs += (present_key_value,)
1436
+
1437
+ return outputs
1438
+
1439
+ DeepseekV3_START_DOCSTRING = r"""
1440
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1441
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1442
+ etc.)
1443
+
1444
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1445
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1446
+ and behavior.
1447
+
1448
+ Parameters:
1449
+ config ([`DeepseekV3Config`]):
1450
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1451
+ load the weights associated with the model, only the configuration. Check out the
1452
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1453
+ """
1454
+
1455
+ @add_start_docstrings(
1456
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1457
+ DeepseekV3_START_DOCSTRING,
1458
+ )
1459
+ class DeepseekV3PreTrainedModel(PreTrainedModel):
1460
+ config_class = DeepseekV3Config
1461
+ base_model_prefix = "model"
1462
+ supports_gradient_checkpointing = True
1463
+ _no_split_modules = ["DeepseekV3DecoderLayer"]
1464
+ _skip_keys_device_placement = "past_key_values"
1465
+ _supports_flash_attn_2 = True
1466
+ _supports_cache_class = True
1467
+
1468
+ def _init_weights(self, module):
1469
+ std = self.config.initializer_range
1470
+ if isinstance(module, nn.Linear):
1471
+ module.weight.data.normal_(mean=0.0, std=std)
1472
+ if module.bias is not None:
1473
+ module.bias.data.zero_()
1474
+ elif isinstance(module, nn.Embedding):
1475
+ module.weight.data.normal_(mean=0.0, std=std)
1476
+ if module.padding_idx is not None:
1477
+ module.weight.data[module.padding_idx].zero_()
1478
+
1479
+ DeepseekV3_INPUTS_DOCSTRING = r"""
1480
+ Args:
1481
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1482
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1483
+ it.
1484
+
1485
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1486
+ [`PreTrainedTokenizer.__call__`] for details.
1487
+
1488
+ [What are input IDs?](../glossary#input-ids)
1489
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1490
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1491
+
1492
+ - 1 for tokens that are **not masked**,
1493
+ - 0 for tokens that are **masked**.
1494
+
1495
+ [What are attention masks?](../glossary#attention-mask)
1496
+
1497
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1498
+ [`PreTrainedTokenizer.__call__`] for details.
1499
+
1500
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1501
+ `past_key_values`).
1502
+
1503
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1504
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1505
+ information on the default strategy.
1506
+
1507
+ - 1 indicates the head is **not masked**,
1508
+ - 0 indicates the head is **masked**.
1509
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1510
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1511
+ config.n_positions - 1]`.
1512
+
1513
+ [What are position IDs?](../glossary#position-ids)
1514
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1515
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1516
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1517
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1518
+
1519
+ Two formats are allowed:
1520
+ - a [`~cache_utils.Cache`] instance;
1521
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1522
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1523
+ cache format.
1524
+
1525
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1526
+ legacy cache format will be returned.
1527
+
1528
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1529
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1530
+ of shape `(batch_size, sequence_length)`.
1531
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1532
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1533
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1534
+ model's internal embedding lookup matrix.
1535
+ use_cache (`bool`, *optional*):
1536
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1537
+ `past_key_values`).
1538
+ output_attentions (`bool`, *optional*):
1539
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1540
+ tensors for more detail.
1541
+ output_hidden_states (`bool`, *optional*):
1542
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1543
+ more detail.
1544
+ return_dict (`bool`, *optional*):
1545
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1546
+ """
1547
+
1548
+ @add_start_docstrings(
1549
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1550
+ DeepseekV3_START_DOCSTRING,
1551
+ )
1552
+ class DeepseekV3Model(DeepseekV3PreTrainedModel):
1553
+ """
1554
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`]
1555
+
1556
+ Args:
1557
+ config: DeepseekV3Config
1558
+ """
1559
+
1560
+ def __init__(self, config: DeepseekV3Config):
1561
+ super().__init__(config)
1562
+ self.padding_idx = config.pad_token_id
1563
+ self.vocab_size = config.vocab_size
1564
+
1565
+ self.embed_tokens = nn.Embedding(
1566
+ config.vocab_size, config.hidden_size, self.padding_idx
1567
+ )
1568
+ self.layers = nn.ModuleList(
1569
+ [
1570
+ DeepseekV3DecoderLayer(config, layer_idx)
1571
+ for layer_idx in range(config.num_hidden_layers)
1572
+ ]
1573
+ )
1574
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1575
+ self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1576
+
1577
+ self.gradient_checkpointing = False
1578
+ # Initialize weights and apply final processing
1579
+ self.post_init()
1580
+
1581
+ def get_input_embeddings(self):
1582
+ return self.embed_tokens
1583
+
1584
+ def set_input_embeddings(self, value):
1585
+ self.embed_tokens = value
1586
+
1587
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1588
+ def forward(
1589
+ self,
1590
+ input_ids: torch.LongTensor = None,
1591
+ attention_mask: Optional[torch.Tensor] = None,
1592
+ position_ids: Optional[torch.LongTensor] = None,
1593
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1594
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1595
+ use_cache: Optional[bool] = None,
1596
+ output_attentions: Optional[bool] = None,
1597
+ output_hidden_states: Optional[bool] = None,
1598
+ return_dict: Optional[bool] = None,
1599
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1600
+ output_attentions = (
1601
+ output_attentions
1602
+ if output_attentions is not None
1603
+ else self.config.output_attentions
1604
+ )
1605
+ output_hidden_states = (
1606
+ output_hidden_states
1607
+ if output_hidden_states is not None
1608
+ else self.config.output_hidden_states
1609
+ )
1610
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1611
+
1612
+ return_dict = (
1613
+ return_dict if return_dict is not None else self.config.use_return_dict
1614
+ )
1615
+
1616
+ # retrieve input_ids and inputs_embeds
1617
+ if input_ids is not None and inputs_embeds is not None:
1618
+ raise ValueError(
1619
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1620
+ )
1621
+ elif input_ids is not None:
1622
+ batch_size, seq_length = input_ids.shape[:2]
1623
+ elif inputs_embeds is not None:
1624
+ batch_size, seq_length = inputs_embeds.shape[:2]
1625
+ else:
1626
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1627
+
1628
+ past_key_values_length = 0
1629
+ if use_cache:
1630
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1631
+ if use_legacy_cache:
1632
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1633
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1634
+
1635
+ if position_ids is None:
1636
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1637
+ position_ids = torch.arange(
1638
+ past_key_values_length,
1639
+ seq_length + past_key_values_length,
1640
+ dtype=torch.long,
1641
+ device=device,
1642
+ )
1643
+ position_ids = position_ids.unsqueeze(0)
1644
+
1645
+ if inputs_embeds is None:
1646
+ input_ids = input_ids.to(self.embed_tokens.weight.device)
1647
+ inputs_embeds = self.embed_tokens(input_ids)
1648
+
1649
+ if self._use_flash_attention_2:
1650
+ # 2d mask is passed through the layers
1651
+ attention_mask = (
1652
+ attention_mask
1653
+ if (attention_mask is not None and 0 in attention_mask)
1654
+ else None
1655
+ )
1656
+ else:
1657
+ # 4d mask is passed through the layers
1658
+ attention_mask = _prepare_4d_causal_attention_mask(
1659
+ attention_mask,
1660
+ (batch_size, seq_length),
1661
+ inputs_embeds,
1662
+ past_key_values_length,
1663
+ )
1664
+
1665
+ # embed positions
1666
+ hidden_states = inputs_embeds
1667
+
1668
+ # decoder layers
1669
+ all_hidden_states = () if output_hidden_states else None
1670
+ all_self_attns = () if output_attentions else None
1671
+ next_decoder_cache = None
1672
+
1673
+ for decoder_layer in self.layers:
1674
+ ## put layer on device
1675
+ hidden_states = hidden_states.to(next(decoder_layer.parameters()).device)
1676
+ position_ids = position_ids.to(next(decoder_layer.parameters()).device)
1677
+
1678
+ if output_hidden_states:
1679
+ all_hidden_states += (hidden_states,)
1680
+
1681
+ layer_outputs = decoder_layer(
1682
+ hidden_states,
1683
+ attention_mask=attention_mask,
1684
+ position_ids=position_ids,
1685
+ past_key_value=past_key_values,
1686
+ output_attentions=output_attentions,
1687
+ use_cache=use_cache,
1688
+ )
1689
+
1690
+ hidden_states = layer_outputs[0]
1691
+
1692
+ if use_cache:
1693
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1694
+
1695
+ if output_attentions:
1696
+ all_self_attns += (layer_outputs[1],)
1697
+
1698
+ hidden_states=hidden_states.to(self.norm.weight.device)
1699
+ hidden_states = self.norm(hidden_states)
1700
+
1701
+ # add hidden states from the last decoder layer
1702
+ if output_hidden_states:
1703
+ all_hidden_states += (hidden_states,)
1704
+
1705
+ next_cache = None
1706
+ if use_cache:
1707
+ next_cache = (
1708
+ next_decoder_cache.to_legacy_cache()
1709
+ if use_legacy_cache
1710
+ else next_decoder_cache
1711
+ )
1712
+ if not return_dict:
1713
+ return tuple(
1714
+ v
1715
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1716
+ if v is not None
1717
+ )
1718
+ return BaseModelOutputWithPast(
1719
+ last_hidden_state=hidden_states,
1720
+ past_key_values=next_cache,
1721
+ hidden_states=all_hidden_states,
1722
+ attentions=all_self_attns,
1723
+ )
1724
+
1725
+ class DeepseekV3ForCausalLM(DeepseekV3PreTrainedModel):
1726
+ _tied_weights_keys = ["lm_head.weight"]
1727
+
1728
+ def __init__(self, config):
1729
+ super().__init__(config)
1730
+ self.model = DeepseekV3Model(config)
1731
+ self.vocab_size = config.vocab_size
1732
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1733
+
1734
+ # Initialize weights and apply final processing
1735
+ self.post_init()
1736
+
1737
+ def get_input_embeddings(self):
1738
+ return self.model.embed_tokens
1739
+
1740
+ def set_input_embeddings(self, value):
1741
+ self.model.embed_tokens = value
1742
+
1743
+ def get_output_embeddings(self):
1744
+ return self.lm_head
1745
+
1746
+ def set_output_embeddings(self, new_embeddings):
1747
+ self.lm_head = new_embeddings
1748
+
1749
+ def set_decoder(self, decoder):
1750
+ self.model = decoder
1751
+
1752
+ def get_decoder(self):
1753
+ return self.model
1754
+
1755
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1756
+ @replace_return_docstrings(
1757
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1758
+ )
1759
+ def forward(
1760
+ self,
1761
+ input_ids: torch.LongTensor = None,
1762
+ attention_mask: Optional[torch.Tensor] = None,
1763
+ position_ids: Optional[torch.LongTensor] = None,
1764
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1765
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1766
+ labels: Optional[torch.LongTensor] = None,
1767
+ use_cache: Optional[bool] = None,
1768
+ output_attentions: Optional[bool] = None,
1769
+ output_hidden_states: Optional[bool] = None,
1770
+ return_dict: Optional[bool] = None,
1771
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1772
+ r"""
1773
+ Args:
1774
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1775
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1776
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1777
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1778
+
1779
+ Returns:
1780
+
1781
+ Example:
1782
+
1783
+ ```python
1784
+ >>> from transformers import AutoTokenizer, DeepseekV3ForCausalLM
1785
+
1786
+ >>> model = DeepseekV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1787
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1788
+
1789
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1790
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1791
+
1792
+ >>> # Generate
1793
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1794
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1795
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1796
+ ```"""
1797
+ output_attentions = (
1798
+ output_attentions
1799
+ if output_attentions is not None
1800
+ else self.config.output_attentions
1801
+ )
1802
+ output_hidden_states = (
1803
+ output_hidden_states
1804
+ if output_hidden_states is not None
1805
+ else self.config.output_hidden_states
1806
+ )
1807
+ return_dict = (
1808
+ return_dict if return_dict is not None else self.config.use_return_dict
1809
+ )
1810
+
1811
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1812
+ outputs = self.model(
1813
+ input_ids=input_ids,
1814
+ attention_mask=attention_mask,
1815
+ position_ids=position_ids,
1816
+ past_key_values=past_key_values,
1817
+ inputs_embeds=inputs_embeds,
1818
+ use_cache=use_cache,
1819
+ output_attentions=output_attentions,
1820
+ output_hidden_states=output_hidden_states,
1821
+ return_dict=return_dict,
1822
+ )
1823
+
1824
+ hidden_states = outputs[0]
1825
+
1826
+ hidden_states=hidden_states.to(self.lm_head.weight.device)
1827
+ logits = self.lm_head(hidden_states)
1828
+ logits = logits.float()
1829
+
1830
+ loss = None
1831
+ if labels is not None:
1832
+ # Shift so that tokens < n predict n
1833
+ shift_logits = logits[..., :-1, :].contiguous()
1834
+ shift_labels = labels[..., 1:].contiguous()
1835
+ # Flatten the tokens
1836
+ loss_fct = CrossEntropyLoss()
1837
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1838
+ shift_labels = shift_labels.view(-1)
1839
+ # Enable model parallelism
1840
+ shift_labels = shift_labels.to(shift_logits.device)
1841
+ loss = loss_fct(shift_logits, shift_labels)
1842
+
1843
+ if not return_dict:
1844
+ output = (logits,) + outputs[1:]
1845
+ return (loss,) + output if loss is not None else output
1846
+
1847
+ return CausalLMOutputWithPast(
1848
+ loss=loss,
1849
+ logits=logits,
1850
+ past_key_values=outputs.past_key_values,
1851
+ hidden_states=outputs.hidden_states,
1852
+ attentions=outputs.attentions,
1853
+ )
1854
+
1855
+ def prepare_inputs_for_generation(
1856
+ self,
1857
+ input_ids,
1858
+ past_key_values=None,
1859
+ attention_mask=None,
1860
+ inputs_embeds=None,
1861
+ **kwargs,
1862
+ ):
1863
+ if past_key_values is not None:
1864
+ if isinstance(past_key_values, Cache):
1865
+ cache_length = past_key_values.get_seq_length()
1866
+ past_length = past_key_values.seen_tokens
1867
+ max_cache_length = past_key_values.get_max_length()
1868
+ else:
1869
+ cache_length = past_length = past_key_values[0][0].shape[2]
1870
+ max_cache_length = None
1871
+
1872
+ # Keep only the unprocessed tokens:
1873
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1874
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1875
+ # input)
1876
+ if (
1877
+ attention_mask is not None
1878
+ and attention_mask.shape[1] > input_ids.shape[1]
1879
+ ):
1880
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1881
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1882
+ # input_ids based on the past_length.
1883
+ elif past_length < input_ids.shape[1]:
1884
+ input_ids = input_ids[:, past_length:]
1885
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1886
+
1887
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1888
+ if (
1889
+ max_cache_length is not None
1890
+ and attention_mask is not None
1891
+ and cache_length + input_ids.shape[1] > max_cache_length
1892
+ ):
1893
+ attention_mask = attention_mask[:, -max_cache_length:]
1894
+
1895
+ position_ids = kwargs.get("position_ids", None)
1896
+ if attention_mask is not None and position_ids is None:
1897
+ # create position_ids on the fly for batch generation
1898
+ position_ids = attention_mask.long().cumsum(-1) - 1
1899
+ position_ids.masked_fill_(attention_mask == 0, 1)
1900
+ if past_key_values:
1901
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1902
+
1903
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1904
+ if inputs_embeds is not None and past_key_values is None:
1905
+ model_inputs = {"inputs_embeds": inputs_embeds}
1906
+ else:
1907
+ model_inputs = {"input_ids": input_ids}
1908
+
1909
+ model_inputs.update(
1910
+ {
1911
+ "position_ids": position_ids,
1912
+ "past_key_values": past_key_values,
1913
+ "use_cache": kwargs.get("use_cache"),
1914
+ "attention_mask": attention_mask,
1915
+ }
1916
+ )
1917
+ return model_inputs
1918
+
1919
+ @staticmethod
1920
+ def _reorder_cache(past_key_values, beam_idx):
1921
+ reordered_past = ()
1922
+ for layer_past in past_key_values:
1923
+ reordered_past += (
1924
+ tuple(
1925
+ past_state.index_select(0, beam_idx.to(past_state.device))
1926
+ for past_state in layer_past
1927
+ ),
1928
+ )
1929
+ return reordered_past
1930
+
1931
+ @add_start_docstrings(
1932
+ """
1933
+ The DeepseekV3 Model transformer with a sequence classification head on top (linear layer).
1934
+
1935
+ [`DeepseekV3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1936
+ (e.g. GPT-2) do.
1937
+
1938
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1939
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1940
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1941
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1942
+ each row of the batch).
1943
+ """,
1944
+ DeepseekV3_START_DOCSTRING,
1945
+ )
1946
+ class DeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel):
1947
+ def __init__(self, config):
1948
+ super().__init__(config)
1949
+ self.num_labels = config.num_labels
1950
+ self.model = DeepseekV3Model(config)
1951
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1952
+
1953
+ # Initialize weights and apply final processing
1954
+ self.post_init()
1955
+
1956
+ def get_input_embeddings(self):
1957
+ return self.model.embed_tokens
1958
+
1959
+ def set_input_embeddings(self, value):
1960
+ self.model.embed_tokens = value
1961
+
1962
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1963
+ def forward(
1964
+ self,
1965
+ input_ids: torch.LongTensor = None,
1966
+ attention_mask: Optional[torch.Tensor] = None,
1967
+ position_ids: Optional[torch.LongTensor] = None,
1968
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1969
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1970
+ labels: Optional[torch.LongTensor] = None,
1971
+ use_cache: Optional[bool] = None,
1972
+ output_attentions: Optional[bool] = None,
1973
+ output_hidden_states: Optional[bool] = None,
1974
+ return_dict: Optional[bool] = None,
1975
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1976
+ r"""
1977
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1978
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1979
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1980
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1981
+ """
1982
+ return_dict = (
1983
+ return_dict if return_dict is not None else self.config.use_return_dict
1984
+ )
1985
+
1986
+ transformer_outputs = self.model(
1987
+ input_ids,
1988
+ attention_mask=attention_mask,
1989
+ position_ids=position_ids,
1990
+ past_key_values=past_key_values,
1991
+ inputs_embeds=inputs_embeds,
1992
+ use_cache=use_cache,
1993
+ output_attentions=output_attentions,
1994
+ output_hidden_states=output_hidden_states,
1995
+ return_dict=return_dict,
1996
+ )
1997
+ hidden_states = transformer_outputs[0]
1998
+ logits = self.score(hidden_states)
1999
+
2000
+ if input_ids is not None:
2001
+ batch_size = input_ids.shape[0]
2002
+ else:
2003
+ batch_size = inputs_embeds.shape[0]
2004
+
2005
+ if self.config.pad_token_id is None and batch_size != 1:
2006
+ raise ValueError(
2007
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2008
+ )
2009
+ if self.config.pad_token_id is None:
2010
+ sequence_lengths = -1
2011
+ else:
2012
+ if input_ids is not None:
2013
+ sequence_lengths = (
2014
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2015
+ ).to(logits.device)
2016
+ else:
2017
+ sequence_lengths = -1
2018
+
2019
+ pooled_logits = logits[
2020
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2021
+ ]
2022
+
2023
+ loss = None
2024
+ if labels is not None:
2025
+ labels = labels.to(logits.device)
2026
+ if self.config.problem_type is None:
2027
+ if self.num_labels == 1:
2028
+ self.config.problem_type = "regression"
2029
+ elif self.num_labels > 1 and (
2030
+ labels.dtype == torch.long or labels.dtype == torch.int
2031
+ ):
2032
+ self.config.problem_type = "single_label_classification"
2033
+ else:
2034
+ self.config.problem_type = "multi_label_classification"
2035
+
2036
+ if self.config.problem_type == "regression":
2037
+ loss_fct = MSELoss()
2038
+ if self.num_labels == 1:
2039
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2040
+ else:
2041
+ loss = loss_fct(pooled_logits, labels)
2042
+ elif self.config.problem_type == "single_label_classification":
2043
+ loss_fct = CrossEntropyLoss()
2044
+ loss = loss_fct(
2045
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2046
+ )
2047
+ elif self.config.problem_type == "multi_label_classification":
2048
+ loss_fct = BCEWithLogitsLoss()
2049
+ loss = loss_fct(pooled_logits, labels)
2050
+ if not return_dict:
2051
+ output = (pooled_logits,) + transformer_outputs[1:]
2052
+ return ((loss,) + output) if loss is not None else output
2053
+
2054
+ return SequenceClassifierOutputWithPast(
2055
+ loss=loss,
2056
+ logits=pooled_logits,
2057
+ past_key_values=transformer_outputs.past_key_values,
2058
+ hidden_states=transformer_outputs.hidden_states,
2059
+ attentions=transformer_outputs.attentions,
2060
+ )
2061
+
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|begin▁of▁sentence|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|end▁of▁sentence|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|end▁of▁sentence|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff