AlphaGaO commited on
Commit
60c27ec
·
verified ·
1 Parent(s): 5582fe9

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-Coder-v2-Lite-Instruct Fused Models (Research Release)
10
+
11
+ ## CRITICAL NOTE: Untrained Fusion - Requires Healing!
12
+
13
+ **These are *unhealed*, experimental versions of DeepSeek-Coder-v2-lite-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
+ ## What to Expect (Before Healing)
16
+
17
+ 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.
18
+
19
+ ## Healing Instructions (Required)
20
+
21
+ **Crucially, you *must* perform post-training to make these models usable.** The necessary scripts and detailed instructions are available in the **moe-pruner** repository:
22
+
23
+ **[https://github.com/gabrielolympie/moe-pruner](https://github.com/gabrielolympie/moe-pruner)**
24
+
25
+ Follow the instructions in that repository *carefully* to "heal" the pruned model. This process is essential to recover performance.
26
+
27
+ ## Contributing and Future Improvements
28
+
29
+ This release represents an initial exploration of model fusion and distillation. Due to hardware limitations, significant compromises were made during development.
30
+
31
+ We welcome contributions to improve this work! There are two primary ways to help:
32
+
33
+ 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)
34
+
35
+ 2. **Code Contributions:** Suggest improvements, bug fixes, or new features directly on the GitHub repository.
36
+
37
+ We are actively working to improve the fusion and distillation techniques, and your contributions are greatly appreciated.
38
+
39
+ ## Disclaimer
40
+
41
+ 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.
42
+
43
+ #
44
+ #
45
+ #
46
+ #
47
+
48
+
49
+ ## Original Model Card
50
+
51
+ ---
52
+ license: other
53
+ license_name: deepseek-license
54
+ license_link: LICENSE
55
+ ---
56
+ <!-- markdownlint-disable first-line-h1 -->
57
+ <!-- markdownlint-disable html -->
58
+ <!-- markdownlint-disable no-duplicate-header -->
59
+
60
+ <div align="center">
61
+ <img src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/logo.svg?raw=true" width="60%" alt="DeepSeek-V2" />
62
+ </div>
63
+ <hr>
64
+ <div align="center" style="line-height: 1;">
65
+ <a href="https://www.deepseek.com/" target="_blank" style="margin: 2px;">
66
+ <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;"/>
67
+ </a>
68
+ <a href="https://chat.deepseek.com/" target="_blank" style="margin: 2px;">
69
+ <img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-DeepSeek%20V2-536af5?color=536af5&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
70
+ </a>
71
+ <a href="https://huggingface.co/deepseek-ai" target="_blank" style="margin: 2px;">
72
+ <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;"/>
73
+ </a>
74
+ </div>
75
+
76
+ <div align="center" style="line-height: 1;">
77
+ <a href="https://discord.gg/Tc7c45Zzu5" target="_blank" style="margin: 2px;">
78
+ <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;"/>
79
+ </a>
80
+ <a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/qr.jpeg?raw=true" target="_blank" style="margin: 2px;">
81
+ <img alt="Wechat" src="https://img.shields.io/badge/WeChat-DeepSeek%20AI-brightgreen?logo=wechat&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
82
+ </a>
83
+ <a href="https://twitter.com/deepseek_ai" target="_blank" style="margin: 2px;">
84
+ <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;"/>
85
+ </a>
86
+ </div>
87
+
88
+ <div align="center" style="line-height: 1;">
89
+ <a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/LICENSE-CODE" style="margin: 2px;">
90
+ <img alt="Code License" src="https://img.shields.io/badge/Code_License-MIT-f5de53?&color=f5de53" style="display: inline-block; vertical-align: middle;"/>
91
+ </a>
92
+ <a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/LICENSE-MODEL" style="margin: 2px;">
93
+ <img alt="Model License" src="https://img.shields.io/badge/Model_License-Model_Agreement-f5de53?&color=f5de53" style="display: inline-block; vertical-align: middle;"/>
94
+ </a>
95
+ </div>
96
+ <p align="center">
97
+ <a href="#4-api-platform">API Platform</a> |
98
+ <a href="#5-how-to-run-locally">How to Use</a> |
99
+ <a href="#6-license">License</a> |
100
+ </p>
101
+
102
+
103
+ <p align="center">
104
+ <a href="https://github.com/deepseek-ai/DeepSeek-Coder-V2/blob/main/paper.pdf"><b>Paper Link</b>👁️</a>
105
+ </p>
106
+
107
+ AWQ quantized version of DeepSeek-Coder-V2-Lite-Instruct model.
108
+
109
+ ---
110
+
111
+ # DeepSeek-Coder-V2: Breaking the Barrier of Closed-Source Models in Code Intelligence
112
+
113
+ ## 1. Introduction
114
+ We present DeepSeek-Coder-V2, an open-source Mixture-of-Experts (MoE) code language model that achieves performance comparable to GPT4-Turbo in code-specific tasks. Specifically, DeepSeek-Coder-V2 is further pre-trained from DeepSeek-Coder-V2-Base with 6 trillion tokens sourced from a high-quality and multi-source corpus. Through this continued pre-training, DeepSeek-Coder-V2 substantially enhances the coding and mathematical reasoning capabilities of DeepSeek-Coder-V2-Base, while maintaining comparable performance in general language tasks. Compared to DeepSeek-Coder, DeepSeek-Coder-V2 demonstrates significant advancements in various aspects of code-related tasks, as well as reasoning and general capabilities. Additionally, DeepSeek-Coder-V2 expands its support for programming languages from 86 to 338, while extending the context length from 16K to 128K.
115
+
116
+ <p align="center">
117
+ <img width="100%" src="https://github.com/deepseek-ai/DeepSeek-Coder-V2/blob/main/figures/performance.png?raw=true">
118
+ </p>
119
+
120
+ In standard benchmark evaluations, DeepSeek-Coder-V2 achieves superior performance compared to closed-source models such as GPT4-Turbo, Claude 3 Opus, and Gemini 1.5 Pro in coding and math benchmarks. The list of supported programming languages can be found in the paper.
121
+
122
+ ## 2. Model Downloads
123
+
124
+ We release the DeepSeek-Coder-V2 with 16B and 236B parameters based on the [DeepSeekMoE](https://arxiv.org/pdf/2401.06066) framework, which has actived parameters of only 2.4B and 21B , including base and instruct models, to the public.
125
+
126
+ <div align="center">
127
+
128
+ | **Model** | **#Total Params** | **#Active Params** | **Context Length** | **Download** |
129
+ | :-----------------------------: | :---------------: | :----------------: | :----------------: | :----------------------------------------------------------: |
130
+ | DeepSeek-Coder-V2-Lite-Base | 16B | 2.4B | 128k | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-Coder-V2-Lite-Base) |
131
+ | DeepSeek-Coder-V2-Lite-Instruct | 16B | 2.4B | 128k | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct) |
132
+ | DeepSeek-Coder-V2-Base | 236B | 21B | 128k | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-Coder-V2-Base) |
133
+ | DeepSeek-Coder-V2-Instruct | 236B | 21B | 128k | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-Coder-V2-Instruct) |
134
+
135
+ </div>
136
+
137
+
138
+ ## 3. Chat Website
139
+
140
+ You can chat with the DeepSeek-Coder-V2 on DeepSeek's official website: [coder.deepseek.com](https://coder.deepseek.com/sign_in)
141
+
142
+ ## 4. API Platform
143
+ We also provide OpenAI-Compatible API at DeepSeek Platform: [platform.deepseek.com](https://platform.deepseek.com/). Sign up for over millions of free tokens. And you can also pay-as-you-go at an unbeatable price.
144
+
145
+ <p align="center">
146
+ <img width="40%" src="https://github.com/deepseek-ai/DeepSeek-Coder-V2/blob/main/figures/model_price.jpg?raw=true">
147
+ </p>
148
+
149
+
150
+ ## 5. How to run locally
151
+ **Here, we provide some examples of how to use DeepSeek-Coder-V2-Lite model. If you want to utilize DeepSeek-Coder-V2 in BF16 format for inference, 80GB*8 GPUs are required.**
152
+
153
+ ### Inference with Huggingface's Transformers
154
+ You can directly employ [Huggingface's Transformers](https://github.com/huggingface/transformers) for model inference.
155
+
156
+ #### Code Completion
157
+ ```python
158
+ from transformers import AutoTokenizer, AutoModelForCausalLM
159
+ import torch
160
+ tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-Coder-V2-Lite-Base", trust_remote_code=True)
161
+ model = AutoModelForCausalLM.from_pretrained("deepseek-ai/DeepSeek-Coder-V2-Lite-Base", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
162
+ input_text = "#write a quick sort algorithm"
163
+ inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
164
+ outputs = model.generate(**inputs, max_length=128)
165
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
166
+ ```
167
+
168
+ #### Code Insertion
169
+ ```python
170
+ from transformers import AutoTokenizer, AutoModelForCausalLM
171
+ import torch
172
+ tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-Coder-V2-Lite-Base", trust_remote_code=True)
173
+ model = AutoModelForCausalLM.from_pretrained("deepseek-ai/DeepSeek-Coder-V2-Lite-Base", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
174
+ input_text = """<|fim▁begin|>def quick_sort(arr):
175
+ if len(arr) <= 1:
176
+ return arr
177
+ pivot = arr[0]
178
+ left = []
179
+ right = []
180
+ <|fim▁hole|>
181
+ if arr[i] < pivot:
182
+ left.append(arr[i])
183
+ else:
184
+ right.append(arr[i])
185
+ return quick_sort(left) + [pivot] + quick_sort(right)<|fim▁end|>"""
186
+ inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
187
+ outputs = model.generate(**inputs, max_length=128)
188
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True)[len(input_text):])
189
+ ```
190
+
191
+ #### Chat Completion
192
+
193
+ ```python
194
+ from transformers import AutoTokenizer, AutoModelForCausalLM
195
+ import torch
196
+ tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct", trust_remote_code=True)
197
+ model = AutoModelForCausalLM.from_pretrained("deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
198
+ messages=[
199
+ { 'role': 'user', 'content': "write a quick sort algorithm in python."}
200
+ ]
201
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
202
+ # tokenizer.eos_token_id is the id of <|EOT|> token
203
+ outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, top_k=50, top_p=0.95, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
204
+ print(tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True))
205
+ ```
206
+
207
+
208
+
209
+ The complete chat template can be found within `tokenizer_config.json` located in the huggingface model repository.
210
+
211
+ An example of chat template is as belows:
212
+
213
+ ```bash
214
+ <|begin▁of▁sentence|>User: {user_message_1}
215
+
216
+ Assistant: {assistant_message_1}<|end▁of▁sentence|>User: {user_message_2}
217
+
218
+ Assistant:
219
+ ```
220
+
221
+ You can also add an optional system message:
222
+
223
+ ```bash
224
+ <|begin▁of▁sentence|>{system_message}
225
+
226
+ User: {user_message_1}
227
+
228
+ Assistant: {assistant_message_1}<|end▁of▁sentence|>User: {user_message_2}
229
+
230
+ Assistant:
231
+ ```
232
+
233
+ ### Inference with vLLM (recommended)
234
+ To utilize [vLLM](https://github.com/vllm-project/vllm) for model inference, please merge this Pull Request into your vLLM codebase: https://github.com/vllm-project/vllm/pull/4650.
235
+
236
+ ```python
237
+ from transformers import AutoTokenizer
238
+ from vllm import LLM, SamplingParams
239
+
240
+ max_model_len, tp_size = 8192, 1
241
+ model_name = "deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct"
242
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
243
+ llm = LLM(model=model_name, tensor_parallel_size=tp_size, max_model_len=max_model_len, trust_remote_code=True, enforce_eager=True)
244
+ sampling_params = SamplingParams(temperature=0.3, max_tokens=256, stop_token_ids=[tokenizer.eos_token_id])
245
+
246
+ messages_list = [
247
+ [{"role": "user", "content": "Who are you?"}],
248
+ [{"role": "user", "content": "write a quick sort algorithm in python."}],
249
+ [{"role": "user", "content": "Write a piece of quicksort code in C++."}],
250
+ ]
251
+
252
+ prompt_token_ids = [tokenizer.apply_chat_template(messages, add_generation_prompt=True) for messages in messages_list]
253
+
254
+ outputs = llm.generate(prompt_token_ids=prompt_token_ids, sampling_params=sampling_params)
255
+
256
+ generated_text = [output.outputs[0].text for output in outputs]
257
+ print(generated_text)
258
+ ```
259
+
260
+
261
+
262
+ ## 6. License
263
+
264
+ This code repository is licensed under [the MIT License](https://github.com/deepseek-ai/DeepSeek-Coder-V2/blob/main/LICENSE-CODE). The use of DeepSeek-Coder-V2 Base/Instruct models is subject to [the Model License](https://github.com/deepseek-ai/DeepSeek-Coder-V2/blob/main/LICENSE-MODEL). DeepSeek-Coder-V2 series (including Base and Instruct) supports commercial use.
265
+
266
+
267
+ ## 7. Contact
268
+ If you have any questions, please raise an issue or contact us at [[email protected]]([email protected]).
config.json ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct",
3
+ "architectures": [
4
+ "DeepseekV2ForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_deepseek.DeepseekV2Config",
10
+ "AutoModel": "modeling_deepseek.DeepseekV2Model",
11
+ "AutoModelForCausalLM": "modeling_deepseek.DeepseekV2ForCausalLM"
12
+ },
13
+ "aux_loss_alpha": 0.001,
14
+ "bos_token_id": 100000,
15
+ "eos_token_id": 100001,
16
+ "ep_size": 1,
17
+ "first_k_dense_replace": 1,
18
+ "fused_expert_dora_rank": 8,
19
+ "fused_expert_method": "mixture",
20
+ "hidden_act": "silu",
21
+ "hidden_size": 2048,
22
+ "initializer_range": 0.02,
23
+ "intermediate_size": 10944,
24
+ "kv_lora_rank": 512,
25
+ "max_position_embeddings": 163840,
26
+ "model_type": "deepseek_v2",
27
+ "moe_intermediate_size": 1408,
28
+ "moe_layer_freq": 1,
29
+ "n_fused_experts": 2,
30
+ "n_group": 1,
31
+ "n_routed_experts": 64,
32
+ "n_shared_experts": 2,
33
+ "norm_topk_prob": false,
34
+ "num_attention_heads": 16,
35
+ "num_experts_per_tok": 6,
36
+ "num_hidden_layers": 27,
37
+ "num_key_value_heads": 16,
38
+ "pretraining_tp": 1,
39
+ "q_lora_rank": null,
40
+ "qk_nope_head_dim": 128,
41
+ "qk_rope_head_dim": 64,
42
+ "rms_norm_eps": 1e-06,
43
+ "rope_scaling": {
44
+ "beta_fast": 32,
45
+ "beta_slow": 1,
46
+ "factor": 40,
47
+ "mscale": 0.707,
48
+ "mscale_all_dim": 0.707,
49
+ "original_max_position_embeddings": 4096,
50
+ "type": "yarn"
51
+ },
52
+ "rope_theta": 10000,
53
+ "routed_scaling_factor": 1.0,
54
+ "scoring_func": "softmax",
55
+ "seq_aux": true,
56
+ "tie_word_embeddings": false,
57
+ "topk_group": 1,
58
+ "topk_method": "greedy",
59
+ "torch_dtype": "bfloat16",
60
+ "transformers_version": "4.47.1",
61
+ "use_cache": true,
62
+ "v_head_dim": 128,
63
+ "vocab_size": 102400
64
+ }
configuration_deepseek.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 DeepseekV2Config(PretrainedConfig):
8
+ r"""
9
+ This is the configuration class to store the configuration of a [`DeepseekV2Model`]. It is used to instantiate an DeepSeek
10
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
11
+ defaults will yield a similar configuration to that of the DeepSeek-V2.
12
+
13
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
14
+ documentation from [`PretrainedConfig`] for more information.
15
+
16
+
17
+ Args:
18
+ vocab_size (`int`, *optional*, defaults to 102400):
19
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
20
+ `inputs_ids` passed when calling [`DeepseekV2Model`]
21
+ hidden_size (`int`, *optional*, defaults to 4096):
22
+ Dimension of the hidden representations.
23
+ intermediate_size (`int`, *optional*, defaults to 11008):
24
+ Dimension of the MLP representations.
25
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
26
+ Dimension of the MoE representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer decoder.
29
+ num_attention_heads (`int`, *optional*, defaults to 32):
30
+ Number of attention heads for each attention layer in the Transformer decoder.
31
+ n_shared_experts (`int`, *optional*, defaults to None):
32
+ Number of shared experts, None means dense model.
33
+ n_routed_experts (`int`, *optional*, defaults to None):
34
+ Number of routed experts, None means dense model.
35
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
36
+ Scaling factor or routed experts.
37
+ topk_method (`str`, *optional*, defaults to `gready`):
38
+ Topk method used in routed gate.
39
+ n_group (`int`, *optional*, defaults to None):
40
+ Number of groups for routed experts.
41
+ topk_group (`int`, *optional*, defaults to None):
42
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
43
+ num_experts_per_tok (`int`, *optional*, defaults to None):
44
+ Number of selected experts, None means dense model.
45
+ moe_layer_freq (`int`, *optional*, defaults to 1):
46
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
47
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
48
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
49
+ \--k dense layers--/
50
+ norm_topk_prob (`bool`, *optional*, defaults to False):
51
+ Whether to normalize the weights of the routed experts.
52
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
53
+ Method of computing expert weights.
54
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
55
+ Auxiliary loss weight coefficient.
56
+ seq_aux = (`bool`, *optional*, defaults to True):
57
+ Whether to compute the auxiliary loss for each individual sample.
58
+ num_key_value_heads (`int`, *optional*):
59
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
60
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
61
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
62
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
63
+ by meanpooling all the original heads within that group. For more details checkout [this
64
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
65
+ `num_attention_heads`.
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with.
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
73
+ The epsilon used by the rms normalization layers.
74
+ use_cache (`bool`, *optional*, defaults to `True`):
75
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
76
+ relevant if `config.is_decoder=True`.
77
+ pad_token_id (`int`, *optional*):
78
+ Padding token id.
79
+ bos_token_id (`int`, *optional*, defaults to 1):
80
+ Beginning of stream token id.
81
+ eos_token_id (`int`, *optional*, defaults to 2):
82
+ End of stream token id.
83
+ pretraining_tp (`int`, *optional*, defaults to 1):
84
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
85
+ document](https://hf-mirror.com/docs/transformers/parallelism) to understand more about it. This value is
86
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
87
+ issue](https://github.com/pytorch/pytorch/issues/76232).
88
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
89
+ Whether to tie weight embeddings
90
+ rope_theta (`float`, *optional*, defaults to 10000.0):
91
+ The base period of the RoPE embeddings.
92
+ rope_scaling (`Dict`, *optional*):
93
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
94
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
95
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
96
+ `max_position_embeddings` to the expected new maximum.
97
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
98
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
99
+ attention_dropout (`float`, *optional*, defaults to 0.0):
100
+ The dropout ratio for the attention probabilities.
101
+
102
+ ```python
103
+ >>> from transformers import DeepseekV2Model, DeepseekV2Config
104
+
105
+ >>> # Initializing a Deepseek-V2 style configuration
106
+ >>> configuration = DeepseekV2Config()
107
+
108
+ >>> # Accessing the model configuration
109
+ >>> configuration = model.config
110
+ ```"""
111
+
112
+ model_type = "deepseek_v2"
113
+ keys_to_ignore_at_inference = ["past_key_values"]
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=102400,
118
+ hidden_size=4096,
119
+ intermediate_size=11008,
120
+ moe_intermediate_size = 1407,
121
+ num_hidden_layers=30,
122
+ num_attention_heads=32,
123
+ num_key_value_heads=32,
124
+ n_shared_experts = None,
125
+ n_routed_experts = None,
126
+ n_fused_experts = None,
127
+ fused_expert_dora_rank = None,
128
+ fused_expert_method = "mixture",
129
+ ep_size = 1,
130
+ routed_scaling_factor = 1.0,
131
+ kv_lora_rank = 512,
132
+ q_lora_rank = 1536,
133
+ qk_rope_head_dim = 64,
134
+ v_head_dim = 128,
135
+ qk_nope_head_dim = 128,
136
+ topk_method = 'gready',
137
+ n_group = None,
138
+ topk_group = None,
139
+ num_experts_per_tok = None,
140
+ moe_layer_freq = 1,
141
+ first_k_dense_replace = 0,
142
+ norm_topk_prob = False,
143
+ scoring_func = 'softmax',
144
+ aux_loss_alpha = 0.001,
145
+ seq_aux = True,
146
+ hidden_act="silu",
147
+ max_position_embeddings=2048,
148
+ initializer_range=0.02,
149
+ rms_norm_eps=1e-6,
150
+ use_cache=True,
151
+ pad_token_id=None,
152
+ bos_token_id=100000,
153
+ eos_token_id=100001,
154
+ pretraining_tp=1,
155
+ tie_word_embeddings=False,
156
+ rope_theta=10000.0,
157
+ rope_scaling=None,
158
+ attention_bias=False,
159
+ attention_dropout=0.0,
160
+ **kwargs,
161
+ ):
162
+ self.vocab_size = vocab_size
163
+ self.max_position_embeddings = max_position_embeddings
164
+ self.hidden_size = hidden_size
165
+ self.intermediate_size = intermediate_size
166
+ self.moe_intermediate_size = moe_intermediate_size
167
+ self.num_hidden_layers = num_hidden_layers
168
+ self.num_attention_heads = num_attention_heads
169
+ self.n_shared_experts = n_shared_experts
170
+ self.n_routed_experts = n_routed_experts
171
+ self.n_fused_experts = n_fused_experts
172
+ self.fused_expert_dora_rank = fused_expert_dora_rank
173
+ self.fused_expert_method=fused_expert_method
174
+ self.ep_size = ep_size
175
+ self.routed_scaling_factor = routed_scaling_factor
176
+ self.kv_lora_rank = kv_lora_rank
177
+ self.q_lora_rank = q_lora_rank
178
+ self.qk_rope_head_dim = qk_rope_head_dim
179
+ self.v_head_dim = v_head_dim
180
+ self.qk_nope_head_dim = qk_nope_head_dim
181
+ self.topk_method = topk_method
182
+ self.n_group = n_group
183
+ self.topk_group = topk_group
184
+ self.num_experts_per_tok = num_experts_per_tok
185
+ self.moe_layer_freq = moe_layer_freq
186
+ self.first_k_dense_replace = first_k_dense_replace
187
+ self.norm_topk_prob = norm_topk_prob
188
+ self.scoring_func = scoring_func
189
+ self.aux_loss_alpha = aux_loss_alpha
190
+ self.seq_aux = seq_aux
191
+ # for backward compatibility
192
+ if num_key_value_heads is None:
193
+ num_key_value_heads = num_attention_heads
194
+
195
+ self.num_key_value_heads = num_key_value_heads
196
+ self.hidden_act = hidden_act
197
+ self.initializer_range = initializer_range
198
+ self.rms_norm_eps = rms_norm_eps
199
+ self.pretraining_tp = pretraining_tp
200
+ self.use_cache = use_cache
201
+ self.rope_theta = rope_theta
202
+ self.rope_scaling = rope_scaling
203
+ self.attention_bias = attention_bias
204
+ self.attention_dropout = attention_dropout
205
+
206
+ super().__init__(
207
+ pad_token_id=pad_token_id,
208
+ bos_token_id=bos_token_id,
209
+ eos_token_id=eos_token_id,
210
+ tie_word_embeddings=tie_word_embeddings,
211
+ **kwargs,
212
+ )
configuration_deepseek_fused_v2.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 DeepseekV2Config(PretrainedConfig):
8
+ r"""
9
+ This is the configuration class to store the configuration of a [`DeepseekV2Model`]. It is used to instantiate an DeepSeek
10
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
11
+ defaults will yield a similar configuration to that of the DeepSeek-V2.
12
+
13
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
14
+ documentation from [`PretrainedConfig`] for more information.
15
+
16
+
17
+ Args:
18
+ vocab_size (`int`, *optional*, defaults to 102400):
19
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
20
+ `inputs_ids` passed when calling [`DeepseekV2Model`]
21
+ hidden_size (`int`, *optional*, defaults to 4096):
22
+ Dimension of the hidden representations.
23
+ intermediate_size (`int`, *optional*, defaults to 11008):
24
+ Dimension of the MLP representations.
25
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
26
+ Dimension of the MoE representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer decoder.
29
+ num_attention_heads (`int`, *optional*, defaults to 32):
30
+ Number of attention heads for each attention layer in the Transformer decoder.
31
+ n_shared_experts (`int`, *optional*, defaults to None):
32
+ Number of shared experts, None means dense model.
33
+ n_routed_experts (`int`, *optional*, defaults to None):
34
+ Number of routed experts, None means dense model.
35
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
36
+ Scaling factor or routed experts.
37
+ topk_method (`str`, *optional*, defaults to `gready`):
38
+ Topk method used in routed gate.
39
+ n_group (`int`, *optional*, defaults to None):
40
+ Number of groups for routed experts.
41
+ topk_group (`int`, *optional*, defaults to None):
42
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
43
+ num_experts_per_tok (`int`, *optional*, defaults to None):
44
+ Number of selected experts, None means dense model.
45
+ moe_layer_freq (`int`, *optional*, defaults to 1):
46
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
47
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
48
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
49
+ \--k dense layers--/
50
+ norm_topk_prob (`bool`, *optional*, defaults to False):
51
+ Whether to normalize the weights of the routed experts.
52
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
53
+ Method of computing expert weights.
54
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
55
+ Auxiliary loss weight coefficient.
56
+ seq_aux = (`bool`, *optional*, defaults to True):
57
+ Whether to compute the auxiliary loss for each individual sample.
58
+ num_key_value_heads (`int`, *optional*):
59
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
60
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
61
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
62
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
63
+ by meanpooling all the original heads within that group. For more details checkout [this
64
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
65
+ `num_attention_heads`.
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with.
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
73
+ The epsilon used by the rms normalization layers.
74
+ use_cache (`bool`, *optional*, defaults to `True`):
75
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
76
+ relevant if `config.is_decoder=True`.
77
+ pad_token_id (`int`, *optional*):
78
+ Padding token id.
79
+ bos_token_id (`int`, *optional*, defaults to 1):
80
+ Beginning of stream token id.
81
+ eos_token_id (`int`, *optional*, defaults to 2):
82
+ End of stream token id.
83
+ pretraining_tp (`int`, *optional*, defaults to 1):
84
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
85
+ document](https://hf-mirror.com/docs/transformers/parallelism) to understand more about it. This value is
86
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
87
+ issue](https://github.com/pytorch/pytorch/issues/76232).
88
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
89
+ Whether to tie weight embeddings
90
+ rope_theta (`float`, *optional*, defaults to 10000.0):
91
+ The base period of the RoPE embeddings.
92
+ rope_scaling (`Dict`, *optional*):
93
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
94
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
95
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
96
+ `max_position_embeddings` to the expected new maximum.
97
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
98
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
99
+ attention_dropout (`float`, *optional*, defaults to 0.0):
100
+ The dropout ratio for the attention probabilities.
101
+
102
+ ```python
103
+ >>> from transformers import DeepseekV2Model, DeepseekV2Config
104
+
105
+ >>> # Initializing a Deepseek-V2 style configuration
106
+ >>> configuration = DeepseekV2Config()
107
+
108
+ >>> # Accessing the model configuration
109
+ >>> configuration = model.config
110
+ ```"""
111
+
112
+ model_type = "deepseek_v2"
113
+ keys_to_ignore_at_inference = ["past_key_values"]
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=102400,
118
+ hidden_size=4096,
119
+ intermediate_size=11008,
120
+ moe_intermediate_size = 1407,
121
+ num_hidden_layers=30,
122
+ num_attention_heads=32,
123
+ num_key_value_heads=32,
124
+ n_shared_experts = None,
125
+ n_routed_experts = None,
126
+ n_fused_experts = None,
127
+ fused_expert_dora_rank = None,
128
+ fused_expert_method = "mixture",
129
+ ep_size = 1,
130
+ routed_scaling_factor = 1.0,
131
+ kv_lora_rank = 512,
132
+ q_lora_rank = 1536,
133
+ qk_rope_head_dim = 64,
134
+ v_head_dim = 128,
135
+ qk_nope_head_dim = 128,
136
+ topk_method = 'gready',
137
+ n_group = None,
138
+ topk_group = None,
139
+ num_experts_per_tok = None,
140
+ moe_layer_freq = 1,
141
+ first_k_dense_replace = 0,
142
+ norm_topk_prob = False,
143
+ scoring_func = 'softmax',
144
+ aux_loss_alpha = 0.001,
145
+ seq_aux = True,
146
+ hidden_act="silu",
147
+ max_position_embeddings=2048,
148
+ initializer_range=0.02,
149
+ rms_norm_eps=1e-6,
150
+ use_cache=True,
151
+ pad_token_id=None,
152
+ bos_token_id=100000,
153
+ eos_token_id=100001,
154
+ pretraining_tp=1,
155
+ tie_word_embeddings=False,
156
+ rope_theta=10000.0,
157
+ rope_scaling=None,
158
+ attention_bias=False,
159
+ attention_dropout=0.0,
160
+ **kwargs,
161
+ ):
162
+ self.vocab_size = vocab_size
163
+ self.max_position_embeddings = max_position_embeddings
164
+ self.hidden_size = hidden_size
165
+ self.intermediate_size = intermediate_size
166
+ self.moe_intermediate_size = moe_intermediate_size
167
+ self.num_hidden_layers = num_hidden_layers
168
+ self.num_attention_heads = num_attention_heads
169
+ self.n_shared_experts = n_shared_experts
170
+ self.n_routed_experts = n_routed_experts
171
+ self.n_fused_experts = n_fused_experts
172
+ self.fused_expert_dora_rank = fused_expert_dora_rank
173
+ self.fused_expert_method=fused_expert_method
174
+ self.ep_size = ep_size
175
+ self.routed_scaling_factor = routed_scaling_factor
176
+ self.kv_lora_rank = kv_lora_rank
177
+ self.q_lora_rank = q_lora_rank
178
+ self.qk_rope_head_dim = qk_rope_head_dim
179
+ self.v_head_dim = v_head_dim
180
+ self.qk_nope_head_dim = qk_nope_head_dim
181
+ self.topk_method = topk_method
182
+ self.n_group = n_group
183
+ self.topk_group = topk_group
184
+ self.num_experts_per_tok = num_experts_per_tok
185
+ self.moe_layer_freq = moe_layer_freq
186
+ self.first_k_dense_replace = first_k_dense_replace
187
+ self.norm_topk_prob = norm_topk_prob
188
+ self.scoring_func = scoring_func
189
+ self.aux_loss_alpha = aux_loss_alpha
190
+ self.seq_aux = seq_aux
191
+ # for backward compatibility
192
+ if num_key_value_heads is None:
193
+ num_key_value_heads = num_attention_heads
194
+
195
+ self.num_key_value_heads = num_key_value_heads
196
+ self.hidden_act = hidden_act
197
+ self.initializer_range = initializer_range
198
+ self.rms_norm_eps = rms_norm_eps
199
+ self.pretraining_tp = pretraining_tp
200
+ self.use_cache = use_cache
201
+ self.rope_theta = rope_theta
202
+ self.rope_scaling = rope_scaling
203
+ self.attention_bias = attention_bias
204
+ self.attention_dropout = attention_dropout
205
+
206
+ super().__init__(
207
+ pad_token_id=pad_token_id,
208
+ bos_token_id=bos_token_id,
209
+ eos_token_id=eos_token_id,
210
+ tie_word_embeddings=tie_word_embeddings,
211
+ **kwargs,
212
+ )
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 100000,
4
+ "do_sample": true,
5
+ "eos_token_id": 100001,
6
+ "temperature": 0.3,
7
+ "top_p": 0.95,
8
+ "transformers_version": "4.47.1"
9
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09123eb294c486fc6f5b43eec1472f882ee601aad32b6fe13ff5a574dc18c5d8
3
+ size 3806432968
modeling_deepseek.py ADDED
@@ -0,0 +1,2082 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch DeepSeek model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ )
38
+ from transformers.modeling_outputs import (
39
+ BaseModelOutputWithPast,
40
+ CausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import (
45
+ ALL_LAYERNORM_LAYERS,
46
+ is_torch_greater_or_equal_than_1_13,
47
+ )
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from transformers.utils.import_utils import is_torch_fx_available
57
+
58
+ try:
59
+ from .configuration_deepseek import DeepseekV2Config
60
+ except:
61
+ from .configuration_deepseek_fused_v2 import DeepseekV2Config
62
+
63
+
64
+ import torch.distributed as dist
65
+ import numpy as np
66
+
67
+ if is_flash_attn_2_available():
68
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
69
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
70
+
71
+
72
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
73
+ # It means that the function will not be traced through and simply appear as a node in the graph.
74
+ if is_torch_fx_available():
75
+ if not is_torch_greater_or_equal_than_1_13:
76
+ import torch.fx
77
+
78
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
79
+
80
+
81
+ logger = logging.get_logger(__name__)
82
+
83
+ _CONFIG_FOR_DOC = "DeepseekV2Config"
84
+
85
+
86
+ def _get_unpad_data(attention_mask):
87
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
88
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
89
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
90
+ cu_seqlens = F.pad(
91
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
92
+ )
93
+ return (
94
+ indices,
95
+ cu_seqlens,
96
+ max_seqlen_in_batch,
97
+ )
98
+
99
+
100
+ class DeepseekV2RMSNorm(nn.Module):
101
+ def __init__(self, hidden_size, eps=1e-6):
102
+ """
103
+ DeepseekV2RMSNorm is equivalent to T5LayerNorm
104
+ """
105
+ super().__init__()
106
+ self.weight = nn.Parameter(torch.ones(hidden_size))
107
+ self.variance_epsilon = eps
108
+
109
+ def forward(self, hidden_states):
110
+ input_dtype = hidden_states.dtype
111
+ hidden_states = hidden_states.to(torch.float32)
112
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
113
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
114
+ return self.weight * hidden_states.to(input_dtype)
115
+
116
+
117
+ ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
118
+
119
+
120
+ class DeepseekV2RotaryEmbedding(nn.Module):
121
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
122
+ super().__init__()
123
+
124
+ self.dim = dim
125
+ self.max_position_embeddings = max_position_embeddings
126
+ self.base = base
127
+ inv_freq = 1.0 / (
128
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
129
+ )
130
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
131
+
132
+ # Build here to make `torch.jit.trace` work.
133
+ self._set_cos_sin_cache(
134
+ seq_len=max_position_embeddings,
135
+ device=self.inv_freq.device,
136
+ dtype=torch.get_default_dtype(),
137
+ )
138
+ self.max_seq_len_cached = None
139
+
140
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
141
+ self.max_seq_len_cached = seq_len
142
+ t = torch.arange(
143
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
144
+ )
145
+
146
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
147
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
148
+ emb = torch.cat((freqs, freqs), dim=-1)
149
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
150
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
151
+
152
+ def forward(self, x, seq_len=None):
153
+ # x: [bs, num_attention_heads, seq_len, head_size]
154
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
155
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
156
+
157
+ return (
158
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
159
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
160
+ )
161
+
162
+
163
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2
164
+ class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
165
+ """DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
166
+
167
+ def __init__(
168
+ self,
169
+ dim,
170
+ max_position_embeddings=2048,
171
+ base=10000,
172
+ device=None,
173
+ scaling_factor=1.0,
174
+ ):
175
+ self.scaling_factor = scaling_factor
176
+ super().__init__(dim, max_position_embeddings, base, device)
177
+
178
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
179
+ self.max_seq_len_cached = seq_len
180
+ t = torch.arange(
181
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
182
+ )
183
+ t = t / self.scaling_factor
184
+
185
+ freqs = torch.outer(t, self.inv_freq)
186
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
187
+ emb = torch.cat((freqs, freqs), dim=-1)
188
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
189
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
190
+
191
+
192
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2
193
+ class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
194
+ """DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
195
+
196
+ def __init__(
197
+ self,
198
+ dim,
199
+ max_position_embeddings=2048,
200
+ base=10000,
201
+ device=None,
202
+ scaling_factor=1.0,
203
+ ):
204
+ self.scaling_factor = scaling_factor
205
+ super().__init__(dim, max_position_embeddings, base, device)
206
+
207
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
208
+ self.max_seq_len_cached = seq_len
209
+
210
+ if seq_len > self.max_position_embeddings:
211
+ base = self.base * (
212
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
213
+ - (self.scaling_factor - 1)
214
+ ) ** (self.dim / (self.dim - 2))
215
+ inv_freq = 1.0 / (
216
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
217
+ )
218
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
219
+
220
+ t = torch.arange(
221
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
222
+ )
223
+
224
+ freqs = torch.outer(t, self.inv_freq)
225
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
226
+ emb = torch.cat((freqs, freqs), dim=-1)
227
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
228
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
229
+
230
+
231
+ # Inverse dim formula to find dim based on number of rotations
232
+ def yarn_find_correction_dim(
233
+ num_rotations, dim, base=10000, max_position_embeddings=2048
234
+ ):
235
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
236
+ 2 * math.log(base)
237
+ )
238
+
239
+
240
+ # Find dim range bounds based on rotations
241
+ def yarn_find_correction_range(
242
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
243
+ ):
244
+ low = math.floor(
245
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
246
+ )
247
+ high = math.ceil(
248
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
249
+ )
250
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
251
+
252
+
253
+ def yarn_get_mscale(scale=1, mscale=1):
254
+ if scale <= 1:
255
+ return 1.0
256
+ return 0.1 * mscale * math.log(scale) + 1.0
257
+
258
+
259
+ def yarn_linear_ramp_mask(min, max, dim):
260
+ if min == max:
261
+ max += 0.001 # Prevent singularity
262
+
263
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
264
+ ramp_func = torch.clamp(linear_func, 0, 1)
265
+ return ramp_func
266
+
267
+
268
+ class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
269
+
270
+ def __init__(
271
+ self,
272
+ dim,
273
+ max_position_embeddings=2048,
274
+ base=10000,
275
+ device=None,
276
+ scaling_factor=1.0,
277
+ original_max_position_embeddings=4096,
278
+ beta_fast=32,
279
+ beta_slow=1,
280
+ mscale=1,
281
+ mscale_all_dim=0,
282
+ ):
283
+ self.scaling_factor = scaling_factor
284
+ self.original_max_position_embeddings = original_max_position_embeddings
285
+ self.beta_fast = beta_fast
286
+ self.beta_slow = beta_slow
287
+ self.mscale = mscale
288
+ self.mscale_all_dim = mscale_all_dim
289
+ super().__init__(dim, max_position_embeddings, base, device)
290
+
291
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
292
+ self.max_seq_len_cached = seq_len
293
+ dim = self.dim
294
+
295
+ freq_extra = 1.0 / (
296
+ self.base
297
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
298
+ )
299
+ freq_inter = 1.0 / (
300
+ self.scaling_factor
301
+ * self.base
302
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
303
+ )
304
+
305
+ low, high = yarn_find_correction_range(
306
+ self.beta_fast,
307
+ self.beta_slow,
308
+ dim,
309
+ self.base,
310
+ self.original_max_position_embeddings,
311
+ )
312
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
313
+ device=device, dtype=torch.float32
314
+ )
315
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
316
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
317
+
318
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
319
+
320
+ freqs = torch.outer(t, inv_freq)
321
+
322
+ _mscale = float(
323
+ yarn_get_mscale(self.scaling_factor, self.mscale)
324
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
325
+ )
326
+
327
+ emb = torch.cat((freqs, freqs), dim=-1)
328
+ self.register_buffer(
329
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
330
+ )
331
+ self.register_buffer(
332
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
333
+ )
334
+
335
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
336
+ def rotate_half(x):
337
+ """Rotates half the hidden dims of the input."""
338
+ x1 = x[..., : x.shape[-1] // 2]
339
+ x2 = x[..., x.shape[-1] // 2 :]
340
+ return torch.cat((-x2, x1), dim=-1)
341
+
342
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
343
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
344
+ """Applies Rotary Position Embedding to the query and key tensors.
345
+
346
+ Args:
347
+ q (`torch.Tensor`): The query tensor.
348
+ k (`torch.Tensor`): The key tensor.
349
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
350
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
351
+ position_ids (`torch.Tensor`):
352
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
353
+ used to pass offsetted position ids when working with a KV-cache.
354
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
355
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
356
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
357
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
358
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
359
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
360
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
361
+ Returns:
362
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
363
+ """
364
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
365
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
366
+
367
+ b, h, s, d = q.shape
368
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
369
+
370
+ b, h, s, d = k.shape
371
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
372
+
373
+ q_embed = (q * cos) + (rotate_half(q) * sin)
374
+ k_embed = (k * cos) + (rotate_half(k) * sin)
375
+ return q_embed, k_embed
376
+
377
+ class DeepseekV2MLP(nn.Module):
378
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
379
+ super().__init__()
380
+ self.config = config
381
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
382
+ self.intermediate_size = (
383
+ config.intermediate_size if intermediate_size is None else intermediate_size
384
+ )
385
+
386
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
387
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
388
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
389
+ self.act_fn = ACT2FN[config.hidden_act]
390
+
391
+ def forward(self, x):
392
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
393
+ return down_proj
394
+
395
+ class FusedLinear(nn.Module):
396
+ def __init__(self, in_features, out_features, rank=8, alpha=1, n_fused=4, adapter_type="mixture", bias=False, **kwargs):
397
+ super().__init__()
398
+
399
+ self.rank = rank
400
+ self.adapter_type = adapter_type
401
+ self.fused_layer = nn.Linear(in_features, out_features, bias=bias)
402
+
403
+ if self.adapter_type == 'lora':
404
+ self.qa_weights = nn.Parameter(torch.randn(rank, in_features) * 0.02)
405
+ self.qb_weights = nn.Parameter(torch.randn(out_features, rank) * 0.02)
406
+ self.mask_up_proj = nn.Parameter(torch.randn(n_fused, rank) * 0.02)
407
+ self.scaling_factor = nn.Parameter(torch.Tensor([0.1] * out_features))
408
+
409
+ if self.adapter_type == 'mixture':
410
+ self.n_fused = n_fused
411
+ # For efficient forward pass, create weight tensors
412
+ self.qa_weights = nn.Parameter(torch.stack([torch.zeros(rank, in_features) for i in range(n_fused)]))
413
+ self.qb_weights = nn.Parameter(torch.stack([torch.zeros(out_features, rank) for i in range(n_fused)]))
414
+ self.scaling_factor = nn.Parameter(torch.Tensor([0.1] * out_features))
415
+
416
+ def forward(self, x, top_k_weights):
417
+ output = self.fused_layer(x)
418
+
419
+ if self.adapter_type == 'lora':
420
+ x = torch.einsum('bh,rh->br', x, self.qa_weights)
421
+ x = torch.einsum('br,brr->br', x, torch.diag_embed(torch.einsum('bk,kr -> br', top_k_weights, self.mask_up_proj)))
422
+ x = torch.einsum('br,hr ->bh', x, self.qb_weights)
423
+ output = output + self.scaling_factor[None] * x
424
+
425
+ if self.adapter_type == 'mixture':
426
+ if len(x.shape) == 2:
427
+ x = torch.einsum('bh,krh->bkr', x, self.qa_weights)
428
+ x = torch.einsum('bkr,khr->bkh', x, self.qb_weights)
429
+ x = torch.einsum('bkh,bk->bkh', x, top_k_weights)
430
+ x = torch.sum(x, dim=1)
431
+ output=output + self.scaling_factor[None] * x
432
+ return output
433
+
434
+ class FusedMLP(torch.nn.Module):
435
+ def __init__(self, config, hidden_size=None, intermediate_size=None, n_fused=4, rank=8, adapter_type='mixture'):
436
+ super().__init__()
437
+ self.config = config
438
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
439
+ self.intermediate_size = (
440
+ config.moe_intermediate_size if intermediate_size is None else intermediate_size
441
+ )
442
+ self.n_fused=n_fused
443
+ self.gate_proj = FusedLinear(self.hidden_size, self.intermediate_size, bias=False, rank=rank, n_fused=n_fused, adapter_type=adapter_type)
444
+ self.up_proj = FusedLinear(self.hidden_size, self.intermediate_size, bias=False, rank=rank, n_fused=n_fused, adapter_type=adapter_type)
445
+ self.down_proj = FusedLinear(self.intermediate_size, self.hidden_size, bias=False, rank=rank, n_fused=n_fused, adapter_type=adapter_type)
446
+ self.mask_up_proj = torch.nn.Linear(self.n_fused, self.hidden_size, bias=False)
447
+ self.act_fn = ACT2FN[config.hidden_act]
448
+ self.adapter_type=adapter_type
449
+
450
+ def forward(self, x, top_k_weights):
451
+ x = x + self.mask_up_proj(top_k_weights)
452
+ 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)
453
+ return down_proj
454
+
455
+ class MoEGate(nn.Module):
456
+ def __init__(self, config):
457
+ super().__init__()
458
+ self.config = config
459
+ self.top_k = config.num_experts_per_tok
460
+ self.n_routed_experts = config.n_routed_experts
461
+ self.routed_scaling_factor = config.routed_scaling_factor
462
+ self.scoring_func = config.scoring_func
463
+ self.alpha = config.aux_loss_alpha
464
+ self.seq_aux = config.seq_aux
465
+ self.topk_method = config.topk_method
466
+ self.n_group = config.n_group
467
+ self.topk_group = config.topk_group
468
+
469
+ # topk selection algorithm
470
+ self.norm_topk_prob = config.norm_topk_prob
471
+ self.gating_dim = config.hidden_size
472
+ self.weight = nn.Parameter(
473
+ torch.empty((self.n_routed_experts, self.gating_dim))
474
+ )
475
+ self.reset_parameters()
476
+
477
+ def reset_parameters(self) -> None:
478
+ import torch.nn.init as init
479
+
480
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
481
+
482
+ def forward(self, hidden_states):
483
+ bsz, seq_len, h = hidden_states.shape
484
+ ### compute gating score
485
+ hidden_states = hidden_states.view(-1, h)
486
+ logits = F.linear(
487
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
488
+ )
489
+ if self.scoring_func == "softmax":
490
+ scores = logits.softmax(dim=-1, dtype=torch.float32)
491
+ else:
492
+ raise NotImplementedError(
493
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
494
+ )
495
+
496
+ ### select top-k experts
497
+ if self.topk_method == "greedy":
498
+ topk_weight, topk_idx = torch.topk(
499
+ scores, k=self.top_k, dim=-1, sorted=False
500
+ )
501
+ elif self.topk_method == "group_limited_greedy":
502
+ group_scores = (
503
+ scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
504
+ ) # [n, n_group]
505
+ group_idx = torch.topk(
506
+ group_scores, k=self.topk_group, dim=-1, sorted=False
507
+ )[
508
+ 1
509
+ ] # [n, top_k_group]
510
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
511
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
512
+ score_mask = (
513
+ group_mask.unsqueeze(-1)
514
+ .expand(
515
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
516
+ )
517
+ .reshape(bsz * seq_len, -1)
518
+ ) # [n, e]
519
+ tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
520
+ topk_weight, topk_idx = torch.topk(
521
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
522
+ )
523
+
524
+ ### norm gate to sum 1
525
+ if self.top_k > 1 and self.norm_topk_prob:
526
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
527
+ topk_weight = topk_weight / denominator
528
+ else:
529
+ topk_weight = topk_weight * self.routed_scaling_factor
530
+ ### expert-level computation auxiliary loss
531
+ if self.training and self.alpha > 0.0:
532
+ scores_for_aux = scores
533
+ aux_topk = self.top_k
534
+ # always compute aux loss based on the naive greedy topk method
535
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
536
+ if self.seq_aux:
537
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
538
+ ce = torch.zeros(
539
+ bsz, self.n_routed_experts, device=hidden_states.device
540
+ )
541
+ ce.scatter_add_(
542
+ 1,
543
+ topk_idx_for_aux_loss,
544
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
545
+ ).div_(seq_len * aux_topk / self.n_routed_experts)
546
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
547
+ dim=1
548
+ ).mean() * self.alpha
549
+ else:
550
+ mask_ce = F.one_hot(
551
+ topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
552
+ )
553
+ ce = mask_ce.float().mean(0)
554
+ Pi = scores_for_aux.mean(0)
555
+ fi = ce * self.n_routed_experts
556
+ aux_loss = (Pi * fi).sum() * self.alpha
557
+ else:
558
+ aux_loss = None
559
+ return topk_idx, topk_weight, aux_loss
560
+
561
+ class AddAuxiliaryLoss(torch.autograd.Function):
562
+ """
563
+ The trick function of adding auxiliary (aux) loss,
564
+ which includes the gradient of the aux loss during backpropagation.
565
+ """
566
+
567
+ @staticmethod
568
+ def forward(ctx, x, loss):
569
+ assert loss.numel() == 1
570
+ ctx.dtype = loss.dtype
571
+ ctx.required_aux_loss = loss.requires_grad
572
+ return x
573
+
574
+ @staticmethod
575
+ def backward(ctx, grad_output):
576
+ grad_loss = None
577
+ if ctx.required_aux_loss:
578
+ grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
579
+ return grad_output, grad_loss
580
+
581
+ class DeepseekV2MoE(nn.Module):
582
+ """
583
+ A mixed expert module containing shared experts.
584
+ """
585
+
586
+ def __init__(self, config):
587
+ super().__init__()
588
+ self.config = config
589
+ self.num_experts_per_tok = config.num_experts_per_tok
590
+
591
+ if hasattr(config, "ep_size") and config.ep_size > 1:
592
+ assert config.ep_size == dist.get_world_size()
593
+ self.ep_size = config.ep_size
594
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
595
+ self.ep_rank = dist.get_rank()
596
+ self.experts = nn.ModuleList(
597
+ [
598
+ (
599
+ DeepseekV2MLP(
600
+ config, intermediate_size=config.moe_intermediate_size
601
+ )
602
+ if i >= self.ep_rank * self.experts_per_rank
603
+ and i < (self.ep_rank + 1) * self.experts_per_rank
604
+ else None
605
+ )
606
+ for i in range(config.n_routed_experts)
607
+ ]
608
+ )
609
+ else:
610
+ self.ep_size = 1
611
+ self.experts_per_rank = config.n_routed_experts
612
+ self.ep_rank = 0
613
+ self.experts = nn.ModuleList(
614
+ [
615
+ DeepseekV2MLP(config, intermediate_size=config.moe_intermediate_size)
616
+ for i in range(config.n_routed_experts)
617
+ ]
618
+ )
619
+ self.gate = MoEGate(config)
620
+ if config.n_shared_experts is not None:
621
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
622
+ self.shared_experts = DeepseekV2MLP(
623
+ config=config, intermediate_size=intermediate_size
624
+ )
625
+
626
+ def forward(self, hidden_states):
627
+ identity = hidden_states
628
+ orig_shape = hidden_states.shape
629
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
630
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
631
+ flat_topk_idx = topk_idx.view(-1)
632
+ if self.training:
633
+ hidden_states = hidden_states.repeat_interleave(
634
+ self.num_experts_per_tok, dim=0
635
+ )
636
+
637
+ y = torch.empty_like(hidden_states)
638
+ for i, expert in enumerate(self.experts):
639
+ expert_output=expert(hidden_states[flat_topk_idx == i])
640
+ try:
641
+ y[flat_topk_idx == i] = expert_output.to(y.dtype)
642
+ except:
643
+ pass
644
+
645
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
646
+ y = y.view(*orig_shape)
647
+ y = AddAuxiliaryLoss.apply(y, aux_loss)
648
+ else:
649
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
650
+ if self.config.n_shared_experts is not None:
651
+ y = y + self.shared_experts(identity)
652
+ return y
653
+
654
+ @torch.no_grad()
655
+ def moe_infer(self, x, topk_ids, topk_weight):
656
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
657
+ cnts.scatter_(1, topk_ids, 1)
658
+ tokens_per_expert = cnts.sum(dim=0)
659
+ idxs = topk_ids.view(-1).argsort()
660
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
661
+ sorted_tokens_shape = sorted_tokens.shape
662
+ if self.ep_size > 1:
663
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
664
+ tokens_per_expert_group = tokens_per_expert.new_empty(
665
+ tokens_per_expert.shape[0]
666
+ )
667
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
668
+ output_splits = (
669
+ tokens_per_expert_group.view(self.ep_size, -1)
670
+ .sum(1)
671
+ .cpu()
672
+ .numpy()
673
+ .tolist()
674
+ )
675
+ gathered_tokens = sorted_tokens.new_empty(
676
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
677
+ )
678
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
679
+ dist.all_to_all(
680
+ list(gathered_tokens.split(output_splits)),
681
+ list(sorted_tokens.split(input_split_sizes)),
682
+ )
683
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
684
+ self.ep_size, self.experts_per_rank
685
+ ).sum(dim=0)
686
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
687
+ s = 0
688
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
689
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
690
+ s += k
691
+ gatherd_idxs = gatherd_idxs.argsort()
692
+ sorted_tokens = gathered_tokens[gatherd_idxs]
693
+ tokens_per_expert = tokens_per_expert_post_gather
694
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
695
+
696
+ outputs = []
697
+ start_idx = 0
698
+ for i, num_tokens in enumerate(tokens_per_expert):
699
+ end_idx = start_idx + num_tokens
700
+ if num_tokens == 0:
701
+ continue
702
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
703
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
704
+ expert_out = expert(tokens_for_this_expert)
705
+ outputs.append(expert_out)
706
+ start_idx = end_idx
707
+
708
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
709
+ if self.ep_size > 1:
710
+ new_x = torch.empty_like(outs)
711
+ new_x[gatherd_idxs] = outs
712
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
713
+ dist.all_to_all(
714
+ list(gathered_tokens.split(input_split_sizes)),
715
+ list(new_x.split(output_splits)),
716
+ )
717
+ outs = gathered_tokens
718
+
719
+ new_x = torch.empty_like(outs)
720
+ new_x[idxs] = outs
721
+ final_out = (
722
+ new_x.view(*topk_ids.shape, -1)
723
+ .type(topk_weight.dtype)
724
+ .mul_(topk_weight.unsqueeze(dim=-1))
725
+ .sum(dim=1)
726
+ .type(new_x.dtype)
727
+ )
728
+ return final_out
729
+
730
+ class FusedMOE(torch.nn.Module):
731
+ def __init__(self, config):
732
+ super().__init__()
733
+ self.config = config
734
+ self.num_experts_per_tok = config.num_experts_per_tok
735
+
736
+ if hasattr(config, "ep_size") and config.ep_size > 1:
737
+ assert config.ep_size == dist.get_world_size()
738
+ self.ep_size = config.ep_size
739
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
740
+ self.ep_rank = dist.get_rank()
741
+ self.experts = nn.ModuleList(
742
+ [
743
+ (
744
+ FusedMLP(
745
+ config,
746
+ intermediate_size=config.moe_intermediate_size,
747
+ n_fused=config.n_routed_experts // config.n_fused_experts,
748
+ rank=config.fused_expert_dora_rank,
749
+ adapter_type=config.fused_expert_method
750
+ )
751
+ if i >= self.ep_rank * self.experts_per_rank
752
+ and i < (self.ep_rank + 1) * self.experts_per_rank
753
+ else None
754
+ )
755
+ for i in range(config.n_fused_experts)
756
+ ]
757
+ )
758
+ else:
759
+ self.ep_size = 1
760
+ self.experts_per_rank = config.n_routed_experts
761
+ self.ep_rank = 0
762
+ self.experts = nn.ModuleList(
763
+ [
764
+ FusedMLP(
765
+ config,
766
+ intermediate_size=config.moe_intermediate_size,
767
+ n_fused=config.n_routed_experts // config.n_fused_experts,
768
+ rank=config.fused_expert_dora_rank,
769
+ adapter_type=config.fused_expert_method
770
+ )
771
+ for i in range(config.n_fused_experts)
772
+ ]
773
+ )
774
+ self.gate = MoEGate(config)
775
+ if config.n_shared_experts is not None:
776
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
777
+ self.shared_experts = DeepseekV2MLP(
778
+ config=config, intermediate_size=intermediate_size
779
+ )
780
+
781
+ # Register inv_mapping_dict as a buffer
782
+ self.register_buffer('inv_mapping_dict', torch.zeros(config.n_fused_experts, config.n_routed_experts // config.n_fused_experts), persistent=True)
783
+
784
+
785
+ def set_ready(self):
786
+ self.experts.to_empty(device="meta")
787
+ del self.experts
788
+ self.ready = True
789
+
790
+ def forward(self, hidden_states):
791
+ identity, orig_shape, hidden_states, topk_idx, topk_weight, aux_loss = self.forward_gate(hidden_states)
792
+
793
+ y = torch.zeros_like(hidden_states, device=hidden_states.device, dtype=hidden_states.dtype)
794
+
795
+ for idx in range(self.inv_mapping_dict.size(0)):
796
+ y += self.forward_fused_expert(idx, hidden_states, topk_idx, topk_weight)
797
+
798
+ y = y.view(*orig_shape)
799
+
800
+ if self.config.n_shared_experts is not None:
801
+ y = y + self.shared_experts(identity)
802
+ return y
803
+
804
+ def forward_gate(self, hidden_states):
805
+ identity = hidden_states
806
+ orig_shape = hidden_states.shape
807
+
808
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
809
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
810
+
811
+ return identity, orig_shape, hidden_states, topk_idx, topk_weight, aux_loss
812
+
813
+ def forward_fused_expert(self, idx, hidden_states, topk_idx, topk_weight):
814
+ indexes = self.inv_mapping_dict[idx].tolist()
815
+
816
+ flat_topk_weight = torch.zeros((hidden_states.shape[0], len(indexes)), device=hidden_states.device, dtype=hidden_states.dtype)
817
+
818
+ for i, index in enumerate(indexes):
819
+ flat_topk_weight[:, i] = torch.sum(topk_weight * (topk_idx == index), axis=-1)
820
+
821
+ scalar = torch.sum(flat_topk_weight, axis=-1, keepdim=True) # keeping the total weight of the experts
822
+
823
+ flat_topk_weight[flat_topk_weight == 0] = -1e9
824
+ flat_topk_weight = torch.softmax(flat_topk_weight, dim=-1)
825
+
826
+ output = torch.zeros_like(hidden_states, device=hidden_states.device, dtype=hidden_states.dtype)
827
+
828
+ 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
829
+
830
+ return scalar * output # Weighting is already taken into account by how the Fused is trained
831
+
832
+
833
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
834
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
835
+ """
836
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
837
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
838
+ """
839
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
840
+ if n_rep == 1:
841
+ return hidden_states
842
+ hidden_states = hidden_states[:, :, None, :, :].expand(
843
+ batch, num_key_value_heads, n_rep, slen, head_dim
844
+ )
845
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
846
+
847
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2
848
+ class DeepseekV2Attention(nn.Module):
849
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
850
+
851
+ def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None):
852
+ super().__init__()
853
+ self.config = config
854
+ self.layer_idx = layer_idx
855
+ if layer_idx is None:
856
+ logger.warning_once(
857
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
858
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
859
+ "when creating this class."
860
+ )
861
+
862
+ self.attention_dropout = config.attention_dropout
863
+ self.hidden_size = config.hidden_size
864
+ self.num_heads = config.num_attention_heads
865
+
866
+ self.max_position_embeddings = config.max_position_embeddings
867
+ self.rope_theta = config.rope_theta
868
+ self.q_lora_rank = config.q_lora_rank
869
+ self.qk_rope_head_dim = config.qk_rope_head_dim
870
+ self.kv_lora_rank = config.kv_lora_rank
871
+ self.v_head_dim = config.v_head_dim
872
+ self.qk_nope_head_dim = config.qk_nope_head_dim
873
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
874
+
875
+ self.is_causal = True
876
+
877
+ if self.q_lora_rank is None:
878
+ self.q_proj = nn.Linear(
879
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
880
+ )
881
+ else:
882
+ self.q_a_proj = nn.Linear(
883
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
884
+ )
885
+ self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank)
886
+ self.q_b_proj = nn.Linear(
887
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
888
+ )
889
+
890
+ self.kv_a_proj_with_mqa = nn.Linear(
891
+ self.hidden_size,
892
+ config.kv_lora_rank + config.qk_rope_head_dim,
893
+ bias=config.attention_bias,
894
+ )
895
+ self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank)
896
+ self.kv_b_proj = nn.Linear(
897
+ config.kv_lora_rank,
898
+ self.num_heads
899
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
900
+ bias=False,
901
+ )
902
+
903
+ self.o_proj = nn.Linear(
904
+ self.num_heads * self.v_head_dim,
905
+ self.hidden_size,
906
+ bias=config.attention_bias,
907
+ )
908
+ self._init_rope()
909
+
910
+ self.softmax_scale = self.q_head_dim ** (-0.5)
911
+ if self.config.rope_scaling is not None:
912
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
913
+ scaling_factor = self.config.rope_scaling["factor"]
914
+ if mscale_all_dim:
915
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
916
+ self.softmax_scale = self.softmax_scale * mscale * mscale
917
+
918
+ def _init_rope(self):
919
+ if self.config.rope_scaling is None:
920
+ self.rotary_emb = DeepseekV2RotaryEmbedding(
921
+ self.qk_rope_head_dim,
922
+ max_position_embeddings=self.max_position_embeddings,
923
+ base=self.rope_theta,
924
+ )
925
+ else:
926
+ scaling_type = self.config.rope_scaling["type"]
927
+ scaling_factor = self.config.rope_scaling["factor"]
928
+ if scaling_type == "linear":
929
+ self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
930
+ self.qk_rope_head_dim,
931
+ max_position_embeddings=self.max_position_embeddings,
932
+ scaling_factor=scaling_factor,
933
+ base=self.rope_theta,
934
+ )
935
+ elif scaling_type == "dynamic":
936
+ self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
937
+ self.qk_rope_head_dim,
938
+ max_position_embeddings=self.max_position_embeddings,
939
+ scaling_factor=scaling_factor,
940
+ base=self.rope_theta,
941
+ )
942
+ elif scaling_type == "yarn":
943
+ kwargs = {
944
+ key: self.config.rope_scaling[key]
945
+ for key in [
946
+ "original_max_position_embeddings",
947
+ "beta_fast",
948
+ "beta_slow",
949
+ "mscale",
950
+ "mscale_all_dim",
951
+ ]
952
+ if key in self.config.rope_scaling
953
+ }
954
+ self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
955
+ self.qk_rope_head_dim,
956
+ max_position_embeddings=self.max_position_embeddings,
957
+ scaling_factor=scaling_factor,
958
+ base=self.rope_theta,
959
+ **kwargs,
960
+ )
961
+ else:
962
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
963
+
964
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
965
+ return (
966
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
967
+ .transpose(1, 2)
968
+ .contiguous()
969
+ )
970
+
971
+ def forward(
972
+ self,
973
+ hidden_states: torch.Tensor,
974
+ attention_mask: Optional[torch.Tensor] = None,
975
+ position_ids: Optional[torch.LongTensor] = None,
976
+ past_key_value: Optional[Cache] = None,
977
+ output_attentions: bool = False,
978
+ use_cache: bool = False,
979
+ **kwargs,
980
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
981
+ if "padding_mask" in kwargs:
982
+ warnings.warn(
983
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
984
+ )
985
+ bsz, q_len, _ = hidden_states.size()
986
+
987
+ if self.q_lora_rank is None:
988
+ q = self.q_proj(hidden_states)
989
+ else:
990
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
991
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
992
+ q_nope, q_pe = torch.split(
993
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
994
+ )
995
+
996
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
997
+ compressed_kv, k_pe = torch.split(
998
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
999
+ )
1000
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1001
+ kv = (
1002
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1003
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1004
+ .transpose(1, 2)
1005
+ )
1006
+
1007
+ k_nope, value_states = torch.split(
1008
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1009
+ )
1010
+ kv_seq_len = value_states.shape[-2]
1011
+ if past_key_value is not None:
1012
+ if self.layer_idx is None:
1013
+ raise ValueError(
1014
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
1015
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
1016
+ "with a layer index."
1017
+ )
1018
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1019
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1020
+
1021
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1022
+
1023
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1024
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1025
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1026
+
1027
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1028
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1029
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1030
+ if past_key_value is not None:
1031
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1032
+ key_states, value_states = past_key_value.update(
1033
+ key_states, value_states, self.layer_idx, cache_kwargs
1034
+ )
1035
+
1036
+ attn_weights = (
1037
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
1038
+ )
1039
+
1040
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
1041
+ raise ValueError(
1042
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
1043
+ f" {attn_weights.size()}"
1044
+ )
1045
+ assert attention_mask is not None
1046
+ if attention_mask is not None:
1047
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1048
+ raise ValueError(
1049
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1050
+ )
1051
+ attn_weights = attn_weights + attention_mask
1052
+
1053
+ # upcast attention to fp32
1054
+ attn_weights = nn.functional.softmax(
1055
+ attn_weights, dim=-1, dtype=torch.float32
1056
+ ).to(query_states.dtype)
1057
+ attn_weights = nn.functional.dropout(
1058
+ attn_weights, p=self.attention_dropout, training=self.training
1059
+ )
1060
+ attn_output = torch.matmul(attn_weights, value_states)
1061
+
1062
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
1063
+ raise ValueError(
1064
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
1065
+ f" {attn_output.size()}"
1066
+ )
1067
+
1068
+ attn_output = attn_output.transpose(1, 2).contiguous()
1069
+
1070
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
1071
+
1072
+ attn_output = self.o_proj(attn_output)
1073
+
1074
+ if not output_attentions:
1075
+ attn_weights = None
1076
+
1077
+ return attn_output, attn_weights, past_key_value
1078
+
1079
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2
1080
+ class DeepseekV2FlashAttention2(DeepseekV2Attention):
1081
+ """
1082
+ DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
1083
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
1084
+ flash attention and deal with padding tokens in case the input contains any of them.
1085
+ """
1086
+
1087
+ def __init__(self, *args, **kwargs):
1088
+ super().__init__(*args, **kwargs)
1089
+
1090
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1091
+ # 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.
1092
+ # 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).
1093
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1094
+
1095
+ def forward(
1096
+ self,
1097
+ hidden_states: torch.Tensor,
1098
+ attention_mask: Optional[torch.LongTensor] = None,
1099
+ position_ids: Optional[torch.LongTensor] = None,
1100
+ past_key_value: Optional[Cache] = None,
1101
+ output_attentions: bool = False,
1102
+ use_cache: bool = False,
1103
+ **kwargs,
1104
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1105
+ # DeepseekV2FlashAttention2 attention does not support output_attentions
1106
+ if "padding_mask" in kwargs:
1107
+ warnings.warn(
1108
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1109
+ )
1110
+
1111
+ # overwrite attention_mask with padding_mask
1112
+ attention_mask = kwargs.pop("padding_mask")
1113
+
1114
+ output_attentions = False
1115
+
1116
+ bsz, q_len, _ = hidden_states.size()
1117
+
1118
+ if self.q_lora_rank is None:
1119
+ q = self.q_proj(hidden_states)
1120
+ else:
1121
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1122
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1123
+ q_nope, q_pe = torch.split(
1124
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1125
+ )
1126
+
1127
+ # Flash attention requires the input to have the shape
1128
+ # batch_size x seq_length x head_dim x hidden_dim
1129
+ # therefore we just need to keep the original shape
1130
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1131
+ compressed_kv, k_pe = torch.split(
1132
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1133
+ )
1134
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1135
+ kv = (
1136
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1137
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1138
+ .transpose(1, 2)
1139
+ )
1140
+
1141
+ k_nope, value_states = torch.split(
1142
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1143
+ )
1144
+ kv_seq_len = value_states.shape[-2]
1145
+
1146
+ kv_seq_len = value_states.shape[-2]
1147
+ if past_key_value is not None:
1148
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1149
+
1150
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1151
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1152
+
1153
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1154
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1155
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1156
+
1157
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1158
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1159
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1160
+
1161
+ if self.q_head_dim != self.v_head_dim:
1162
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1163
+
1164
+ if past_key_value is not None:
1165
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1166
+ key_states, value_states = past_key_value.update(
1167
+ key_states, value_states, self.layer_idx, cache_kwargs
1168
+ )
1169
+
1170
+ # 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
1171
+ # to be able to avoid many of these transpose/reshape/view.
1172
+ query_states = query_states.transpose(1, 2)
1173
+ key_states = key_states.transpose(1, 2)
1174
+ value_states = value_states.transpose(1, 2)
1175
+
1176
+ dropout_rate = self.attention_dropout if self.training else 0.0
1177
+
1178
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1179
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1180
+ # cast them back in the correct dtype just to be sure everything works as expected.
1181
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1182
+ # in fp32. (DeepseekV2RMSNorm handles it correctly)
1183
+
1184
+ input_dtype = query_states.dtype
1185
+ if input_dtype == torch.float32:
1186
+ # Handle the case where the model is quantized
1187
+ if hasattr(self.config, "_pre_quantization_dtype"):
1188
+ target_dtype = self.config._pre_quantization_dtype
1189
+ elif torch.is_autocast_enabled():
1190
+ target_dtype = torch.get_autocast_gpu_dtype()
1191
+ else:
1192
+ target_dtype = self.q_proj.weight.dtype if self.q_lora_rank is None else self.q_a_proj.weight.dtype
1193
+
1194
+ logger.warning_once(
1195
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1196
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1197
+ f" {target_dtype}."
1198
+ )
1199
+
1200
+ query_states = query_states.to(target_dtype)
1201
+ key_states = key_states.to(target_dtype)
1202
+ value_states = value_states.to(target_dtype)
1203
+
1204
+ attn_output = self._flash_attention_forward(
1205
+ query_states,
1206
+ key_states,
1207
+ value_states,
1208
+ attention_mask,
1209
+ q_len,
1210
+ dropout=dropout_rate,
1211
+ softmax_scale=self.softmax_scale,
1212
+ )
1213
+ if self.q_head_dim != self.v_head_dim:
1214
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1215
+
1216
+ attn_output = attn_output.reshape(
1217
+ bsz, q_len, self.num_heads * self.v_head_dim
1218
+ ).contiguous()
1219
+ attn_output = self.o_proj(attn_output)
1220
+
1221
+ if not output_attentions:
1222
+ attn_weights = None
1223
+
1224
+ return attn_output, attn_weights, past_key_value
1225
+
1226
+ def _flash_attention_forward(
1227
+ self,
1228
+ query_states,
1229
+ key_states,
1230
+ value_states,
1231
+ attention_mask,
1232
+ query_length,
1233
+ dropout=0.0,
1234
+ softmax_scale=None,
1235
+ ):
1236
+ """
1237
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1238
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1239
+
1240
+ Args:
1241
+ query_states (`torch.Tensor`):
1242
+ Input query states to be passed to Flash Attention API
1243
+ key_states (`torch.Tensor`):
1244
+ Input key states to be passed to Flash Attention API
1245
+ value_states (`torch.Tensor`):
1246
+ Input value states to be passed to Flash Attention API
1247
+ attention_mask (`torch.Tensor`):
1248
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1249
+ position of padding tokens and 1 for the position of non-padding tokens.
1250
+ dropout (`int`, *optional*):
1251
+ Attention dropout
1252
+ softmax_scale (`float`, *optional*):
1253
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1254
+ """
1255
+ if not self._flash_attn_uses_top_left_mask:
1256
+ causal = self.is_causal
1257
+ else:
1258
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__.
1259
+ causal = self.is_causal and query_length != 1
1260
+
1261
+ # Contains at least one padding token in the sequence
1262
+ if attention_mask is not None:
1263
+ batch_size = query_states.shape[0]
1264
+ (
1265
+ query_states,
1266
+ key_states,
1267
+ value_states,
1268
+ indices_q,
1269
+ cu_seq_lens,
1270
+ max_seq_lens,
1271
+ ) = self._upad_input(
1272
+ query_states, key_states, value_states, attention_mask, query_length
1273
+ )
1274
+
1275
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1276
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1277
+
1278
+ attn_output_unpad = flash_attn_varlen_func(
1279
+ query_states,
1280
+ key_states,
1281
+ value_states,
1282
+ cu_seqlens_q=cu_seqlens_q,
1283
+ cu_seqlens_k=cu_seqlens_k,
1284
+ max_seqlen_q=max_seqlen_in_batch_q,
1285
+ max_seqlen_k=max_seqlen_in_batch_k,
1286
+ dropout_p=dropout,
1287
+ softmax_scale=softmax_scale,
1288
+ causal=causal,
1289
+ )
1290
+
1291
+ attn_output = pad_input(
1292
+ attn_output_unpad, indices_q, batch_size, query_length
1293
+ )
1294
+ else:
1295
+ attn_output = flash_attn_func(
1296
+ query_states,
1297
+ key_states,
1298
+ value_states,
1299
+ dropout,
1300
+ softmax_scale=softmax_scale,
1301
+ causal=causal,
1302
+ )
1303
+
1304
+ return attn_output
1305
+
1306
+ def _upad_input(
1307
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1308
+ ):
1309
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1310
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1311
+
1312
+ key_layer = index_first_axis(
1313
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1314
+ indices_k,
1315
+ )
1316
+ value_layer = index_first_axis(
1317
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1318
+ indices_k,
1319
+ )
1320
+ if query_length == kv_seq_len:
1321
+ query_layer = index_first_axis(
1322
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1323
+ indices_k,
1324
+ )
1325
+ cu_seqlens_q = cu_seqlens_k
1326
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1327
+ indices_q = indices_k
1328
+ elif query_length == 1:
1329
+ max_seqlen_in_batch_q = 1
1330
+ cu_seqlens_q = torch.arange(
1331
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1332
+ ) # There is a memcpy here, that is very bad.
1333
+ indices_q = cu_seqlens_q[:-1]
1334
+ query_layer = query_layer.squeeze(1)
1335
+ else:
1336
+ # The -q_len: slice assumes left padding.
1337
+ attention_mask = attention_mask[:, -query_length:]
1338
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1339
+ query_layer, attention_mask
1340
+ )
1341
+
1342
+ return (
1343
+ query_layer,
1344
+ key_layer,
1345
+ value_layer,
1346
+ indices_q,
1347
+ (cu_seqlens_q, cu_seqlens_k),
1348
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1349
+ )
1350
+
1351
+
1352
+ ATTENTION_CLASSES = {
1353
+ "eager": DeepseekV2Attention,
1354
+ "flash_attention_2": DeepseekV2FlashAttention2,
1355
+ }
1356
+
1357
+
1358
+ class DeepseekV2DecoderLayer(nn.Module):
1359
+ def __init__(self, config: DeepseekV2Config, layer_idx: int):
1360
+ super().__init__()
1361
+ self.hidden_size = config.hidden_size
1362
+
1363
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1364
+ config=config, layer_idx=layer_idx
1365
+ )
1366
+
1367
+ self.mlp = (
1368
+ FusedMOE(config)
1369
+ if (
1370
+ config.n_routed_experts is not None
1371
+ and layer_idx >= config.first_k_dense_replace
1372
+ and layer_idx % config.moe_layer_freq == 0
1373
+ )
1374
+ else DeepseekV2MLP(config)
1375
+ )
1376
+ self.input_layernorm = DeepseekV2RMSNorm(
1377
+ config.hidden_size, eps=config.rms_norm_eps
1378
+ )
1379
+ self.post_attention_layernorm = DeepseekV2RMSNorm(
1380
+ config.hidden_size, eps=config.rms_norm_eps
1381
+ )
1382
+
1383
+ def forward(
1384
+ self,
1385
+ hidden_states: torch.Tensor,
1386
+ attention_mask: Optional[torch.Tensor] = None,
1387
+ position_ids: Optional[torch.LongTensor] = None,
1388
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1389
+ output_attentions: Optional[bool] = False,
1390
+ use_cache: Optional[bool] = False,
1391
+ **kwargs,
1392
+ ) -> Tuple[
1393
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1394
+ ]:
1395
+ """
1396
+ Args:
1397
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1398
+ attention_mask (`torch.FloatTensor`, *optional*):
1399
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1400
+ query_sequence_length, key_sequence_length)` if default attention is used.
1401
+ output_attentions (`bool`, *optional*):
1402
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1403
+ returned tensors for more detail.
1404
+ use_cache (`bool`, *optional*):
1405
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1406
+ (see `past_key_values`).
1407
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1408
+ """
1409
+ if "padding_mask" in kwargs:
1410
+ warnings.warn(
1411
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1412
+ )
1413
+ residual = hidden_states
1414
+
1415
+ hidden_states = self.input_layernorm(hidden_states)
1416
+
1417
+ # Self Attention
1418
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1419
+ hidden_states=hidden_states,
1420
+ attention_mask=attention_mask,
1421
+ position_ids=position_ids,
1422
+ past_key_value=past_key_value,
1423
+ output_attentions=output_attentions,
1424
+ use_cache=use_cache,
1425
+ **kwargs,
1426
+ )
1427
+ hidden_states = residual + hidden_states
1428
+
1429
+ # Fully Connected
1430
+ residual = hidden_states
1431
+ hidden_states = self.post_attention_layernorm(hidden_states)
1432
+ hidden_states = self.mlp(hidden_states)
1433
+ hidden_states = residual + hidden_states
1434
+
1435
+ outputs = (hidden_states,)
1436
+
1437
+ if output_attentions:
1438
+ outputs += (self_attn_weights,)
1439
+
1440
+ if use_cache:
1441
+ outputs += (present_key_value,)
1442
+
1443
+ return outputs
1444
+
1445
+
1446
+ DeepseekV2_START_DOCSTRING = r"""
1447
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1448
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1449
+ etc.)
1450
+
1451
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1452
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1453
+ and behavior.
1454
+
1455
+ Parameters:
1456
+ config ([`DeepseekV2Config`]):
1457
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1458
+ load the weights associated with the model, only the configuration. Check out the
1459
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1460
+ """
1461
+
1462
+
1463
+ @add_start_docstrings(
1464
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1465
+ DeepseekV2_START_DOCSTRING,
1466
+ )
1467
+ class DeepseekV2PreTrainedModel(PreTrainedModel):
1468
+ config_class = DeepseekV2Config
1469
+ base_model_prefix = "model"
1470
+ supports_gradient_checkpointing = True
1471
+ _no_split_modules = ["DeepseekV2DecoderLayer"]
1472
+ _skip_keys_device_placement = "past_key_values"
1473
+ _supports_flash_attn_2 = True
1474
+ _supports_cache_class = True
1475
+
1476
+ def _init_weights(self, module):
1477
+ std = self.config.initializer_range
1478
+ if isinstance(module, nn.Linear):
1479
+ module.weight.data.normal_(mean=0.0, std=std)
1480
+ if module.bias is not None:
1481
+ module.bias.data.zero_()
1482
+ elif isinstance(module, nn.Embedding):
1483
+ module.weight.data.normal_(mean=0.0, std=std)
1484
+ if module.padding_idx is not None:
1485
+ module.weight.data[module.padding_idx].zero_()
1486
+
1487
+
1488
+ DeepseekV2_INPUTS_DOCSTRING = r"""
1489
+ Args:
1490
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1491
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1492
+ it.
1493
+
1494
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1495
+ [`PreTrainedTokenizer.__call__`] for details.
1496
+
1497
+ [What are input IDs?](../glossary#input-ids)
1498
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1499
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1500
+
1501
+ - 1 for tokens that are **not masked**,
1502
+ - 0 for tokens that are **masked**.
1503
+
1504
+ [What are attention masks?](../glossary#attention-mask)
1505
+
1506
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1507
+ [`PreTrainedTokenizer.__call__`] for details.
1508
+
1509
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1510
+ `past_key_values`).
1511
+
1512
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1513
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1514
+ information on the default strategy.
1515
+
1516
+ - 1 indicates the head is **not masked**,
1517
+ - 0 indicates the head is **masked**.
1518
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1519
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1520
+ config.n_positions - 1]`.
1521
+
1522
+ [What are position IDs?](../glossary#position-ids)
1523
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1524
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1525
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1526
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1527
+
1528
+ Two formats are allowed:
1529
+ - a [`~cache_utils.Cache`] instance;
1530
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1531
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1532
+ cache format.
1533
+
1534
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1535
+ legacy cache format will be returned.
1536
+
1537
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1538
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1539
+ of shape `(batch_size, sequence_length)`.
1540
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1541
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1542
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1543
+ model's internal embedding lookup matrix.
1544
+ use_cache (`bool`, *optional*):
1545
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1546
+ `past_key_values`).
1547
+ output_attentions (`bool`, *optional*):
1548
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1549
+ tensors for more detail.
1550
+ output_hidden_states (`bool`, *optional*):
1551
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1552
+ more detail.
1553
+ return_dict (`bool`, *optional*):
1554
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1555
+ """
1556
+
1557
+
1558
+ @add_start_docstrings(
1559
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1560
+ DeepseekV2_START_DOCSTRING,
1561
+ )
1562
+ class DeepseekV2Model(DeepseekV2PreTrainedModel):
1563
+ """
1564
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
1565
+
1566
+ Args:
1567
+ config: DeepseekV2Config
1568
+ """
1569
+
1570
+ def __init__(self, config: DeepseekV2Config):
1571
+ super().__init__(config)
1572
+ self.padding_idx = config.pad_token_id
1573
+ self.vocab_size = config.vocab_size
1574
+
1575
+ self.embed_tokens = nn.Embedding(
1576
+ config.vocab_size, config.hidden_size, self.padding_idx
1577
+ )
1578
+ self.layers = nn.ModuleList(
1579
+ [
1580
+ DeepseekV2DecoderLayer(config, layer_idx)
1581
+ for layer_idx in range(config.num_hidden_layers)
1582
+ ]
1583
+ )
1584
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1585
+ self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1586
+
1587
+ self.gradient_checkpointing = False
1588
+ # Initialize weights and apply final processing
1589
+ self.post_init()
1590
+
1591
+ def get_input_embeddings(self):
1592
+ return self.embed_tokens
1593
+
1594
+ def set_input_embeddings(self, value):
1595
+ self.embed_tokens = value
1596
+
1597
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1598
+ def forward(
1599
+ self,
1600
+ input_ids: torch.LongTensor = None,
1601
+ attention_mask: Optional[torch.Tensor] = None,
1602
+ position_ids: Optional[torch.LongTensor] = None,
1603
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1604
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1605
+ use_cache: Optional[bool] = None,
1606
+ output_attentions: Optional[bool] = None,
1607
+ output_hidden_states: Optional[bool] = None,
1608
+ return_dict: Optional[bool] = None,
1609
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1610
+ output_attentions = (
1611
+ output_attentions
1612
+ if output_attentions is not None
1613
+ else self.config.output_attentions
1614
+ )
1615
+ output_hidden_states = (
1616
+ output_hidden_states
1617
+ if output_hidden_states is not None
1618
+ else self.config.output_hidden_states
1619
+ )
1620
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1621
+
1622
+ return_dict = (
1623
+ return_dict if return_dict is not None else self.config.use_return_dict
1624
+ )
1625
+
1626
+ # retrieve input_ids and inputs_embeds
1627
+ if input_ids is not None and inputs_embeds is not None:
1628
+ raise ValueError(
1629
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1630
+ )
1631
+ elif input_ids is not None:
1632
+ batch_size, seq_length = input_ids.shape[:2]
1633
+ elif inputs_embeds is not None:
1634
+ batch_size, seq_length = inputs_embeds.shape[:2]
1635
+ else:
1636
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1637
+
1638
+ if self.gradient_checkpointing and self.training:
1639
+ if use_cache:
1640
+ logger.warning_once(
1641
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1642
+ )
1643
+ use_cache = False
1644
+
1645
+ past_key_values_length = 0
1646
+ if use_cache:
1647
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1648
+ if use_legacy_cache:
1649
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1650
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1651
+
1652
+ if position_ids is None:
1653
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1654
+ position_ids = torch.arange(
1655
+ past_key_values_length,
1656
+ seq_length + past_key_values_length,
1657
+ dtype=torch.long,
1658
+ device=device,
1659
+ )
1660
+ position_ids = position_ids.unsqueeze(0)
1661
+
1662
+ if inputs_embeds is None:
1663
+ inputs_embeds = self.embed_tokens(input_ids)
1664
+
1665
+ if self._use_flash_attention_2:
1666
+ # 2d mask is passed through the layers
1667
+ attention_mask = (
1668
+ attention_mask
1669
+ if (attention_mask is not None and 0 in attention_mask)
1670
+ else None
1671
+ )
1672
+ else:
1673
+ # 4d mask is passed through the layers
1674
+ attention_mask = _prepare_4d_causal_attention_mask(
1675
+ attention_mask,
1676
+ (batch_size, seq_length),
1677
+ inputs_embeds,
1678
+ past_key_values_length,
1679
+ )
1680
+
1681
+ # embed positions
1682
+ hidden_states = inputs_embeds
1683
+
1684
+ # decoder layers
1685
+ all_hidden_states = () if output_hidden_states else None
1686
+ all_self_attns = () if output_attentions else None
1687
+ next_decoder_cache = None
1688
+
1689
+ for decoder_layer in self.layers:
1690
+ if output_hidden_states:
1691
+ all_hidden_states += (hidden_states,)
1692
+
1693
+ if self.gradient_checkpointing and self.training:
1694
+ layer_outputs = self._gradient_checkpointing_func(
1695
+ decoder_layer.__call__,
1696
+ hidden_states,
1697
+ attention_mask,
1698
+ position_ids,
1699
+ past_key_values,
1700
+ output_attentions,
1701
+ use_cache,
1702
+ )
1703
+ else:
1704
+ layer_outputs = decoder_layer(
1705
+ hidden_states,
1706
+ attention_mask=attention_mask,
1707
+ position_ids=position_ids,
1708
+ past_key_value=past_key_values,
1709
+ output_attentions=output_attentions,
1710
+ use_cache=use_cache,
1711
+ )
1712
+
1713
+ hidden_states = layer_outputs[0]
1714
+
1715
+ if use_cache:
1716
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1717
+
1718
+ if output_attentions:
1719
+ all_self_attns += (layer_outputs[1],)
1720
+
1721
+ hidden_states = self.norm(hidden_states)
1722
+
1723
+ # add hidden states from the last decoder layer
1724
+ if output_hidden_states:
1725
+ all_hidden_states += (hidden_states,)
1726
+
1727
+ next_cache = None
1728
+ if use_cache:
1729
+ next_cache = (
1730
+ next_decoder_cache.to_legacy_cache()
1731
+ if use_legacy_cache
1732
+ else next_decoder_cache
1733
+ )
1734
+ if not return_dict:
1735
+ return tuple(
1736
+ v
1737
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1738
+ if v is not None
1739
+ )
1740
+ return BaseModelOutputWithPast(
1741
+ last_hidden_state=hidden_states,
1742
+ past_key_values=next_cache,
1743
+ hidden_states=all_hidden_states,
1744
+ attentions=all_self_attns,
1745
+ )
1746
+
1747
+
1748
+ class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
1749
+ _tied_weights_keys = ["lm_head.weight"]
1750
+
1751
+ def __init__(self, config):
1752
+ super().__init__(config)
1753
+ self.model = DeepseekV2Model(config)
1754
+ self.vocab_size = config.vocab_size
1755
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1756
+
1757
+ # Initialize weights and apply final processing
1758
+ self.post_init()
1759
+
1760
+ def get_input_embeddings(self):
1761
+ return self.model.embed_tokens
1762
+
1763
+ def set_input_embeddings(self, value):
1764
+ self.model.embed_tokens = value
1765
+
1766
+ def get_output_embeddings(self):
1767
+ return self.lm_head
1768
+
1769
+ def set_output_embeddings(self, new_embeddings):
1770
+ self.lm_head = new_embeddings
1771
+
1772
+ def set_decoder(self, decoder):
1773
+ self.model = decoder
1774
+
1775
+ def get_decoder(self):
1776
+ return self.model
1777
+
1778
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1779
+ @replace_return_docstrings(
1780
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1781
+ )
1782
+ def forward(
1783
+ self,
1784
+ input_ids: torch.LongTensor = None,
1785
+ attention_mask: Optional[torch.Tensor] = None,
1786
+ position_ids: Optional[torch.LongTensor] = None,
1787
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1788
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1789
+ labels: Optional[torch.LongTensor] = None,
1790
+ use_cache: Optional[bool] = None,
1791
+ output_attentions: Optional[bool] = None,
1792
+ output_hidden_states: Optional[bool] = None,
1793
+ return_dict: Optional[bool] = None,
1794
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1795
+ r"""
1796
+ Args:
1797
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1798
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1799
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1800
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1801
+
1802
+ Returns:
1803
+
1804
+ Example:
1805
+
1806
+ ```python
1807
+ >>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
1808
+
1809
+ >>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1810
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1811
+
1812
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1813
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1814
+
1815
+ >>> # Generate
1816
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1817
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1818
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1819
+ ```"""
1820
+ output_attentions = (
1821
+ output_attentions
1822
+ if output_attentions is not None
1823
+ else self.config.output_attentions
1824
+ )
1825
+ output_hidden_states = (
1826
+ output_hidden_states
1827
+ if output_hidden_states is not None
1828
+ else self.config.output_hidden_states
1829
+ )
1830
+ return_dict = (
1831
+ return_dict if return_dict is not None else self.config.use_return_dict
1832
+ )
1833
+
1834
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1835
+ outputs = self.model(
1836
+ input_ids=input_ids,
1837
+ attention_mask=attention_mask,
1838
+ position_ids=position_ids,
1839
+ past_key_values=past_key_values,
1840
+ inputs_embeds=inputs_embeds,
1841
+ use_cache=use_cache,
1842
+ output_attentions=output_attentions,
1843
+ output_hidden_states=output_hidden_states,
1844
+ return_dict=return_dict,
1845
+ )
1846
+
1847
+ hidden_states = outputs[0]
1848
+ logits = self.lm_head(hidden_states)
1849
+ logits = logits.float()
1850
+
1851
+ loss = None
1852
+ if labels is not None:
1853
+ # Shift so that tokens < n predict n
1854
+ shift_logits = logits[..., :-1, :].contiguous()
1855
+ shift_labels = labels[..., 1:].contiguous()
1856
+ # Flatten the tokens
1857
+ loss_fct = CrossEntropyLoss()
1858
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1859
+ shift_labels = shift_labels.view(-1)
1860
+ # Enable model parallelism
1861
+ shift_labels = shift_labels.to(shift_logits.device)
1862
+ loss = loss_fct(shift_logits, shift_labels)
1863
+
1864
+ if not return_dict:
1865
+ output = (logits,) + outputs[1:]
1866
+ return (loss,) + output if loss is not None else output
1867
+
1868
+ return CausalLMOutputWithPast(
1869
+ loss=loss,
1870
+ logits=logits,
1871
+ past_key_values=outputs.past_key_values,
1872
+ hidden_states=outputs.hidden_states,
1873
+ attentions=outputs.attentions,
1874
+ )
1875
+
1876
+ def prepare_inputs_for_generation(
1877
+ self,
1878
+ input_ids,
1879
+ past_key_values=None,
1880
+ attention_mask=None,
1881
+ inputs_embeds=None,
1882
+ **kwargs,
1883
+ ):
1884
+ if past_key_values is not None:
1885
+ if isinstance(past_key_values, Cache):
1886
+ cache_length = past_key_values.get_seq_length()
1887
+ past_length = past_key_values.seen_tokens
1888
+ max_cache_length = past_key_values.get_max_length()
1889
+ else:
1890
+ cache_length = past_length = past_key_values[0][0].shape[2]
1891
+ max_cache_length = None
1892
+
1893
+ # Keep only the unprocessed tokens:
1894
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1895
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1896
+ # input)
1897
+ if (
1898
+ attention_mask is not None
1899
+ and attention_mask.shape[1] > input_ids.shape[1]
1900
+ ):
1901
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1902
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1903
+ # input_ids based on the past_length.
1904
+ elif past_length < input_ids.shape[1]:
1905
+ input_ids = input_ids[:, past_length:]
1906
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1907
+
1908
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1909
+ if (
1910
+ max_cache_length is not None
1911
+ and attention_mask is not None
1912
+ and cache_length + input_ids.shape[1] > max_cache_length
1913
+ ):
1914
+ attention_mask = attention_mask[:, -max_cache_length:]
1915
+
1916
+ position_ids = kwargs.get("position_ids", None)
1917
+ if attention_mask is not None and position_ids is None:
1918
+ # create position_ids on the fly for batch generation
1919
+ position_ids = attention_mask.long().cumsum(-1) - 1
1920
+ position_ids.masked_fill_(attention_mask == 0, 1)
1921
+ if past_key_values:
1922
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1923
+
1924
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1925
+ if inputs_embeds is not None and past_key_values is None:
1926
+ model_inputs = {"inputs_embeds": inputs_embeds}
1927
+ else:
1928
+ model_inputs = {"input_ids": input_ids}
1929
+
1930
+ model_inputs.update(
1931
+ {
1932
+ "position_ids": position_ids,
1933
+ "past_key_values": past_key_values,
1934
+ "use_cache": kwargs.get("use_cache"),
1935
+ "attention_mask": attention_mask,
1936
+ }
1937
+ )
1938
+ return model_inputs
1939
+
1940
+ @staticmethod
1941
+ def _reorder_cache(past_key_values, beam_idx):
1942
+ reordered_past = ()
1943
+ for layer_past in past_key_values:
1944
+ reordered_past += (
1945
+ tuple(
1946
+ past_state.index_select(0, beam_idx.to(past_state.device))
1947
+ for past_state in layer_past
1948
+ ),
1949
+ )
1950
+ return reordered_past
1951
+
1952
+
1953
+ @add_start_docstrings(
1954
+ """
1955
+ The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
1956
+
1957
+ [`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1958
+ (e.g. GPT-2) do.
1959
+
1960
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1961
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1962
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1963
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1964
+ each row of the batch).
1965
+ """,
1966
+ DeepseekV2_START_DOCSTRING,
1967
+ )
1968
+ class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel):
1969
+ def __init__(self, config):
1970
+ super().__init__(config)
1971
+ self.num_labels = config.num_labels
1972
+ self.model = DeepseekV2Model(config)
1973
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1974
+
1975
+ # Initialize weights and apply final processing
1976
+ self.post_init()
1977
+
1978
+ def get_input_embeddings(self):
1979
+ return self.model.embed_tokens
1980
+
1981
+ def set_input_embeddings(self, value):
1982
+ self.model.embed_tokens = value
1983
+
1984
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1985
+ def forward(
1986
+ self,
1987
+ input_ids: torch.LongTensor = None,
1988
+ attention_mask: Optional[torch.Tensor] = None,
1989
+ position_ids: Optional[torch.LongTensor] = None,
1990
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1991
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1992
+ labels: Optional[torch.LongTensor] = None,
1993
+ use_cache: Optional[bool] = None,
1994
+ output_attentions: Optional[bool] = None,
1995
+ output_hidden_states: Optional[bool] = None,
1996
+ return_dict: Optional[bool] = None,
1997
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1998
+ r"""
1999
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2000
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2001
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2002
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2003
+ """
2004
+ return_dict = (
2005
+ return_dict if return_dict is not None else self.config.use_return_dict
2006
+ )
2007
+
2008
+ transformer_outputs = self.model(
2009
+ input_ids,
2010
+ attention_mask=attention_mask,
2011
+ position_ids=position_ids,
2012
+ past_key_values=past_key_values,
2013
+ inputs_embeds=inputs_embeds,
2014
+ use_cache=use_cache,
2015
+ output_attentions=output_attentions,
2016
+ output_hidden_states=output_hidden_states,
2017
+ return_dict=return_dict,
2018
+ )
2019
+ hidden_states = transformer_outputs[0]
2020
+ logits = self.score(hidden_states)
2021
+
2022
+ if input_ids is not None:
2023
+ batch_size = input_ids.shape[0]
2024
+ else:
2025
+ batch_size = inputs_embeds.shape[0]
2026
+
2027
+ if self.config.pad_token_id is None and batch_size != 1:
2028
+ raise ValueError(
2029
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2030
+ )
2031
+ if self.config.pad_token_id is None:
2032
+ sequence_lengths = -1
2033
+ else:
2034
+ if input_ids is not None:
2035
+ sequence_lengths = (
2036
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2037
+ ).to(logits.device)
2038
+ else:
2039
+ sequence_lengths = -1
2040
+
2041
+ pooled_logits = logits[
2042
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2043
+ ]
2044
+
2045
+ loss = None
2046
+ if labels is not None:
2047
+ labels = labels.to(logits.device)
2048
+ if self.config.problem_type is None:
2049
+ if self.num_labels == 1:
2050
+ self.config.problem_type = "regression"
2051
+ elif self.num_labels > 1 and (
2052
+ labels.dtype == torch.long or labels.dtype == torch.int
2053
+ ):
2054
+ self.config.problem_type = "single_label_classification"
2055
+ else:
2056
+ self.config.problem_type = "multi_label_classification"
2057
+
2058
+ if self.config.problem_type == "regression":
2059
+ loss_fct = MSELoss()
2060
+ if self.num_labels == 1:
2061
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2062
+ else:
2063
+ loss = loss_fct(pooled_logits, labels)
2064
+ elif self.config.problem_type == "single_label_classification":
2065
+ loss_fct = CrossEntropyLoss()
2066
+ loss = loss_fct(
2067
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2068
+ )
2069
+ elif self.config.problem_type == "multi_label_classification":
2070
+ loss_fct = BCEWithLogitsLoss()
2071
+ loss = loss_fct(pooled_logits, labels)
2072
+ if not return_dict:
2073
+ output = (pooled_logits,) + transformer_outputs[1:]
2074
+ return ((loss,) + output) if loss is not None else output
2075
+
2076
+ return SequenceClassifierOutputWithPast(
2077
+ loss=loss,
2078
+ logits=pooled_logits,
2079
+ past_key_values=transformer_outputs.past_key_values,
2080
+ hidden_states=transformer_outputs.hidden_states,
2081
+ attentions=transformer_outputs.attentions,
2082
+ )
modeling_deepseek_fused_v2.py ADDED
@@ -0,0 +1,2082 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch DeepSeek model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ )
38
+ from transformers.modeling_outputs import (
39
+ BaseModelOutputWithPast,
40
+ CausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import (
45
+ ALL_LAYERNORM_LAYERS,
46
+ is_torch_greater_or_equal_than_1_13,
47
+ )
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from transformers.utils.import_utils import is_torch_fx_available
57
+
58
+ try:
59
+ from .configuration_deepseek import DeepseekV2Config
60
+ except:
61
+ from .configuration_deepseek_fused_v2 import DeepseekV2Config
62
+
63
+
64
+ import torch.distributed as dist
65
+ import numpy as np
66
+
67
+ if is_flash_attn_2_available():
68
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
69
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
70
+
71
+
72
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
73
+ # It means that the function will not be traced through and simply appear as a node in the graph.
74
+ if is_torch_fx_available():
75
+ if not is_torch_greater_or_equal_than_1_13:
76
+ import torch.fx
77
+
78
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
79
+
80
+
81
+ logger = logging.get_logger(__name__)
82
+
83
+ _CONFIG_FOR_DOC = "DeepseekV2Config"
84
+
85
+
86
+ def _get_unpad_data(attention_mask):
87
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
88
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
89
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
90
+ cu_seqlens = F.pad(
91
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
92
+ )
93
+ return (
94
+ indices,
95
+ cu_seqlens,
96
+ max_seqlen_in_batch,
97
+ )
98
+
99
+
100
+ class DeepseekV2RMSNorm(nn.Module):
101
+ def __init__(self, hidden_size, eps=1e-6):
102
+ """
103
+ DeepseekV2RMSNorm is equivalent to T5LayerNorm
104
+ """
105
+ super().__init__()
106
+ self.weight = nn.Parameter(torch.ones(hidden_size))
107
+ self.variance_epsilon = eps
108
+
109
+ def forward(self, hidden_states):
110
+ input_dtype = hidden_states.dtype
111
+ hidden_states = hidden_states.to(torch.float32)
112
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
113
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
114
+ return self.weight * hidden_states.to(input_dtype)
115
+
116
+
117
+ ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
118
+
119
+
120
+ class DeepseekV2RotaryEmbedding(nn.Module):
121
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
122
+ super().__init__()
123
+
124
+ self.dim = dim
125
+ self.max_position_embeddings = max_position_embeddings
126
+ self.base = base
127
+ inv_freq = 1.0 / (
128
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
129
+ )
130
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
131
+
132
+ # Build here to make `torch.jit.trace` work.
133
+ self._set_cos_sin_cache(
134
+ seq_len=max_position_embeddings,
135
+ device=self.inv_freq.device,
136
+ dtype=torch.get_default_dtype(),
137
+ )
138
+ self.max_seq_len_cached = None
139
+
140
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
141
+ self.max_seq_len_cached = seq_len
142
+ t = torch.arange(
143
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
144
+ )
145
+
146
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
147
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
148
+ emb = torch.cat((freqs, freqs), dim=-1)
149
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
150
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
151
+
152
+ def forward(self, x, seq_len=None):
153
+ # x: [bs, num_attention_heads, seq_len, head_size]
154
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
155
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
156
+
157
+ return (
158
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
159
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
160
+ )
161
+
162
+
163
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2
164
+ class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
165
+ """DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
166
+
167
+ def __init__(
168
+ self,
169
+ dim,
170
+ max_position_embeddings=2048,
171
+ base=10000,
172
+ device=None,
173
+ scaling_factor=1.0,
174
+ ):
175
+ self.scaling_factor = scaling_factor
176
+ super().__init__(dim, max_position_embeddings, base, device)
177
+
178
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
179
+ self.max_seq_len_cached = seq_len
180
+ t = torch.arange(
181
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
182
+ )
183
+ t = t / self.scaling_factor
184
+
185
+ freqs = torch.outer(t, self.inv_freq)
186
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
187
+ emb = torch.cat((freqs, freqs), dim=-1)
188
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
189
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
190
+
191
+
192
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2
193
+ class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
194
+ """DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
195
+
196
+ def __init__(
197
+ self,
198
+ dim,
199
+ max_position_embeddings=2048,
200
+ base=10000,
201
+ device=None,
202
+ scaling_factor=1.0,
203
+ ):
204
+ self.scaling_factor = scaling_factor
205
+ super().__init__(dim, max_position_embeddings, base, device)
206
+
207
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
208
+ self.max_seq_len_cached = seq_len
209
+
210
+ if seq_len > self.max_position_embeddings:
211
+ base = self.base * (
212
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
213
+ - (self.scaling_factor - 1)
214
+ ) ** (self.dim / (self.dim - 2))
215
+ inv_freq = 1.0 / (
216
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
217
+ )
218
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
219
+
220
+ t = torch.arange(
221
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
222
+ )
223
+
224
+ freqs = torch.outer(t, self.inv_freq)
225
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
226
+ emb = torch.cat((freqs, freqs), dim=-1)
227
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
228
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
229
+
230
+
231
+ # Inverse dim formula to find dim based on number of rotations
232
+ def yarn_find_correction_dim(
233
+ num_rotations, dim, base=10000, max_position_embeddings=2048
234
+ ):
235
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
236
+ 2 * math.log(base)
237
+ )
238
+
239
+
240
+ # Find dim range bounds based on rotations
241
+ def yarn_find_correction_range(
242
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
243
+ ):
244
+ low = math.floor(
245
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
246
+ )
247
+ high = math.ceil(
248
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
249
+ )
250
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
251
+
252
+
253
+ def yarn_get_mscale(scale=1, mscale=1):
254
+ if scale <= 1:
255
+ return 1.0
256
+ return 0.1 * mscale * math.log(scale) + 1.0
257
+
258
+
259
+ def yarn_linear_ramp_mask(min, max, dim):
260
+ if min == max:
261
+ max += 0.001 # Prevent singularity
262
+
263
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
264
+ ramp_func = torch.clamp(linear_func, 0, 1)
265
+ return ramp_func
266
+
267
+
268
+ class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
269
+
270
+ def __init__(
271
+ self,
272
+ dim,
273
+ max_position_embeddings=2048,
274
+ base=10000,
275
+ device=None,
276
+ scaling_factor=1.0,
277
+ original_max_position_embeddings=4096,
278
+ beta_fast=32,
279
+ beta_slow=1,
280
+ mscale=1,
281
+ mscale_all_dim=0,
282
+ ):
283
+ self.scaling_factor = scaling_factor
284
+ self.original_max_position_embeddings = original_max_position_embeddings
285
+ self.beta_fast = beta_fast
286
+ self.beta_slow = beta_slow
287
+ self.mscale = mscale
288
+ self.mscale_all_dim = mscale_all_dim
289
+ super().__init__(dim, max_position_embeddings, base, device)
290
+
291
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
292
+ self.max_seq_len_cached = seq_len
293
+ dim = self.dim
294
+
295
+ freq_extra = 1.0 / (
296
+ self.base
297
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
298
+ )
299
+ freq_inter = 1.0 / (
300
+ self.scaling_factor
301
+ * self.base
302
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
303
+ )
304
+
305
+ low, high = yarn_find_correction_range(
306
+ self.beta_fast,
307
+ self.beta_slow,
308
+ dim,
309
+ self.base,
310
+ self.original_max_position_embeddings,
311
+ )
312
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
313
+ device=device, dtype=torch.float32
314
+ )
315
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
316
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
317
+
318
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
319
+
320
+ freqs = torch.outer(t, inv_freq)
321
+
322
+ _mscale = float(
323
+ yarn_get_mscale(self.scaling_factor, self.mscale)
324
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
325
+ )
326
+
327
+ emb = torch.cat((freqs, freqs), dim=-1)
328
+ self.register_buffer(
329
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
330
+ )
331
+ self.register_buffer(
332
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
333
+ )
334
+
335
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
336
+ def rotate_half(x):
337
+ """Rotates half the hidden dims of the input."""
338
+ x1 = x[..., : x.shape[-1] // 2]
339
+ x2 = x[..., x.shape[-1] // 2 :]
340
+ return torch.cat((-x2, x1), dim=-1)
341
+
342
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
343
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
344
+ """Applies Rotary Position Embedding to the query and key tensors.
345
+
346
+ Args:
347
+ q (`torch.Tensor`): The query tensor.
348
+ k (`torch.Tensor`): The key tensor.
349
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
350
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
351
+ position_ids (`torch.Tensor`):
352
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
353
+ used to pass offsetted position ids when working with a KV-cache.
354
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
355
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
356
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
357
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
358
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
359
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
360
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
361
+ Returns:
362
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
363
+ """
364
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
365
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
366
+
367
+ b, h, s, d = q.shape
368
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
369
+
370
+ b, h, s, d = k.shape
371
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
372
+
373
+ q_embed = (q * cos) + (rotate_half(q) * sin)
374
+ k_embed = (k * cos) + (rotate_half(k) * sin)
375
+ return q_embed, k_embed
376
+
377
+ class DeepseekV2MLP(nn.Module):
378
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
379
+ super().__init__()
380
+ self.config = config
381
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
382
+ self.intermediate_size = (
383
+ config.intermediate_size if intermediate_size is None else intermediate_size
384
+ )
385
+
386
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
387
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
388
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
389
+ self.act_fn = ACT2FN[config.hidden_act]
390
+
391
+ def forward(self, x):
392
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
393
+ return down_proj
394
+
395
+ class FusedLinear(nn.Module):
396
+ def __init__(self, in_features, out_features, rank=8, alpha=1, n_fused=4, adapter_type="mixture", bias=False, **kwargs):
397
+ super().__init__()
398
+
399
+ self.rank = rank
400
+ self.adapter_type = adapter_type
401
+ self.fused_layer = nn.Linear(in_features, out_features, bias=bias)
402
+
403
+ if self.adapter_type == 'lora':
404
+ self.qa_weights = nn.Parameter(torch.randn(rank, in_features) * 0.02)
405
+ self.qb_weights = nn.Parameter(torch.randn(out_features, rank) * 0.02)
406
+ self.mask_up_proj = nn.Parameter(torch.randn(n_fused, rank) * 0.02)
407
+ self.scaling_factor = nn.Parameter(torch.Tensor([0.1] * out_features))
408
+
409
+ if self.adapter_type == 'mixture':
410
+ self.n_fused = n_fused
411
+ # For efficient forward pass, create weight tensors
412
+ self.qa_weights = nn.Parameter(torch.stack([torch.zeros(rank, in_features) for i in range(n_fused)]))
413
+ self.qb_weights = nn.Parameter(torch.stack([torch.zeros(out_features, rank) for i in range(n_fused)]))
414
+ self.scaling_factor = nn.Parameter(torch.Tensor([0.1] * out_features))
415
+
416
+ def forward(self, x, top_k_weights):
417
+ output = self.fused_layer(x)
418
+
419
+ if self.adapter_type == 'lora':
420
+ x = torch.einsum('bh,rh->br', x, self.qa_weights)
421
+ x = torch.einsum('br,brr->br', x, torch.diag_embed(torch.einsum('bk,kr -> br', top_k_weights, self.mask_up_proj)))
422
+ x = torch.einsum('br,hr ->bh', x, self.qb_weights)
423
+ output = output + self.scaling_factor[None] * x
424
+
425
+ if self.adapter_type == 'mixture':
426
+ if len(x.shape) == 2:
427
+ x = torch.einsum('bh,krh->bkr', x, self.qa_weights)
428
+ x = torch.einsum('bkr,khr->bkh', x, self.qb_weights)
429
+ x = torch.einsum('bkh,bk->bkh', x, top_k_weights)
430
+ x = torch.sum(x, dim=1)
431
+ output=output + self.scaling_factor[None] * x
432
+ return output
433
+
434
+ class FusedMLP(torch.nn.Module):
435
+ def __init__(self, config, hidden_size=None, intermediate_size=None, n_fused=4, rank=8, adapter_type='mixture'):
436
+ super().__init__()
437
+ self.config = config
438
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
439
+ self.intermediate_size = (
440
+ config.moe_intermediate_size if intermediate_size is None else intermediate_size
441
+ )
442
+ self.n_fused=n_fused
443
+ self.gate_proj = FusedLinear(self.hidden_size, self.intermediate_size, bias=False, rank=rank, n_fused=n_fused, adapter_type=adapter_type)
444
+ self.up_proj = FusedLinear(self.hidden_size, self.intermediate_size, bias=False, rank=rank, n_fused=n_fused, adapter_type=adapter_type)
445
+ self.down_proj = FusedLinear(self.intermediate_size, self.hidden_size, bias=False, rank=rank, n_fused=n_fused, adapter_type=adapter_type)
446
+ self.mask_up_proj = torch.nn.Linear(self.n_fused, self.hidden_size, bias=False)
447
+ self.act_fn = ACT2FN[config.hidden_act]
448
+ self.adapter_type=adapter_type
449
+
450
+ def forward(self, x, top_k_weights):
451
+ x = x + self.mask_up_proj(top_k_weights)
452
+ 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)
453
+ return down_proj
454
+
455
+ class MoEGate(nn.Module):
456
+ def __init__(self, config):
457
+ super().__init__()
458
+ self.config = config
459
+ self.top_k = config.num_experts_per_tok
460
+ self.n_routed_experts = config.n_routed_experts
461
+ self.routed_scaling_factor = config.routed_scaling_factor
462
+ self.scoring_func = config.scoring_func
463
+ self.alpha = config.aux_loss_alpha
464
+ self.seq_aux = config.seq_aux
465
+ self.topk_method = config.topk_method
466
+ self.n_group = config.n_group
467
+ self.topk_group = config.topk_group
468
+
469
+ # topk selection algorithm
470
+ self.norm_topk_prob = config.norm_topk_prob
471
+ self.gating_dim = config.hidden_size
472
+ self.weight = nn.Parameter(
473
+ torch.empty((self.n_routed_experts, self.gating_dim))
474
+ )
475
+ self.reset_parameters()
476
+
477
+ def reset_parameters(self) -> None:
478
+ import torch.nn.init as init
479
+
480
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
481
+
482
+ def forward(self, hidden_states):
483
+ bsz, seq_len, h = hidden_states.shape
484
+ ### compute gating score
485
+ hidden_states = hidden_states.view(-1, h)
486
+ logits = F.linear(
487
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
488
+ )
489
+ if self.scoring_func == "softmax":
490
+ scores = logits.softmax(dim=-1, dtype=torch.float32)
491
+ else:
492
+ raise NotImplementedError(
493
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
494
+ )
495
+
496
+ ### select top-k experts
497
+ if self.topk_method == "greedy":
498
+ topk_weight, topk_idx = torch.topk(
499
+ scores, k=self.top_k, dim=-1, sorted=False
500
+ )
501
+ elif self.topk_method == "group_limited_greedy":
502
+ group_scores = (
503
+ scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
504
+ ) # [n, n_group]
505
+ group_idx = torch.topk(
506
+ group_scores, k=self.topk_group, dim=-1, sorted=False
507
+ )[
508
+ 1
509
+ ] # [n, top_k_group]
510
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
511
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
512
+ score_mask = (
513
+ group_mask.unsqueeze(-1)
514
+ .expand(
515
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
516
+ )
517
+ .reshape(bsz * seq_len, -1)
518
+ ) # [n, e]
519
+ tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
520
+ topk_weight, topk_idx = torch.topk(
521
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
522
+ )
523
+
524
+ ### norm gate to sum 1
525
+ if self.top_k > 1 and self.norm_topk_prob:
526
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
527
+ topk_weight = topk_weight / denominator
528
+ else:
529
+ topk_weight = topk_weight * self.routed_scaling_factor
530
+ ### expert-level computation auxiliary loss
531
+ if self.training and self.alpha > 0.0:
532
+ scores_for_aux = scores
533
+ aux_topk = self.top_k
534
+ # always compute aux loss based on the naive greedy topk method
535
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
536
+ if self.seq_aux:
537
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
538
+ ce = torch.zeros(
539
+ bsz, self.n_routed_experts, device=hidden_states.device
540
+ )
541
+ ce.scatter_add_(
542
+ 1,
543
+ topk_idx_for_aux_loss,
544
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
545
+ ).div_(seq_len * aux_topk / self.n_routed_experts)
546
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
547
+ dim=1
548
+ ).mean() * self.alpha
549
+ else:
550
+ mask_ce = F.one_hot(
551
+ topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
552
+ )
553
+ ce = mask_ce.float().mean(0)
554
+ Pi = scores_for_aux.mean(0)
555
+ fi = ce * self.n_routed_experts
556
+ aux_loss = (Pi * fi).sum() * self.alpha
557
+ else:
558
+ aux_loss = None
559
+ return topk_idx, topk_weight, aux_loss
560
+
561
+ class AddAuxiliaryLoss(torch.autograd.Function):
562
+ """
563
+ The trick function of adding auxiliary (aux) loss,
564
+ which includes the gradient of the aux loss during backpropagation.
565
+ """
566
+
567
+ @staticmethod
568
+ def forward(ctx, x, loss):
569
+ assert loss.numel() == 1
570
+ ctx.dtype = loss.dtype
571
+ ctx.required_aux_loss = loss.requires_grad
572
+ return x
573
+
574
+ @staticmethod
575
+ def backward(ctx, grad_output):
576
+ grad_loss = None
577
+ if ctx.required_aux_loss:
578
+ grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
579
+ return grad_output, grad_loss
580
+
581
+ class DeepseekV2MoE(nn.Module):
582
+ """
583
+ A mixed expert module containing shared experts.
584
+ """
585
+
586
+ def __init__(self, config):
587
+ super().__init__()
588
+ self.config = config
589
+ self.num_experts_per_tok = config.num_experts_per_tok
590
+
591
+ if hasattr(config, "ep_size") and config.ep_size > 1:
592
+ assert config.ep_size == dist.get_world_size()
593
+ self.ep_size = config.ep_size
594
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
595
+ self.ep_rank = dist.get_rank()
596
+ self.experts = nn.ModuleList(
597
+ [
598
+ (
599
+ DeepseekV2MLP(
600
+ config, intermediate_size=config.moe_intermediate_size
601
+ )
602
+ if i >= self.ep_rank * self.experts_per_rank
603
+ and i < (self.ep_rank + 1) * self.experts_per_rank
604
+ else None
605
+ )
606
+ for i in range(config.n_routed_experts)
607
+ ]
608
+ )
609
+ else:
610
+ self.ep_size = 1
611
+ self.experts_per_rank = config.n_routed_experts
612
+ self.ep_rank = 0
613
+ self.experts = nn.ModuleList(
614
+ [
615
+ DeepseekV2MLP(config, intermediate_size=config.moe_intermediate_size)
616
+ for i in range(config.n_routed_experts)
617
+ ]
618
+ )
619
+ self.gate = MoEGate(config)
620
+ if config.n_shared_experts is not None:
621
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
622
+ self.shared_experts = DeepseekV2MLP(
623
+ config=config, intermediate_size=intermediate_size
624
+ )
625
+
626
+ def forward(self, hidden_states):
627
+ identity = hidden_states
628
+ orig_shape = hidden_states.shape
629
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
630
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
631
+ flat_topk_idx = topk_idx.view(-1)
632
+ if self.training:
633
+ hidden_states = hidden_states.repeat_interleave(
634
+ self.num_experts_per_tok, dim=0
635
+ )
636
+
637
+ y = torch.empty_like(hidden_states)
638
+ for i, expert in enumerate(self.experts):
639
+ expert_output=expert(hidden_states[flat_topk_idx == i])
640
+ try:
641
+ y[flat_topk_idx == i] = expert_output.to(y.dtype)
642
+ except:
643
+ pass
644
+
645
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
646
+ y = y.view(*orig_shape)
647
+ y = AddAuxiliaryLoss.apply(y, aux_loss)
648
+ else:
649
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
650
+ if self.config.n_shared_experts is not None:
651
+ y = y + self.shared_experts(identity)
652
+ return y
653
+
654
+ @torch.no_grad()
655
+ def moe_infer(self, x, topk_ids, topk_weight):
656
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
657
+ cnts.scatter_(1, topk_ids, 1)
658
+ tokens_per_expert = cnts.sum(dim=0)
659
+ idxs = topk_ids.view(-1).argsort()
660
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
661
+ sorted_tokens_shape = sorted_tokens.shape
662
+ if self.ep_size > 1:
663
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
664
+ tokens_per_expert_group = tokens_per_expert.new_empty(
665
+ tokens_per_expert.shape[0]
666
+ )
667
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
668
+ output_splits = (
669
+ tokens_per_expert_group.view(self.ep_size, -1)
670
+ .sum(1)
671
+ .cpu()
672
+ .numpy()
673
+ .tolist()
674
+ )
675
+ gathered_tokens = sorted_tokens.new_empty(
676
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
677
+ )
678
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
679
+ dist.all_to_all(
680
+ list(gathered_tokens.split(output_splits)),
681
+ list(sorted_tokens.split(input_split_sizes)),
682
+ )
683
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
684
+ self.ep_size, self.experts_per_rank
685
+ ).sum(dim=0)
686
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
687
+ s = 0
688
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
689
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
690
+ s += k
691
+ gatherd_idxs = gatherd_idxs.argsort()
692
+ sorted_tokens = gathered_tokens[gatherd_idxs]
693
+ tokens_per_expert = tokens_per_expert_post_gather
694
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
695
+
696
+ outputs = []
697
+ start_idx = 0
698
+ for i, num_tokens in enumerate(tokens_per_expert):
699
+ end_idx = start_idx + num_tokens
700
+ if num_tokens == 0:
701
+ continue
702
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
703
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
704
+ expert_out = expert(tokens_for_this_expert)
705
+ outputs.append(expert_out)
706
+ start_idx = end_idx
707
+
708
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
709
+ if self.ep_size > 1:
710
+ new_x = torch.empty_like(outs)
711
+ new_x[gatherd_idxs] = outs
712
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
713
+ dist.all_to_all(
714
+ list(gathered_tokens.split(input_split_sizes)),
715
+ list(new_x.split(output_splits)),
716
+ )
717
+ outs = gathered_tokens
718
+
719
+ new_x = torch.empty_like(outs)
720
+ new_x[idxs] = outs
721
+ final_out = (
722
+ new_x.view(*topk_ids.shape, -1)
723
+ .type(topk_weight.dtype)
724
+ .mul_(topk_weight.unsqueeze(dim=-1))
725
+ .sum(dim=1)
726
+ .type(new_x.dtype)
727
+ )
728
+ return final_out
729
+
730
+ class FusedMOE(torch.nn.Module):
731
+ def __init__(self, config):
732
+ super().__init__()
733
+ self.config = config
734
+ self.num_experts_per_tok = config.num_experts_per_tok
735
+
736
+ if hasattr(config, "ep_size") and config.ep_size > 1:
737
+ assert config.ep_size == dist.get_world_size()
738
+ self.ep_size = config.ep_size
739
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
740
+ self.ep_rank = dist.get_rank()
741
+ self.experts = nn.ModuleList(
742
+ [
743
+ (
744
+ FusedMLP(
745
+ config,
746
+ intermediate_size=config.moe_intermediate_size,
747
+ n_fused=config.n_routed_experts // config.n_fused_experts,
748
+ rank=config.fused_expert_dora_rank,
749
+ adapter_type=config.fused_expert_method
750
+ )
751
+ if i >= self.ep_rank * self.experts_per_rank
752
+ and i < (self.ep_rank + 1) * self.experts_per_rank
753
+ else None
754
+ )
755
+ for i in range(config.n_fused_experts)
756
+ ]
757
+ )
758
+ else:
759
+ self.ep_size = 1
760
+ self.experts_per_rank = config.n_routed_experts
761
+ self.ep_rank = 0
762
+ self.experts = nn.ModuleList(
763
+ [
764
+ FusedMLP(
765
+ config,
766
+ intermediate_size=config.moe_intermediate_size,
767
+ n_fused=config.n_routed_experts // config.n_fused_experts,
768
+ rank=config.fused_expert_dora_rank,
769
+ adapter_type=config.fused_expert_method
770
+ )
771
+ for i in range(config.n_fused_experts)
772
+ ]
773
+ )
774
+ self.gate = MoEGate(config)
775
+ if config.n_shared_experts is not None:
776
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
777
+ self.shared_experts = DeepseekV2MLP(
778
+ config=config, intermediate_size=intermediate_size
779
+ )
780
+
781
+ # Register inv_mapping_dict as a buffer
782
+ self.register_buffer('inv_mapping_dict', torch.zeros(config.n_fused_experts, config.n_routed_experts // config.n_fused_experts), persistent=True)
783
+
784
+
785
+ def set_ready(self):
786
+ self.experts.to_empty(device="meta")
787
+ del self.experts
788
+ self.ready = True
789
+
790
+ def forward(self, hidden_states):
791
+ identity, orig_shape, hidden_states, topk_idx, topk_weight, aux_loss = self.forward_gate(hidden_states)
792
+
793
+ y = torch.zeros_like(hidden_states, device=hidden_states.device, dtype=hidden_states.dtype)
794
+
795
+ for idx in range(self.inv_mapping_dict.size(0)):
796
+ y += self.forward_fused_expert(idx, hidden_states, topk_idx, topk_weight)
797
+
798
+ y = y.view(*orig_shape)
799
+
800
+ if self.config.n_shared_experts is not None:
801
+ y = y + self.shared_experts(identity)
802
+ return y
803
+
804
+ def forward_gate(self, hidden_states):
805
+ identity = hidden_states
806
+ orig_shape = hidden_states.shape
807
+
808
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
809
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
810
+
811
+ return identity, orig_shape, hidden_states, topk_idx, topk_weight, aux_loss
812
+
813
+ def forward_fused_expert(self, idx, hidden_states, topk_idx, topk_weight):
814
+ indexes = self.inv_mapping_dict[idx].tolist()
815
+
816
+ flat_topk_weight = torch.zeros((hidden_states.shape[0], len(indexes)), device=hidden_states.device, dtype=hidden_states.dtype)
817
+
818
+ for i, index in enumerate(indexes):
819
+ flat_topk_weight[:, i] = torch.sum(topk_weight * (topk_idx == index), axis=-1)
820
+
821
+ scalar = torch.sum(flat_topk_weight, axis=-1, keepdim=True) # keeping the total weight of the experts
822
+
823
+ flat_topk_weight[flat_topk_weight == 0] = -1e9
824
+ flat_topk_weight = torch.softmax(flat_topk_weight, dim=-1)
825
+
826
+ output = torch.zeros_like(hidden_states, device=hidden_states.device, dtype=hidden_states.dtype)
827
+
828
+ 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
829
+
830
+ return scalar * output # Weighting is already taken into account by how the Fused is trained
831
+
832
+
833
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
834
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
835
+ """
836
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
837
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
838
+ """
839
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
840
+ if n_rep == 1:
841
+ return hidden_states
842
+ hidden_states = hidden_states[:, :, None, :, :].expand(
843
+ batch, num_key_value_heads, n_rep, slen, head_dim
844
+ )
845
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
846
+
847
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2
848
+ class DeepseekV2Attention(nn.Module):
849
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
850
+
851
+ def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None):
852
+ super().__init__()
853
+ self.config = config
854
+ self.layer_idx = layer_idx
855
+ if layer_idx is None:
856
+ logger.warning_once(
857
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
858
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
859
+ "when creating this class."
860
+ )
861
+
862
+ self.attention_dropout = config.attention_dropout
863
+ self.hidden_size = config.hidden_size
864
+ self.num_heads = config.num_attention_heads
865
+
866
+ self.max_position_embeddings = config.max_position_embeddings
867
+ self.rope_theta = config.rope_theta
868
+ self.q_lora_rank = config.q_lora_rank
869
+ self.qk_rope_head_dim = config.qk_rope_head_dim
870
+ self.kv_lora_rank = config.kv_lora_rank
871
+ self.v_head_dim = config.v_head_dim
872
+ self.qk_nope_head_dim = config.qk_nope_head_dim
873
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
874
+
875
+ self.is_causal = True
876
+
877
+ if self.q_lora_rank is None:
878
+ self.q_proj = nn.Linear(
879
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
880
+ )
881
+ else:
882
+ self.q_a_proj = nn.Linear(
883
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
884
+ )
885
+ self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank)
886
+ self.q_b_proj = nn.Linear(
887
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
888
+ )
889
+
890
+ self.kv_a_proj_with_mqa = nn.Linear(
891
+ self.hidden_size,
892
+ config.kv_lora_rank + config.qk_rope_head_dim,
893
+ bias=config.attention_bias,
894
+ )
895
+ self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank)
896
+ self.kv_b_proj = nn.Linear(
897
+ config.kv_lora_rank,
898
+ self.num_heads
899
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
900
+ bias=False,
901
+ )
902
+
903
+ self.o_proj = nn.Linear(
904
+ self.num_heads * self.v_head_dim,
905
+ self.hidden_size,
906
+ bias=config.attention_bias,
907
+ )
908
+ self._init_rope()
909
+
910
+ self.softmax_scale = self.q_head_dim ** (-0.5)
911
+ if self.config.rope_scaling is not None:
912
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
913
+ scaling_factor = self.config.rope_scaling["factor"]
914
+ if mscale_all_dim:
915
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
916
+ self.softmax_scale = self.softmax_scale * mscale * mscale
917
+
918
+ def _init_rope(self):
919
+ if self.config.rope_scaling is None:
920
+ self.rotary_emb = DeepseekV2RotaryEmbedding(
921
+ self.qk_rope_head_dim,
922
+ max_position_embeddings=self.max_position_embeddings,
923
+ base=self.rope_theta,
924
+ )
925
+ else:
926
+ scaling_type = self.config.rope_scaling["type"]
927
+ scaling_factor = self.config.rope_scaling["factor"]
928
+ if scaling_type == "linear":
929
+ self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
930
+ self.qk_rope_head_dim,
931
+ max_position_embeddings=self.max_position_embeddings,
932
+ scaling_factor=scaling_factor,
933
+ base=self.rope_theta,
934
+ )
935
+ elif scaling_type == "dynamic":
936
+ self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
937
+ self.qk_rope_head_dim,
938
+ max_position_embeddings=self.max_position_embeddings,
939
+ scaling_factor=scaling_factor,
940
+ base=self.rope_theta,
941
+ )
942
+ elif scaling_type == "yarn":
943
+ kwargs = {
944
+ key: self.config.rope_scaling[key]
945
+ for key in [
946
+ "original_max_position_embeddings",
947
+ "beta_fast",
948
+ "beta_slow",
949
+ "mscale",
950
+ "mscale_all_dim",
951
+ ]
952
+ if key in self.config.rope_scaling
953
+ }
954
+ self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
955
+ self.qk_rope_head_dim,
956
+ max_position_embeddings=self.max_position_embeddings,
957
+ scaling_factor=scaling_factor,
958
+ base=self.rope_theta,
959
+ **kwargs,
960
+ )
961
+ else:
962
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
963
+
964
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
965
+ return (
966
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
967
+ .transpose(1, 2)
968
+ .contiguous()
969
+ )
970
+
971
+ def forward(
972
+ self,
973
+ hidden_states: torch.Tensor,
974
+ attention_mask: Optional[torch.Tensor] = None,
975
+ position_ids: Optional[torch.LongTensor] = None,
976
+ past_key_value: Optional[Cache] = None,
977
+ output_attentions: bool = False,
978
+ use_cache: bool = False,
979
+ **kwargs,
980
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
981
+ if "padding_mask" in kwargs:
982
+ warnings.warn(
983
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
984
+ )
985
+ bsz, q_len, _ = hidden_states.size()
986
+
987
+ if self.q_lora_rank is None:
988
+ q = self.q_proj(hidden_states)
989
+ else:
990
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
991
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
992
+ q_nope, q_pe = torch.split(
993
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
994
+ )
995
+
996
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
997
+ compressed_kv, k_pe = torch.split(
998
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
999
+ )
1000
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1001
+ kv = (
1002
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1003
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1004
+ .transpose(1, 2)
1005
+ )
1006
+
1007
+ k_nope, value_states = torch.split(
1008
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1009
+ )
1010
+ kv_seq_len = value_states.shape[-2]
1011
+ if past_key_value is not None:
1012
+ if self.layer_idx is None:
1013
+ raise ValueError(
1014
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
1015
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
1016
+ "with a layer index."
1017
+ )
1018
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1019
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1020
+
1021
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1022
+
1023
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1024
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1025
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1026
+
1027
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1028
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1029
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1030
+ if past_key_value is not None:
1031
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1032
+ key_states, value_states = past_key_value.update(
1033
+ key_states, value_states, self.layer_idx, cache_kwargs
1034
+ )
1035
+
1036
+ attn_weights = (
1037
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
1038
+ )
1039
+
1040
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
1041
+ raise ValueError(
1042
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
1043
+ f" {attn_weights.size()}"
1044
+ )
1045
+ assert attention_mask is not None
1046
+ if attention_mask is not None:
1047
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1048
+ raise ValueError(
1049
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1050
+ )
1051
+ attn_weights = attn_weights + attention_mask
1052
+
1053
+ # upcast attention to fp32
1054
+ attn_weights = nn.functional.softmax(
1055
+ attn_weights, dim=-1, dtype=torch.float32
1056
+ ).to(query_states.dtype)
1057
+ attn_weights = nn.functional.dropout(
1058
+ attn_weights, p=self.attention_dropout, training=self.training
1059
+ )
1060
+ attn_output = torch.matmul(attn_weights, value_states)
1061
+
1062
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
1063
+ raise ValueError(
1064
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
1065
+ f" {attn_output.size()}"
1066
+ )
1067
+
1068
+ attn_output = attn_output.transpose(1, 2).contiguous()
1069
+
1070
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
1071
+
1072
+ attn_output = self.o_proj(attn_output)
1073
+
1074
+ if not output_attentions:
1075
+ attn_weights = None
1076
+
1077
+ return attn_output, attn_weights, past_key_value
1078
+
1079
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2
1080
+ class DeepseekV2FlashAttention2(DeepseekV2Attention):
1081
+ """
1082
+ DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
1083
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
1084
+ flash attention and deal with padding tokens in case the input contains any of them.
1085
+ """
1086
+
1087
+ def __init__(self, *args, **kwargs):
1088
+ super().__init__(*args, **kwargs)
1089
+
1090
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1091
+ # 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.
1092
+ # 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).
1093
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1094
+
1095
+ def forward(
1096
+ self,
1097
+ hidden_states: torch.Tensor,
1098
+ attention_mask: Optional[torch.LongTensor] = None,
1099
+ position_ids: Optional[torch.LongTensor] = None,
1100
+ past_key_value: Optional[Cache] = None,
1101
+ output_attentions: bool = False,
1102
+ use_cache: bool = False,
1103
+ **kwargs,
1104
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1105
+ # DeepseekV2FlashAttention2 attention does not support output_attentions
1106
+ if "padding_mask" in kwargs:
1107
+ warnings.warn(
1108
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1109
+ )
1110
+
1111
+ # overwrite attention_mask with padding_mask
1112
+ attention_mask = kwargs.pop("padding_mask")
1113
+
1114
+ output_attentions = False
1115
+
1116
+ bsz, q_len, _ = hidden_states.size()
1117
+
1118
+ if self.q_lora_rank is None:
1119
+ q = self.q_proj(hidden_states)
1120
+ else:
1121
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1122
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1123
+ q_nope, q_pe = torch.split(
1124
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1125
+ )
1126
+
1127
+ # Flash attention requires the input to have the shape
1128
+ # batch_size x seq_length x head_dim x hidden_dim
1129
+ # therefore we just need to keep the original shape
1130
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1131
+ compressed_kv, k_pe = torch.split(
1132
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1133
+ )
1134
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1135
+ kv = (
1136
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1137
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1138
+ .transpose(1, 2)
1139
+ )
1140
+
1141
+ k_nope, value_states = torch.split(
1142
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1143
+ )
1144
+ kv_seq_len = value_states.shape[-2]
1145
+
1146
+ kv_seq_len = value_states.shape[-2]
1147
+ if past_key_value is not None:
1148
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1149
+
1150
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1151
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1152
+
1153
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1154
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1155
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1156
+
1157
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1158
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1159
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1160
+
1161
+ if self.q_head_dim != self.v_head_dim:
1162
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1163
+
1164
+ if past_key_value is not None:
1165
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1166
+ key_states, value_states = past_key_value.update(
1167
+ key_states, value_states, self.layer_idx, cache_kwargs
1168
+ )
1169
+
1170
+ # 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
1171
+ # to be able to avoid many of these transpose/reshape/view.
1172
+ query_states = query_states.transpose(1, 2)
1173
+ key_states = key_states.transpose(1, 2)
1174
+ value_states = value_states.transpose(1, 2)
1175
+
1176
+ dropout_rate = self.attention_dropout if self.training else 0.0
1177
+
1178
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1179
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1180
+ # cast them back in the correct dtype just to be sure everything works as expected.
1181
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1182
+ # in fp32. (DeepseekV2RMSNorm handles it correctly)
1183
+
1184
+ input_dtype = query_states.dtype
1185
+ if input_dtype == torch.float32:
1186
+ # Handle the case where the model is quantized
1187
+ if hasattr(self.config, "_pre_quantization_dtype"):
1188
+ target_dtype = self.config._pre_quantization_dtype
1189
+ elif torch.is_autocast_enabled():
1190
+ target_dtype = torch.get_autocast_gpu_dtype()
1191
+ else:
1192
+ target_dtype = self.q_proj.weight.dtype if self.q_lora_rank is None else self.q_a_proj.weight.dtype
1193
+
1194
+ logger.warning_once(
1195
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1196
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1197
+ f" {target_dtype}."
1198
+ )
1199
+
1200
+ query_states = query_states.to(target_dtype)
1201
+ key_states = key_states.to(target_dtype)
1202
+ value_states = value_states.to(target_dtype)
1203
+
1204
+ attn_output = self._flash_attention_forward(
1205
+ query_states,
1206
+ key_states,
1207
+ value_states,
1208
+ attention_mask,
1209
+ q_len,
1210
+ dropout=dropout_rate,
1211
+ softmax_scale=self.softmax_scale,
1212
+ )
1213
+ if self.q_head_dim != self.v_head_dim:
1214
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1215
+
1216
+ attn_output = attn_output.reshape(
1217
+ bsz, q_len, self.num_heads * self.v_head_dim
1218
+ ).contiguous()
1219
+ attn_output = self.o_proj(attn_output)
1220
+
1221
+ if not output_attentions:
1222
+ attn_weights = None
1223
+
1224
+ return attn_output, attn_weights, past_key_value
1225
+
1226
+ def _flash_attention_forward(
1227
+ self,
1228
+ query_states,
1229
+ key_states,
1230
+ value_states,
1231
+ attention_mask,
1232
+ query_length,
1233
+ dropout=0.0,
1234
+ softmax_scale=None,
1235
+ ):
1236
+ """
1237
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1238
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1239
+
1240
+ Args:
1241
+ query_states (`torch.Tensor`):
1242
+ Input query states to be passed to Flash Attention API
1243
+ key_states (`torch.Tensor`):
1244
+ Input key states to be passed to Flash Attention API
1245
+ value_states (`torch.Tensor`):
1246
+ Input value states to be passed to Flash Attention API
1247
+ attention_mask (`torch.Tensor`):
1248
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1249
+ position of padding tokens and 1 for the position of non-padding tokens.
1250
+ dropout (`int`, *optional*):
1251
+ Attention dropout
1252
+ softmax_scale (`float`, *optional*):
1253
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1254
+ """
1255
+ if not self._flash_attn_uses_top_left_mask:
1256
+ causal = self.is_causal
1257
+ else:
1258
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__.
1259
+ causal = self.is_causal and query_length != 1
1260
+
1261
+ # Contains at least one padding token in the sequence
1262
+ if attention_mask is not None:
1263
+ batch_size = query_states.shape[0]
1264
+ (
1265
+ query_states,
1266
+ key_states,
1267
+ value_states,
1268
+ indices_q,
1269
+ cu_seq_lens,
1270
+ max_seq_lens,
1271
+ ) = self._upad_input(
1272
+ query_states, key_states, value_states, attention_mask, query_length
1273
+ )
1274
+
1275
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1276
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1277
+
1278
+ attn_output_unpad = flash_attn_varlen_func(
1279
+ query_states,
1280
+ key_states,
1281
+ value_states,
1282
+ cu_seqlens_q=cu_seqlens_q,
1283
+ cu_seqlens_k=cu_seqlens_k,
1284
+ max_seqlen_q=max_seqlen_in_batch_q,
1285
+ max_seqlen_k=max_seqlen_in_batch_k,
1286
+ dropout_p=dropout,
1287
+ softmax_scale=softmax_scale,
1288
+ causal=causal,
1289
+ )
1290
+
1291
+ attn_output = pad_input(
1292
+ attn_output_unpad, indices_q, batch_size, query_length
1293
+ )
1294
+ else:
1295
+ attn_output = flash_attn_func(
1296
+ query_states,
1297
+ key_states,
1298
+ value_states,
1299
+ dropout,
1300
+ softmax_scale=softmax_scale,
1301
+ causal=causal,
1302
+ )
1303
+
1304
+ return attn_output
1305
+
1306
+ def _upad_input(
1307
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1308
+ ):
1309
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1310
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1311
+
1312
+ key_layer = index_first_axis(
1313
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1314
+ indices_k,
1315
+ )
1316
+ value_layer = index_first_axis(
1317
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1318
+ indices_k,
1319
+ )
1320
+ if query_length == kv_seq_len:
1321
+ query_layer = index_first_axis(
1322
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1323
+ indices_k,
1324
+ )
1325
+ cu_seqlens_q = cu_seqlens_k
1326
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1327
+ indices_q = indices_k
1328
+ elif query_length == 1:
1329
+ max_seqlen_in_batch_q = 1
1330
+ cu_seqlens_q = torch.arange(
1331
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1332
+ ) # There is a memcpy here, that is very bad.
1333
+ indices_q = cu_seqlens_q[:-1]
1334
+ query_layer = query_layer.squeeze(1)
1335
+ else:
1336
+ # The -q_len: slice assumes left padding.
1337
+ attention_mask = attention_mask[:, -query_length:]
1338
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1339
+ query_layer, attention_mask
1340
+ )
1341
+
1342
+ return (
1343
+ query_layer,
1344
+ key_layer,
1345
+ value_layer,
1346
+ indices_q,
1347
+ (cu_seqlens_q, cu_seqlens_k),
1348
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1349
+ )
1350
+
1351
+
1352
+ ATTENTION_CLASSES = {
1353
+ "eager": DeepseekV2Attention,
1354
+ "flash_attention_2": DeepseekV2FlashAttention2,
1355
+ }
1356
+
1357
+
1358
+ class DeepseekV2DecoderLayer(nn.Module):
1359
+ def __init__(self, config: DeepseekV2Config, layer_idx: int):
1360
+ super().__init__()
1361
+ self.hidden_size = config.hidden_size
1362
+
1363
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1364
+ config=config, layer_idx=layer_idx
1365
+ )
1366
+
1367
+ self.mlp = (
1368
+ FusedMOE(config)
1369
+ if (
1370
+ config.n_routed_experts is not None
1371
+ and layer_idx >= config.first_k_dense_replace
1372
+ and layer_idx % config.moe_layer_freq == 0
1373
+ )
1374
+ else DeepseekV2MLP(config)
1375
+ )
1376
+ self.input_layernorm = DeepseekV2RMSNorm(
1377
+ config.hidden_size, eps=config.rms_norm_eps
1378
+ )
1379
+ self.post_attention_layernorm = DeepseekV2RMSNorm(
1380
+ config.hidden_size, eps=config.rms_norm_eps
1381
+ )
1382
+
1383
+ def forward(
1384
+ self,
1385
+ hidden_states: torch.Tensor,
1386
+ attention_mask: Optional[torch.Tensor] = None,
1387
+ position_ids: Optional[torch.LongTensor] = None,
1388
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1389
+ output_attentions: Optional[bool] = False,
1390
+ use_cache: Optional[bool] = False,
1391
+ **kwargs,
1392
+ ) -> Tuple[
1393
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1394
+ ]:
1395
+ """
1396
+ Args:
1397
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1398
+ attention_mask (`torch.FloatTensor`, *optional*):
1399
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1400
+ query_sequence_length, key_sequence_length)` if default attention is used.
1401
+ output_attentions (`bool`, *optional*):
1402
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1403
+ returned tensors for more detail.
1404
+ use_cache (`bool`, *optional*):
1405
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1406
+ (see `past_key_values`).
1407
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1408
+ """
1409
+ if "padding_mask" in kwargs:
1410
+ warnings.warn(
1411
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1412
+ )
1413
+ residual = hidden_states
1414
+
1415
+ hidden_states = self.input_layernorm(hidden_states)
1416
+
1417
+ # Self Attention
1418
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1419
+ hidden_states=hidden_states,
1420
+ attention_mask=attention_mask,
1421
+ position_ids=position_ids,
1422
+ past_key_value=past_key_value,
1423
+ output_attentions=output_attentions,
1424
+ use_cache=use_cache,
1425
+ **kwargs,
1426
+ )
1427
+ hidden_states = residual + hidden_states
1428
+
1429
+ # Fully Connected
1430
+ residual = hidden_states
1431
+ hidden_states = self.post_attention_layernorm(hidden_states)
1432
+ hidden_states = self.mlp(hidden_states)
1433
+ hidden_states = residual + hidden_states
1434
+
1435
+ outputs = (hidden_states,)
1436
+
1437
+ if output_attentions:
1438
+ outputs += (self_attn_weights,)
1439
+
1440
+ if use_cache:
1441
+ outputs += (present_key_value,)
1442
+
1443
+ return outputs
1444
+
1445
+
1446
+ DeepseekV2_START_DOCSTRING = r"""
1447
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1448
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1449
+ etc.)
1450
+
1451
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1452
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1453
+ and behavior.
1454
+
1455
+ Parameters:
1456
+ config ([`DeepseekV2Config`]):
1457
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1458
+ load the weights associated with the model, only the configuration. Check out the
1459
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1460
+ """
1461
+
1462
+
1463
+ @add_start_docstrings(
1464
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1465
+ DeepseekV2_START_DOCSTRING,
1466
+ )
1467
+ class DeepseekV2PreTrainedModel(PreTrainedModel):
1468
+ config_class = DeepseekV2Config
1469
+ base_model_prefix = "model"
1470
+ supports_gradient_checkpointing = True
1471
+ _no_split_modules = ["DeepseekV2DecoderLayer"]
1472
+ _skip_keys_device_placement = "past_key_values"
1473
+ _supports_flash_attn_2 = True
1474
+ _supports_cache_class = True
1475
+
1476
+ def _init_weights(self, module):
1477
+ std = self.config.initializer_range
1478
+ if isinstance(module, nn.Linear):
1479
+ module.weight.data.normal_(mean=0.0, std=std)
1480
+ if module.bias is not None:
1481
+ module.bias.data.zero_()
1482
+ elif isinstance(module, nn.Embedding):
1483
+ module.weight.data.normal_(mean=0.0, std=std)
1484
+ if module.padding_idx is not None:
1485
+ module.weight.data[module.padding_idx].zero_()
1486
+
1487
+
1488
+ DeepseekV2_INPUTS_DOCSTRING = r"""
1489
+ Args:
1490
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1491
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1492
+ it.
1493
+
1494
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1495
+ [`PreTrainedTokenizer.__call__`] for details.
1496
+
1497
+ [What are input IDs?](../glossary#input-ids)
1498
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1499
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1500
+
1501
+ - 1 for tokens that are **not masked**,
1502
+ - 0 for tokens that are **masked**.
1503
+
1504
+ [What are attention masks?](../glossary#attention-mask)
1505
+
1506
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1507
+ [`PreTrainedTokenizer.__call__`] for details.
1508
+
1509
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1510
+ `past_key_values`).
1511
+
1512
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1513
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1514
+ information on the default strategy.
1515
+
1516
+ - 1 indicates the head is **not masked**,
1517
+ - 0 indicates the head is **masked**.
1518
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1519
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1520
+ config.n_positions - 1]`.
1521
+
1522
+ [What are position IDs?](../glossary#position-ids)
1523
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1524
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1525
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1526
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1527
+
1528
+ Two formats are allowed:
1529
+ - a [`~cache_utils.Cache`] instance;
1530
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1531
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1532
+ cache format.
1533
+
1534
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1535
+ legacy cache format will be returned.
1536
+
1537
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1538
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1539
+ of shape `(batch_size, sequence_length)`.
1540
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1541
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1542
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1543
+ model's internal embedding lookup matrix.
1544
+ use_cache (`bool`, *optional*):
1545
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1546
+ `past_key_values`).
1547
+ output_attentions (`bool`, *optional*):
1548
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1549
+ tensors for more detail.
1550
+ output_hidden_states (`bool`, *optional*):
1551
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1552
+ more detail.
1553
+ return_dict (`bool`, *optional*):
1554
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1555
+ """
1556
+
1557
+
1558
+ @add_start_docstrings(
1559
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1560
+ DeepseekV2_START_DOCSTRING,
1561
+ )
1562
+ class DeepseekV2Model(DeepseekV2PreTrainedModel):
1563
+ """
1564
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
1565
+
1566
+ Args:
1567
+ config: DeepseekV2Config
1568
+ """
1569
+
1570
+ def __init__(self, config: DeepseekV2Config):
1571
+ super().__init__(config)
1572
+ self.padding_idx = config.pad_token_id
1573
+ self.vocab_size = config.vocab_size
1574
+
1575
+ self.embed_tokens = nn.Embedding(
1576
+ config.vocab_size, config.hidden_size, self.padding_idx
1577
+ )
1578
+ self.layers = nn.ModuleList(
1579
+ [
1580
+ DeepseekV2DecoderLayer(config, layer_idx)
1581
+ for layer_idx in range(config.num_hidden_layers)
1582
+ ]
1583
+ )
1584
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1585
+ self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1586
+
1587
+ self.gradient_checkpointing = False
1588
+ # Initialize weights and apply final processing
1589
+ self.post_init()
1590
+
1591
+ def get_input_embeddings(self):
1592
+ return self.embed_tokens
1593
+
1594
+ def set_input_embeddings(self, value):
1595
+ self.embed_tokens = value
1596
+
1597
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1598
+ def forward(
1599
+ self,
1600
+ input_ids: torch.LongTensor = None,
1601
+ attention_mask: Optional[torch.Tensor] = None,
1602
+ position_ids: Optional[torch.LongTensor] = None,
1603
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1604
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1605
+ use_cache: Optional[bool] = None,
1606
+ output_attentions: Optional[bool] = None,
1607
+ output_hidden_states: Optional[bool] = None,
1608
+ return_dict: Optional[bool] = None,
1609
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1610
+ output_attentions = (
1611
+ output_attentions
1612
+ if output_attentions is not None
1613
+ else self.config.output_attentions
1614
+ )
1615
+ output_hidden_states = (
1616
+ output_hidden_states
1617
+ if output_hidden_states is not None
1618
+ else self.config.output_hidden_states
1619
+ )
1620
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1621
+
1622
+ return_dict = (
1623
+ return_dict if return_dict is not None else self.config.use_return_dict
1624
+ )
1625
+
1626
+ # retrieve input_ids and inputs_embeds
1627
+ if input_ids is not None and inputs_embeds is not None:
1628
+ raise ValueError(
1629
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1630
+ )
1631
+ elif input_ids is not None:
1632
+ batch_size, seq_length = input_ids.shape[:2]
1633
+ elif inputs_embeds is not None:
1634
+ batch_size, seq_length = inputs_embeds.shape[:2]
1635
+ else:
1636
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1637
+
1638
+ if self.gradient_checkpointing and self.training:
1639
+ if use_cache:
1640
+ logger.warning_once(
1641
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1642
+ )
1643
+ use_cache = False
1644
+
1645
+ past_key_values_length = 0
1646
+ if use_cache:
1647
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1648
+ if use_legacy_cache:
1649
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1650
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1651
+
1652
+ if position_ids is None:
1653
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1654
+ position_ids = torch.arange(
1655
+ past_key_values_length,
1656
+ seq_length + past_key_values_length,
1657
+ dtype=torch.long,
1658
+ device=device,
1659
+ )
1660
+ position_ids = position_ids.unsqueeze(0)
1661
+
1662
+ if inputs_embeds is None:
1663
+ inputs_embeds = self.embed_tokens(input_ids)
1664
+
1665
+ if self._use_flash_attention_2:
1666
+ # 2d mask is passed through the layers
1667
+ attention_mask = (
1668
+ attention_mask
1669
+ if (attention_mask is not None and 0 in attention_mask)
1670
+ else None
1671
+ )
1672
+ else:
1673
+ # 4d mask is passed through the layers
1674
+ attention_mask = _prepare_4d_causal_attention_mask(
1675
+ attention_mask,
1676
+ (batch_size, seq_length),
1677
+ inputs_embeds,
1678
+ past_key_values_length,
1679
+ )
1680
+
1681
+ # embed positions
1682
+ hidden_states = inputs_embeds
1683
+
1684
+ # decoder layers
1685
+ all_hidden_states = () if output_hidden_states else None
1686
+ all_self_attns = () if output_attentions else None
1687
+ next_decoder_cache = None
1688
+
1689
+ for decoder_layer in self.layers:
1690
+ if output_hidden_states:
1691
+ all_hidden_states += (hidden_states,)
1692
+
1693
+ if self.gradient_checkpointing and self.training:
1694
+ layer_outputs = self._gradient_checkpointing_func(
1695
+ decoder_layer.__call__,
1696
+ hidden_states,
1697
+ attention_mask,
1698
+ position_ids,
1699
+ past_key_values,
1700
+ output_attentions,
1701
+ use_cache,
1702
+ )
1703
+ else:
1704
+ layer_outputs = decoder_layer(
1705
+ hidden_states,
1706
+ attention_mask=attention_mask,
1707
+ position_ids=position_ids,
1708
+ past_key_value=past_key_values,
1709
+ output_attentions=output_attentions,
1710
+ use_cache=use_cache,
1711
+ )
1712
+
1713
+ hidden_states = layer_outputs[0]
1714
+
1715
+ if use_cache:
1716
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1717
+
1718
+ if output_attentions:
1719
+ all_self_attns += (layer_outputs[1],)
1720
+
1721
+ hidden_states = self.norm(hidden_states)
1722
+
1723
+ # add hidden states from the last decoder layer
1724
+ if output_hidden_states:
1725
+ all_hidden_states += (hidden_states,)
1726
+
1727
+ next_cache = None
1728
+ if use_cache:
1729
+ next_cache = (
1730
+ next_decoder_cache.to_legacy_cache()
1731
+ if use_legacy_cache
1732
+ else next_decoder_cache
1733
+ )
1734
+ if not return_dict:
1735
+ return tuple(
1736
+ v
1737
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1738
+ if v is not None
1739
+ )
1740
+ return BaseModelOutputWithPast(
1741
+ last_hidden_state=hidden_states,
1742
+ past_key_values=next_cache,
1743
+ hidden_states=all_hidden_states,
1744
+ attentions=all_self_attns,
1745
+ )
1746
+
1747
+
1748
+ class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
1749
+ _tied_weights_keys = ["lm_head.weight"]
1750
+
1751
+ def __init__(self, config):
1752
+ super().__init__(config)
1753
+ self.model = DeepseekV2Model(config)
1754
+ self.vocab_size = config.vocab_size
1755
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1756
+
1757
+ # Initialize weights and apply final processing
1758
+ self.post_init()
1759
+
1760
+ def get_input_embeddings(self):
1761
+ return self.model.embed_tokens
1762
+
1763
+ def set_input_embeddings(self, value):
1764
+ self.model.embed_tokens = value
1765
+
1766
+ def get_output_embeddings(self):
1767
+ return self.lm_head
1768
+
1769
+ def set_output_embeddings(self, new_embeddings):
1770
+ self.lm_head = new_embeddings
1771
+
1772
+ def set_decoder(self, decoder):
1773
+ self.model = decoder
1774
+
1775
+ def get_decoder(self):
1776
+ return self.model
1777
+
1778
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1779
+ @replace_return_docstrings(
1780
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1781
+ )
1782
+ def forward(
1783
+ self,
1784
+ input_ids: torch.LongTensor = None,
1785
+ attention_mask: Optional[torch.Tensor] = None,
1786
+ position_ids: Optional[torch.LongTensor] = None,
1787
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1788
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1789
+ labels: Optional[torch.LongTensor] = None,
1790
+ use_cache: Optional[bool] = None,
1791
+ output_attentions: Optional[bool] = None,
1792
+ output_hidden_states: Optional[bool] = None,
1793
+ return_dict: Optional[bool] = None,
1794
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1795
+ r"""
1796
+ Args:
1797
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1798
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1799
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1800
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1801
+
1802
+ Returns:
1803
+
1804
+ Example:
1805
+
1806
+ ```python
1807
+ >>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
1808
+
1809
+ >>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1810
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1811
+
1812
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1813
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1814
+
1815
+ >>> # Generate
1816
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1817
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1818
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1819
+ ```"""
1820
+ output_attentions = (
1821
+ output_attentions
1822
+ if output_attentions is not None
1823
+ else self.config.output_attentions
1824
+ )
1825
+ output_hidden_states = (
1826
+ output_hidden_states
1827
+ if output_hidden_states is not None
1828
+ else self.config.output_hidden_states
1829
+ )
1830
+ return_dict = (
1831
+ return_dict if return_dict is not None else self.config.use_return_dict
1832
+ )
1833
+
1834
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1835
+ outputs = self.model(
1836
+ input_ids=input_ids,
1837
+ attention_mask=attention_mask,
1838
+ position_ids=position_ids,
1839
+ past_key_values=past_key_values,
1840
+ inputs_embeds=inputs_embeds,
1841
+ use_cache=use_cache,
1842
+ output_attentions=output_attentions,
1843
+ output_hidden_states=output_hidden_states,
1844
+ return_dict=return_dict,
1845
+ )
1846
+
1847
+ hidden_states = outputs[0]
1848
+ logits = self.lm_head(hidden_states)
1849
+ logits = logits.float()
1850
+
1851
+ loss = None
1852
+ if labels is not None:
1853
+ # Shift so that tokens < n predict n
1854
+ shift_logits = logits[..., :-1, :].contiguous()
1855
+ shift_labels = labels[..., 1:].contiguous()
1856
+ # Flatten the tokens
1857
+ loss_fct = CrossEntropyLoss()
1858
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1859
+ shift_labels = shift_labels.view(-1)
1860
+ # Enable model parallelism
1861
+ shift_labels = shift_labels.to(shift_logits.device)
1862
+ loss = loss_fct(shift_logits, shift_labels)
1863
+
1864
+ if not return_dict:
1865
+ output = (logits,) + outputs[1:]
1866
+ return (loss,) + output if loss is not None else output
1867
+
1868
+ return CausalLMOutputWithPast(
1869
+ loss=loss,
1870
+ logits=logits,
1871
+ past_key_values=outputs.past_key_values,
1872
+ hidden_states=outputs.hidden_states,
1873
+ attentions=outputs.attentions,
1874
+ )
1875
+
1876
+ def prepare_inputs_for_generation(
1877
+ self,
1878
+ input_ids,
1879
+ past_key_values=None,
1880
+ attention_mask=None,
1881
+ inputs_embeds=None,
1882
+ **kwargs,
1883
+ ):
1884
+ if past_key_values is not None:
1885
+ if isinstance(past_key_values, Cache):
1886
+ cache_length = past_key_values.get_seq_length()
1887
+ past_length = past_key_values.seen_tokens
1888
+ max_cache_length = past_key_values.get_max_length()
1889
+ else:
1890
+ cache_length = past_length = past_key_values[0][0].shape[2]
1891
+ max_cache_length = None
1892
+
1893
+ # Keep only the unprocessed tokens:
1894
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1895
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1896
+ # input)
1897
+ if (
1898
+ attention_mask is not None
1899
+ and attention_mask.shape[1] > input_ids.shape[1]
1900
+ ):
1901
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1902
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1903
+ # input_ids based on the past_length.
1904
+ elif past_length < input_ids.shape[1]:
1905
+ input_ids = input_ids[:, past_length:]
1906
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1907
+
1908
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1909
+ if (
1910
+ max_cache_length is not None
1911
+ and attention_mask is not None
1912
+ and cache_length + input_ids.shape[1] > max_cache_length
1913
+ ):
1914
+ attention_mask = attention_mask[:, -max_cache_length:]
1915
+
1916
+ position_ids = kwargs.get("position_ids", None)
1917
+ if attention_mask is not None and position_ids is None:
1918
+ # create position_ids on the fly for batch generation
1919
+ position_ids = attention_mask.long().cumsum(-1) - 1
1920
+ position_ids.masked_fill_(attention_mask == 0, 1)
1921
+ if past_key_values:
1922
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1923
+
1924
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1925
+ if inputs_embeds is not None and past_key_values is None:
1926
+ model_inputs = {"inputs_embeds": inputs_embeds}
1927
+ else:
1928
+ model_inputs = {"input_ids": input_ids}
1929
+
1930
+ model_inputs.update(
1931
+ {
1932
+ "position_ids": position_ids,
1933
+ "past_key_values": past_key_values,
1934
+ "use_cache": kwargs.get("use_cache"),
1935
+ "attention_mask": attention_mask,
1936
+ }
1937
+ )
1938
+ return model_inputs
1939
+
1940
+ @staticmethod
1941
+ def _reorder_cache(past_key_values, beam_idx):
1942
+ reordered_past = ()
1943
+ for layer_past in past_key_values:
1944
+ reordered_past += (
1945
+ tuple(
1946
+ past_state.index_select(0, beam_idx.to(past_state.device))
1947
+ for past_state in layer_past
1948
+ ),
1949
+ )
1950
+ return reordered_past
1951
+
1952
+
1953
+ @add_start_docstrings(
1954
+ """
1955
+ The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
1956
+
1957
+ [`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1958
+ (e.g. GPT-2) do.
1959
+
1960
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1961
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1962
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1963
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1964
+ each row of the batch).
1965
+ """,
1966
+ DeepseekV2_START_DOCSTRING,
1967
+ )
1968
+ class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel):
1969
+ def __init__(self, config):
1970
+ super().__init__(config)
1971
+ self.num_labels = config.num_labels
1972
+ self.model = DeepseekV2Model(config)
1973
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1974
+
1975
+ # Initialize weights and apply final processing
1976
+ self.post_init()
1977
+
1978
+ def get_input_embeddings(self):
1979
+ return self.model.embed_tokens
1980
+
1981
+ def set_input_embeddings(self, value):
1982
+ self.model.embed_tokens = value
1983
+
1984
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1985
+ def forward(
1986
+ self,
1987
+ input_ids: torch.LongTensor = None,
1988
+ attention_mask: Optional[torch.Tensor] = None,
1989
+ position_ids: Optional[torch.LongTensor] = None,
1990
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1991
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1992
+ labels: Optional[torch.LongTensor] = None,
1993
+ use_cache: Optional[bool] = None,
1994
+ output_attentions: Optional[bool] = None,
1995
+ output_hidden_states: Optional[bool] = None,
1996
+ return_dict: Optional[bool] = None,
1997
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1998
+ r"""
1999
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2000
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2001
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2002
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2003
+ """
2004
+ return_dict = (
2005
+ return_dict if return_dict is not None else self.config.use_return_dict
2006
+ )
2007
+
2008
+ transformer_outputs = self.model(
2009
+ input_ids,
2010
+ attention_mask=attention_mask,
2011
+ position_ids=position_ids,
2012
+ past_key_values=past_key_values,
2013
+ inputs_embeds=inputs_embeds,
2014
+ use_cache=use_cache,
2015
+ output_attentions=output_attentions,
2016
+ output_hidden_states=output_hidden_states,
2017
+ return_dict=return_dict,
2018
+ )
2019
+ hidden_states = transformer_outputs[0]
2020
+ logits = self.score(hidden_states)
2021
+
2022
+ if input_ids is not None:
2023
+ batch_size = input_ids.shape[0]
2024
+ else:
2025
+ batch_size = inputs_embeds.shape[0]
2026
+
2027
+ if self.config.pad_token_id is None and batch_size != 1:
2028
+ raise ValueError(
2029
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2030
+ )
2031
+ if self.config.pad_token_id is None:
2032
+ sequence_lengths = -1
2033
+ else:
2034
+ if input_ids is not None:
2035
+ sequence_lengths = (
2036
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2037
+ ).to(logits.device)
2038
+ else:
2039
+ sequence_lengths = -1
2040
+
2041
+ pooled_logits = logits[
2042
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2043
+ ]
2044
+
2045
+ loss = None
2046
+ if labels is not None:
2047
+ labels = labels.to(logits.device)
2048
+ if self.config.problem_type is None:
2049
+ if self.num_labels == 1:
2050
+ self.config.problem_type = "regression"
2051
+ elif self.num_labels > 1 and (
2052
+ labels.dtype == torch.long or labels.dtype == torch.int
2053
+ ):
2054
+ self.config.problem_type = "single_label_classification"
2055
+ else:
2056
+ self.config.problem_type = "multi_label_classification"
2057
+
2058
+ if self.config.problem_type == "regression":
2059
+ loss_fct = MSELoss()
2060
+ if self.num_labels == 1:
2061
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2062
+ else:
2063
+ loss = loss_fct(pooled_logits, labels)
2064
+ elif self.config.problem_type == "single_label_classification":
2065
+ loss_fct = CrossEntropyLoss()
2066
+ loss = loss_fct(
2067
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2068
+ )
2069
+ elif self.config.problem_type == "multi_label_classification":
2070
+ loss_fct = BCEWithLogitsLoss()
2071
+ loss = loss_fct(pooled_logits, labels)
2072
+ if not return_dict:
2073
+ output = (pooled_logits,) + transformer_outputs[1:]
2074
+ return ((loss,) + output) if loss is not None else output
2075
+
2076
+ return SequenceClassifierOutputWithPast(
2077
+ loss=loss,
2078
+ logits=pooled_logits,
2079
+ past_key_values=transformer_outputs.past_key_values,
2080
+ hidden_states=transformer_outputs.hidden_states,
2081
+ attentions=transformer_outputs.attentions,
2082
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|begin▁of▁sentence|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|end▁of▁sentence|>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|end▁of▁sentence|>",
18
+ "lstrip": false,
19
+ "normalized": true,
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
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "100000": {
7
+ "content": "<|begin▁of▁sentence|>",
8
+ "lstrip": false,
9
+ "normalized": true,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "100001": {
15
+ "content": "<|end▁of▁sentence|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "100002": {
23
+ "content": "<|fim▁hole|>",
24
+ "lstrip": false,
25
+ "normalized": true,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "100003": {
31
+ "content": "<|fim▁begin|>",
32
+ "lstrip": false,
33
+ "normalized": true,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": false
37
+ },
38
+ "100004": {
39
+ "content": "<|fim▁end|>",
40
+ "lstrip": false,
41
+ "normalized": true,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": false
45
+ },
46
+ "100005": {
47
+ "content": "<|completion|>",
48
+ "lstrip": false,
49
+ "normalized": true,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": false
53
+ },
54
+ "100006": {
55
+ "content": "<|User|>",
56
+ "lstrip": false,
57
+ "normalized": true,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": false
61
+ },
62
+ "100007": {
63
+ "content": "<|Assistant|>",
64
+ "lstrip": false,
65
+ "normalized": true,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": false
69
+ },
70
+ "100008": {
71
+ "content": "<|EOT|>",
72
+ "lstrip": false,
73
+ "normalized": true,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "100009": {
79
+ "content": "<|tool▁calls▁begin|>",
80
+ "lstrip": false,
81
+ "normalized": true,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": false
85
+ },
86
+ "100010": {
87
+ "content": "<|tool▁calls▁end|>",
88
+ "lstrip": false,
89
+ "normalized": true,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": false
93
+ },
94
+ "100011": {
95
+ "content": "<|tool▁call▁begin|>",
96
+ "lstrip": false,
97
+ "normalized": true,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": false
101
+ },
102
+ "100012": {
103
+ "content": "<|tool▁call▁end|>",
104
+ "lstrip": false,
105
+ "normalized": true,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": false
109
+ },
110
+ "100013": {
111
+ "content": "<|tool▁outputs▁begin|>",
112
+ "lstrip": false,
113
+ "normalized": true,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": false
117
+ },
118
+ "100014": {
119
+ "content": "<|tool▁outputs▁end|>",
120
+ "lstrip": false,
121
+ "normalized": true,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": false
125
+ },
126
+ "100015": {
127
+ "content": "<|tool▁output▁begin|>",
128
+ "lstrip": false,
129
+ "normalized": true,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": false
133
+ },
134
+ "100016": {
135
+ "content": "<|tool▁output▁end|>",
136
+ "lstrip": false,
137
+ "normalized": true,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": false
141
+ },
142
+ "100017": {
143
+ "content": "<|tool▁sep|>",
144
+ "lstrip": false,
145
+ "normalized": true,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": false
149
+ }
150
+ },
151
+ "bos_token": "<|begin▁of▁sentence|>",
152
+ "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{{ bos_token }}{% for message in messages %}{% if message['role'] == 'user' %}{{ 'User: ' + message['content'] + '\n\n' }}{% elif message['role'] == 'assistant' %}{{ 'Assistant: ' + message['content'] + eos_token }}{% elif message['role'] == 'system' %}{{ message['content'] + '\n\n' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}",
153
+ "clean_up_tokenization_spaces": false,
154
+ "eos_token": "<|end▁of▁sentence|>",
155
+ "extra_special_tokens": {},
156
+ "legacy": true,
157
+ "model_max_length": 16384,
158
+ "pad_token": "<|end▁of▁sentence|>",
159
+ "sp_model_kwargs": {},
160
+ "tokenizer_class": "LlamaTokenizer",
161
+ "unk_token": null,
162
+ "use_default_system_prompt": false
163
+ }