autoprogrammer commited on
Commit
8b42d70
·
verified ·
1 Parent(s): 9d39ff7

Upload DeepSeekV2Lite DenseMixer model

Browse files

DeepSeekV2Lite model with DenseMixer architecture

LICENSE ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DEEPSEEK LICENSE AGREEMENT
2
+
3
+ Version 1.0, 23 October 2023
4
+
5
+ Copyright (c) 2023 DeepSeek
6
+
7
+ Section I: PREAMBLE
8
+
9
+ Large generative models are being widely adopted and used, and have the potential to transform the way individuals conceive and benefit from AI or ML technologies.
10
+
11
+ Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
12
+
13
+ In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for content generation.
14
+
15
+ Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this agreement aims to strike a balance between both in order to enable responsible open-science in the field of AI.
16
+
17
+ This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
18
+
19
+ NOW THEREFORE, You and DeepSeek agree as follows:
20
+
21
+ 1. Definitions
22
+ "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
23
+ "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
24
+ "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
25
+ "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
26
+ "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
27
+ "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
28
+ "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
29
+ "DeepSeek" (or "we") means Beijing DeepSeek Artificial Intelligence Fundamental Technology Research Co., Ltd., Hangzhou DeepSeek Artificial Intelligence Fundamental Technology Research Co., Ltd. and/or any of their affiliates.
30
+ "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, etc.
31
+ "Third Parties" means individuals or legal entities that are not under common control with DeepSeek or You.
32
+
33
+ Section II: INTELLECTUAL PROPERTY RIGHTS
34
+
35
+ Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
36
+
37
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, DeepSeek hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
38
+
39
+ 3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, DeepSeek hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by DeepSeek that are necessarily infringed by its contribution(s). If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or works shall terminate as of the date such litigation is asserted or filed.
40
+
41
+
42
+ Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
43
+
44
+ 4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
45
+ a. Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
46
+ b. You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
47
+ c. You must cause any modified files to carry prominent notices stating that You changed the files;
48
+ d. You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
49
+ e. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. – for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
50
+
51
+ 5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
52
+
53
+ 6. The Output You Generate. Except as set forth herein, DeepSeek claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
54
+
55
+ Section IV: OTHER PROVISIONS
56
+
57
+ 7. Updates and Runtime Restrictions. To the maximum extent permitted by law, DeepSeek reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License.
58
+
59
+ 8. Trademarks and related. Nothing in this License permits You to make use of DeepSeek’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by DeepSeek.
60
+
61
+ 9. Personal information, IP rights and related. This Model may contain personal information and works with IP rights. You commit to complying with applicable laws and regulations in the handling of personal information and the use of such works. Please note that DeepSeek's license granted to you to use the Model does not imply that you have obtained a legitimate basis for processing the related information or works. As an independent personal information processor and IP rights user, you need to ensure full compliance with relevant legal and regulatory requirements when handling personal information and works with IP rights that may be contained in the Model, and are willing to assume solely any risks and consequences that may arise from that.
62
+
63
+ 10. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, DeepSeek provides the Model and the Complementary Material on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
64
+
65
+ 11. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall DeepSeek be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if DeepSeek has been advised of the possibility of such damages.
66
+
67
+ 12. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of DeepSeek, and only if You agree to indemnify, defend, and hold DeepSeek harmless for any liability incurred by, or claims asserted against, DeepSeek by reason of your accepting any such warranty or additional liability.
68
+
69
+ 13. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
70
+
71
+ 14. Governing Law and Jurisdiction. This agreement will be governed and construed under PRC laws without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this agreement. The courts located in the domicile of Hangzhou DeepSeek Artificial Intelligence Fundamental Technology Research Co., Ltd. shall have exclusive jurisdiction of any dispute arising out of this agreement.
72
+
73
+ END OF TERMS AND CONDITIONS
74
+
75
+ Attachment A
76
+
77
+ Use Restrictions
78
+
79
+ You agree not to use the Model or Derivatives of the Model:
80
+
81
+ - In any way that violates any applicable national or international law or regulation or infringes upon the lawful rights and interests of any third party;
82
+ - For military use in any way;
83
+ - For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
84
+ - To generate or disseminate verifiably false information and/or content with the purpose of harming others;
85
+ - To generate or disseminate inappropriate content subject to applicable regulatory requirements;
86
+ - To generate or disseminate personal identifiable information without due authorization or for unreasonable use;
87
+ - To defame, disparage or otherwise harass others;
88
+ - For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
89
+ - For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
90
+ - To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
91
+ - For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories.
README.md ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: deepseek
4
+ license_link: https://github.com/deepseek-ai/DeepSeek-V2/blob/main/LICENSE-MODEL
5
+ ---
6
+
7
+ <!-- markdownlint-disable first-line-h1 -->
8
+ <!-- markdownlint-disable html -->
9
+ <!-- markdownlint-disable no-duplicate-header -->
10
+
11
+ <div align="center">
12
+ <img src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/logo.svg?raw=true" width="60%" alt="DeepSeek-V2" />
13
+ </div>
14
+ <hr>
15
+ <div align="center" style="line-height: 1;">
16
+ <a href="https://www.deepseek.com/" target="_blank" style="margin: 2px;">
17
+ <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;"/>
18
+ </a>
19
+ <a href="https://chat.deepseek.com/" target="_blank" style="margin: 2px;">
20
+ <img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-DeepSeek%20V2-536af5?color=536af5&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
21
+ </a>
22
+ <a href="https://huggingface.co/deepseek-ai" target="_blank" style="margin: 2px;">
23
+ <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;"/>
24
+ </a>
25
+ </div>
26
+
27
+ <div align="center" style="line-height: 1;">
28
+ <a href="https://discord.gg/Tc7c45Zzu5" target="_blank" style="margin: 2px;">
29
+ <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;"/>
30
+ </a>
31
+ <a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/qr.jpeg?raw=true" target="_blank" style="margin: 2px;">
32
+ <img alt="Wechat" src="https://img.shields.io/badge/WeChat-DeepSeek%20AI-brightgreen?logo=wechat&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
33
+ </a>
34
+ <a href="https://twitter.com/deepseek_ai" target="_blank" style="margin: 2px;">
35
+ <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;"/>
36
+ </a>
37
+ </div>
38
+
39
+ <div align="center" style="line-height: 1;">
40
+ <a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/LICENSE-CODE" style="margin: 2px;">
41
+ <img alt="Code License" src="https://img.shields.io/badge/Code_License-MIT-f5de53?&color=f5de53" style="display: inline-block; vertical-align: middle;"/>
42
+ </a>
43
+ <a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/LICENSE-MODEL" style="margin: 2px;">
44
+ <img alt="Model License" src="https://img.shields.io/badge/Model_License-Model_Agreement-f5de53?&color=f5de53" style="display: inline-block; vertical-align: middle;"/>
45
+ </a>
46
+ </div>
47
+
48
+ <p align="center">
49
+ <a href="#2-model-downloads">Model Download</a> |
50
+ <a href="#3-evaluation-results">Evaluation Results</a> |
51
+ <a href="#4-model-architecture">Model Architecture</a> |
52
+ <a href="#6-api-platform">API Platform</a> |
53
+ <a href="#8-license">License</a> |
54
+ <a href="#9-citation">Citation</a>
55
+ </p>
56
+
57
+ <p align="center">
58
+ <a href="https://arxiv.org/abs/2405.04434"><b>Paper Link</b>👁️</a>
59
+ </p>
60
+
61
+ # DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model
62
+
63
+ ## 1. Introduction
64
+
65
+ Last week, the release and buzz around DeepSeek-V2 have ignited widespread interest in MLA (Multi-head Latent Attention)! Many in the community suggested open-sourcing a smaller MoE model for in-depth research. And now DeepSeek-V2-Lite comes out:
66
+
67
+ - 16B total params, 2.4B active params, scratch training with 5.7T tokens
68
+ - Outperforms 7B dense and 16B MoE on many English & Chinese benchmarks
69
+ - Deployable on single 40G GPU, fine-tunable on 8x80G GPUs
70
+
71
+ DeepSeek-V2, a strong Mixture-of-Experts (MoE) language model characterized by economical training and efficient inference. DeepSeek-V2 adopts innovative architectures including Multi-head Latent Attention (MLA) and DeepSeekMoE. MLA guarantees efficient inference through significantly compressing the Key-Value (KV) cache into a latent vector, while DeepSeekMoE enables training strong models at an economical cost through sparse computation.
72
+
73
+ ## 2. News
74
+
75
+ - 2024.05.16: We released the DeepSeek-V2-Lite.
76
+ - 2024.05.06: We released the DeepSeek-V2.
77
+
78
+ ## 3. Model Downloads
79
+
80
+ With DeepSeek-V2, we are open-sourcing base and chat models across two sizes:
81
+
82
+ <div align="center">
83
+
84
+ | **Model** | **#Total Params** | **#Activated Params** | **Context Length** | **Download** |
85
+ | :------------: | :------------: | :------------: | :------------: | :------------: |
86
+ | DeepSeek-V2-Lite | 16B | 2.4B | 32k | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite) |
87
+ | DeepSeek-V2-Lite-Chat (SFT) | 16B | 2.4B | 32k | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite-Chat) |
88
+ | DeepSeek-V2 | 236B | 21B | 128k | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-V2) |
89
+ | DeepSeek-V2-Chat (RL) | 236B | 21B | 128k | [���� HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-V2-Chat) |
90
+
91
+ </div>
92
+
93
+ Due to the constraints of HuggingFace, the open-source code currently experiences slower performance than our internal codebase when running on GPUs with Huggingface. To facilitate the efficient execution of our model, we offer a dedicated vllm solution that optimizes performance for running our model effectively.
94
+
95
+ ## 4. Evaluation Results
96
+ ### Base Model
97
+ #### Standard Benchmark
98
+ <div align="center">
99
+
100
+ | **Benchmark** | **Domain** | **DeepSeek 7B (Dense)** | **DeepSeekMoE 16B** | **DeepSeek-V2-Lite (MoE-16B)** |
101
+ |:-------------:|:----------:|:--------------:|:-----------------:|:--------------------------:|
102
+ | **Architecture** | - | MHA+Dense | MHA+MoE | MLA+MoE |
103
+ | **MMLU** | English | 48.2 | 45.0 | 58.3 |
104
+ | **BBH** | English | 39.5 | 38.9 | 44.1 |
105
+ | **C-Eval** | Chinese | 45.0 | 40.6 | 60.3 |
106
+ | **CMMLU** | Chinese | 47.2 | 42.5 | 64.3 |
107
+ | **HumanEval** | Code | 26.2 | 26.8 | 29.9 |
108
+ | **MBPP** | Code | 39.0 | 39.2 | 43.2 |
109
+ | **GSM8K** | Math | 17.4 | 18.8 | 41.1 |
110
+ | **Math** | Math | 3.3 | 4.3 | 17.1 |
111
+
112
+ </div>
113
+ For more evaluation details, such as few-shot settings and prompts, please check our paper.
114
+
115
+
116
+ ### Chat Model
117
+ #### Standard Benchmark
118
+
119
+ <div align="center">
120
+
121
+ | Benchmark | Domain | DeepSeek 7B Chat (SFT) | DeepSeekMoE 16B Chat (SFT) | DeepSeek-V2-Lite 16B Chat (SFT) |
122
+ |:-----------:|:----------------:|:------------------:|:---------------:|:---------------------:|
123
+ | **MMLU** | English | 49.7 | 47.2 | 55.7 |
124
+ | **BBH** | English | 43.1 | 42.2 | 48.1 |
125
+ | **C-Eval** | Chinese | 44.7 | 40.0 | 60.1 |
126
+ | **CMMLU** | Chinese | 51.2 | 49.3 | 62.5 |
127
+ | **HumanEval** | Code | 45.1 | 45.7 | 57.3 |
128
+ | **MBPP** | Code | 39.0 | 46.2 | 45.8 |
129
+ | **GSM8K** | Math | 62.6 | 62.2 | 72.0 |
130
+ | **Math** | Math | 14.7 | 15.2 | 27.9 |
131
+
132
+ </div>
133
+
134
+
135
+ ## 5. Model Architecture
136
+ DeepSeek-V2 adopts innovative architectures to guarantee economical training and efficient inference:
137
+ - For attention, we design MLA (Multi-head Latent Attention), which utilizes low-rank key-value union compression to eliminate the bottleneck of inference-time key-value cache, thus supporting efficient inference.
138
+ - For Feed-Forward Networks (FFNs), we adopt DeepSeekMoE architecture, a high-performance MoE architecture that enables training stronger models at lower costs.
139
+
140
+ <p align="center">
141
+ <img width="90%" src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/architecture.png?raw=true" />
142
+ </p>
143
+
144
+ DeepSeek-V2-Lite has 27 layers and a hidden dimension of 2048. It also employs MLA and has 16 attention heads, where each head has a dimension of 128. Its KV compression dimension is 512, but slightly different from DeepSeek-V2, it does not compress the queries. For the decoupled queries and key, it has a per-head dimension of 64. DeepSeek-V2-Lite also employs DeepSeekMoE, and all FFNs except for the first layer are replaced with MoE layers. Each MoE layer consists of 2 shared experts and 64 routed experts, where the intermediate hidden dimension of each expert is 1408. Among the routed experts, 6 experts will be activated for each token. Under this configuration, DeepSeek-V2-Lite comprises 15.7B total parameters, of which 2.4B are activated for each token.
145
+
146
+
147
+ ## 6. Training Details
148
+ DeepSeek-V2-Lite is also trained from scratch on the same pre-training corpus of DeepSeek-V2, which is not polluted by any SFT data. It uses the AdamW optimizer with hyper-parameters set to $\beta_1=0.9$, $\beta_2=0.95$, and $\mathrm{weight_decay}=0.1$. The learning rate is scheduled using a warmup-and-step-decay strategy. Initially, the learning rate linearly increases from 0 to the maximum value during the first 2K steps. Subsequently, the learning rate is multiplied by 0.316 after training about 80% of tokens, and again by 0.316 after training about 90% of tokens. The maximum learning rate is set to $4.2 \times 10^{-4}$, and the gradient clipping norm is set to 1.0. We do not employ the batch size scheduling strategy for it, and it is trained with a constant batch size of 4608 sequences. During pre-training, we set the maximum sequence length to 4K, and train DeepSeek-V2-Lite on 5.7T tokens. We leverage pipeline parallelism to deploy different layers of it on different devices, but for each layer, all experts will be deployed on the same device. Therefore, we only employ a small expert-level balance loss with $\alpha_{1}=0.001$, and do not employ device-level balance loss and communication balance loss for it. After pre-training, we also perform long-context extension, SFT for DeepSeek-V2-Lite and get a chat model called DeepSeek-V2-Lite Chat.
149
+
150
+ ## 7. How to run locally
151
+
152
+ **To utilize DeepSeek-V2-Lite in BF16 format for inference, 40GB*1 GPU is required.**
153
+ ### Inference with Huggingface's Transformers
154
+ You can directly employ [Huggingface's Transformers](https://github.com/huggingface/transformers) for model inference.
155
+
156
+ #### Text Completion
157
+ ```python
158
+ import torch
159
+ from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
160
+
161
+ model_name = "deepseek-ai/DeepSeek-V2-Lite"
162
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
163
+ model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
164
+ model.generation_config = GenerationConfig.from_pretrained(model_name)
165
+ model.generation_config.pad_token_id = model.generation_config.eos_token_id
166
+
167
+ text = "An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is"
168
+ inputs = tokenizer(text, return_tensors="pt")
169
+ outputs = model.generate(**inputs.to(model.device), max_new_tokens=100)
170
+
171
+ result = tokenizer.decode(outputs[0], skip_special_tokens=True)
172
+ print(result)
173
+ ```
174
+
175
+ #### Chat Completion
176
+ ```python
177
+ import torch
178
+ from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
179
+
180
+ model_name = "deepseek-ai/DeepSeek-V2-Lite-Chat"
181
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
182
+ model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
183
+ model.generation_config = GenerationConfig.from_pretrained(model_name)
184
+ model.generation_config.pad_token_id = model.generation_config.eos_token_id
185
+
186
+ messages = [
187
+ {"role": "user", "content": "Write a piece of quicksort code in C++"}
188
+ ]
189
+ input_tensor = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
190
+ outputs = model.generate(input_tensor.to(model.device), max_new_tokens=100)
191
+
192
+ result = tokenizer.decode(outputs[0][input_tensor.shape[1]:], skip_special_tokens=True)
193
+ print(result)
194
+ ```
195
+
196
+ The complete chat template can be found within `tokenizer_config.json` located in the huggingface model repository.
197
+
198
+ An example of chat template is as belows:
199
+
200
+ ```bash
201
+ <|begin▁of▁sentence|>User: {user_message_1}
202
+
203
+ Assistant: {assistant_message_1}<|end▁of▁sentence|>User: {user_message_2}
204
+
205
+ Assistant:
206
+ ```
207
+
208
+ You can also add an optional system message:
209
+
210
+ ```bash
211
+ <|begin▁of▁sentence|>{system_message}
212
+
213
+ User: {user_message_1}
214
+
215
+ Assistant: {assistant_message_1}<|end▁of▁sentence|>User: {user_message_2}
216
+
217
+ Assistant:
218
+ ```
219
+
220
+ ### Inference with vLLM (recommended)
221
+ 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.
222
+
223
+ ```python
224
+ from transformers import AutoTokenizer
225
+ from vllm import LLM, SamplingParams
226
+
227
+ max_model_len, tp_size = 8192, 1
228
+ model_name = "deepseek-ai/DeepSeek-V2-Lite-Chat"
229
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
230
+ llm = LLM(model=model_name, tensor_parallel_size=tp_size, max_model_len=max_model_len, trust_remote_code=True, enforce_eager=True)
231
+ sampling_params = SamplingParams(temperature=0.3, max_tokens=256, stop_token_ids=[tokenizer.eos_token_id])
232
+
233
+ messages_list = [
234
+ [{"role": "user", "content": "Who are you?"}],
235
+ [{"role": "user", "content": "Translate the following content into Chinese directly: DeepSeek-V2 adopts innovative architectures to guarantee economical training and efficient inference."}],
236
+ [{"role": "user", "content": "Write a piece of quicksort code in C++."}],
237
+ ]
238
+
239
+ prompt_token_ids = [tokenizer.apply_chat_template(messages, add_generation_prompt=True) for messages in messages_list]
240
+
241
+ outputs = llm.generate(prompt_token_ids=prompt_token_ids, sampling_params=sampling_params)
242
+
243
+ generated_text = [output.outputs[0].text for output in outputs]
244
+ print(generated_text)
245
+ ```
246
+
247
+ ### LangChain Support
248
+ Since our API is compatible with OpenAI, you can easily use it in [langchain](https://www.langchain.com/).
249
+ Here is an example:
250
+
251
+ ```
252
+ from langchain_openai import ChatOpenAI
253
+ llm = ChatOpenAI(
254
+ model='deepseek-chat',
255
+ openai_api_key=<your-deepseek-api-key>,
256
+ openai_api_base='https://api.deepseek.com/v1',
257
+ temperature=0.85,
258
+ max_tokens=8000)
259
+ ```
260
+ ## 8. License
261
+ This code repository is licensed under [the MIT License](LICENSE-CODE). The use of DeepSeek-V2 Base/Chat models is subject to [the Model License](LICENSE-MODEL). DeepSeek-V2 series (including Base and Chat) supports commercial use.
262
+
263
+ ## 9. Citation
264
+ ```
265
+ @misc{deepseekv2,
266
+ title={DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model},
267
+ author={DeepSeek-AI},
268
+ year={2024},
269
+ eprint={2405.04434},
270
+ archivePrefix={arXiv},
271
+ primaryClass={cs.CL}
272
+ }
273
+ ```
274
+
275
+ ## 10. Contact
276
+ If you have any questions, please raise an issue or contact us at [[email protected]]([email protected]).
config.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DeepseekV2ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_deepseek.DeepseekV2Config",
9
+ "AutoModel": "modeling_deepseek.DeepseekV2Model",
10
+ "AutoModelForCausalLM": "modeling_deepseek.DeepseekV2ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.001,
13
+ "bos_token_id": 100000,
14
+ "eos_token_id": 100001,
15
+ "first_k_dense_replace": 1,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2048,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 10944,
20
+ "kv_lora_rank": 512,
21
+ "max_position_embeddings": 163840,
22
+ "model_type": "deepseek_v2",
23
+ "moe_intermediate_size": 1408,
24
+ "moe_layer_freq": 1,
25
+ "n_group": 1,
26
+ "n_routed_experts": 64,
27
+ "n_shared_experts": 2,
28
+ "norm_topk_prob": false,
29
+ "num_attention_heads": 16,
30
+ "num_experts_per_tok": 6,
31
+ "num_hidden_layers": 27,
32
+ "num_key_value_heads": 16,
33
+ "pretraining_tp": 1,
34
+ "q_lora_rank": null,
35
+ "qk_nope_head_dim": 128,
36
+ "qk_rope_head_dim": 64,
37
+ "rms_norm_eps": 1e-06,
38
+ "rope_scaling": {
39
+ "beta_fast": 32,
40
+ "beta_slow": 1,
41
+ "factor": 40,
42
+ "mscale": 0.707,
43
+ "mscale_all_dim": 0.707,
44
+ "original_max_position_embeddings": 4096,
45
+ "type": "yarn"
46
+ },
47
+ "rope_theta": 10000,
48
+ "routed_scaling_factor": 1.0,
49
+ "scoring_func": "softmax",
50
+ "seq_aux": true,
51
+ "tie_word_embeddings": false,
52
+ "topk_group": 1,
53
+ "topk_method": "greedy",
54
+ "torch_dtype": "bfloat16",
55
+ "transformers_version": "4.33.1",
56
+ "use_cache": true,
57
+ "v_head_dim": 128,
58
+ "vocab_size": 102400
59
+ }
configuration_deepseek.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
86
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
87
+ issue](https://github.com/pytorch/pytorch/issues/76232).
88
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
89
+ Whether to tie weight embeddings
90
+ rope_theta (`float`, *optional*, defaults to 10000.0):
91
+ The base period of the RoPE embeddings.
92
+ rope_scaling (`Dict`, *optional*):
93
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
94
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
95
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
96
+ `max_position_embeddings` to the expected new maximum.
97
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
98
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
99
+ attention_dropout (`float`, *optional*, defaults to 0.0):
100
+ The dropout ratio for the attention probabilities.
101
+
102
+ ```python
103
+ >>> from transformers import 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
+ ep_size = 1,
127
+ routed_scaling_factor = 1.0,
128
+ kv_lora_rank = 512,
129
+ q_lora_rank = 1536,
130
+ qk_rope_head_dim = 64,
131
+ v_head_dim = 128,
132
+ qk_nope_head_dim = 128,
133
+ topk_method = 'gready',
134
+ n_group = None,
135
+ topk_group = None,
136
+ num_experts_per_tok = None,
137
+ moe_layer_freq = 1,
138
+ first_k_dense_replace = 0,
139
+ norm_topk_prob = False,
140
+ scoring_func = 'softmax',
141
+ aux_loss_alpha = 0.001,
142
+ seq_aux = True,
143
+ hidden_act="silu",
144
+ max_position_embeddings=2048,
145
+ initializer_range=0.02,
146
+ rms_norm_eps=1e-6,
147
+ use_cache=True,
148
+ pad_token_id=None,
149
+ bos_token_id=100000,
150
+ eos_token_id=100001,
151
+ pretraining_tp=1,
152
+ tie_word_embeddings=False,
153
+ rope_theta=10000.0,
154
+ rope_scaling=None,
155
+ attention_bias=False,
156
+ attention_dropout=0.0,
157
+ **kwargs,
158
+ ):
159
+ self.vocab_size = vocab_size
160
+ self.max_position_embeddings = max_position_embeddings
161
+ self.hidden_size = hidden_size
162
+ self.intermediate_size = intermediate_size
163
+ self.moe_intermediate_size = moe_intermediate_size
164
+ self.num_hidden_layers = num_hidden_layers
165
+ self.num_attention_heads = num_attention_heads
166
+ self.n_shared_experts = n_shared_experts
167
+ self.n_routed_experts = n_routed_experts
168
+ self.ep_size = ep_size
169
+ self.routed_scaling_factor = routed_scaling_factor
170
+ self.kv_lora_rank = kv_lora_rank
171
+ self.q_lora_rank = q_lora_rank
172
+ self.qk_rope_head_dim = qk_rope_head_dim
173
+ self.v_head_dim = v_head_dim
174
+ self.qk_nope_head_dim = qk_nope_head_dim
175
+ self.topk_method = topk_method
176
+ self.n_group = n_group
177
+ self.topk_group = topk_group
178
+ self.num_experts_per_tok = num_experts_per_tok
179
+ self.moe_layer_freq = moe_layer_freq
180
+ self.first_k_dense_replace = first_k_dense_replace
181
+ self.norm_topk_prob = norm_topk_prob
182
+ self.scoring_func = scoring_func
183
+ self.aux_loss_alpha = aux_loss_alpha
184
+ self.seq_aux = seq_aux
185
+ # for backward compatibility
186
+ if num_key_value_heads is None:
187
+ num_key_value_heads = num_attention_heads
188
+
189
+ self.num_key_value_heads = num_key_value_heads
190
+ self.hidden_act = hidden_act
191
+ self.initializer_range = initializer_range
192
+ self.rms_norm_eps = rms_norm_eps
193
+ self.pretraining_tp = pretraining_tp
194
+ self.use_cache = use_cache
195
+ self.rope_theta = rope_theta
196
+ self.rope_scaling = rope_scaling
197
+ self.attention_bias = attention_bias
198
+ self.attention_dropout = attention_dropout
199
+
200
+ super().__init__(
201
+ pad_token_id=pad_token_id,
202
+ bos_token_id=bos_token_id,
203
+ eos_token_id=eos_token_id,
204
+ tie_word_embeddings=tie_word_embeddings,
205
+ **kwargs,
206
+ )
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 100000,
4
+ "eos_token_id": 100001,
5
+ "do_sample": true,
6
+ "temperature": 0.3,
7
+ "top_p": 0.95,
8
+ "transformers_version": "4.39.3"
9
+ }
model-00001-of-000004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:258811fe017b955eb542325c73f8cd8fc2f77f7c5c27dc1721877212182bffe4
3
+ size 135
model-00002-of-000004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46264772a9631656d6f8ff201943336f45d298e2dade91cbf3bf87f61dbc10eb
3
+ size 135
model-00003-of-000004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5c3a29ec4c6a815eaf1fbff20ca641ce9f3dc030fd7f7d5ea6d4962605322f7
3
+ size 135
model-00004-of-000004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:900e5ae475e2105613495a483a4aca219d3de2c07757e01d6db3ea4abe682790
3
+ size 135
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_deepseek.py ADDED
@@ -0,0 +1,2029 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch DeepSeek model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ )
38
+ from transformers.modeling_outputs import (
39
+ BaseModelOutputWithPast,
40
+ CausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import (
45
+ ALL_LAYERNORM_LAYERS,
46
+ is_torch_greater_or_equal_than_1_13,
47
+ )
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from transformers.utils.import_utils import is_torch_fx_available
57
+ from configuration_deepseek import DeepseekV2Config
58
+ import torch.distributed as dist
59
+ import numpy as np
60
+
61
+ if is_flash_attn_2_available():
62
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
63
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
64
+
65
+
66
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
67
+ # It means that the function will not be traced through and simply appear as a node in the graph.
68
+ if is_torch_fx_available():
69
+ if not is_torch_greater_or_equal_than_1_13:
70
+ import torch.fx
71
+
72
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
73
+
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+ _CONFIG_FOR_DOC = "DeepseekV2Config"
78
+
79
+
80
+ def _get_unpad_data(attention_mask):
81
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
82
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
83
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
84
+ cu_seqlens = F.pad(
85
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
86
+ )
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+
94
+ class DeepseekV2RMSNorm(nn.Module):
95
+ def __init__(self, hidden_size, eps=1e-6):
96
+ """
97
+ DeepseekV2RMSNorm is equivalent to T5LayerNorm
98
+ """
99
+ super().__init__()
100
+ self.weight = nn.Parameter(torch.ones(hidden_size))
101
+ self.variance_epsilon = eps
102
+
103
+ def forward(self, hidden_states):
104
+ input_dtype = hidden_states.dtype
105
+ hidden_states = hidden_states.to(torch.float32)
106
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
107
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
108
+ return self.weight * hidden_states.to(input_dtype)
109
+
110
+
111
+ ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
112
+
113
+
114
+ class DeepseekV2RotaryEmbedding(nn.Module):
115
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
116
+ super().__init__()
117
+
118
+ self.dim = dim
119
+ self.max_position_embeddings = max_position_embeddings
120
+ self.base = base
121
+ inv_freq = 1.0 / (
122
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
123
+ )
124
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
125
+
126
+ # Build here to make `torch.jit.trace` work.
127
+ self._set_cos_sin_cache(
128
+ seq_len=max_position_embeddings,
129
+ device=self.inv_freq.device,
130
+ dtype=torch.get_default_dtype(),
131
+ )
132
+ self.max_seq_len_cached = None
133
+
134
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
135
+ self.max_seq_len_cached = seq_len
136
+ t = torch.arange(
137
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
138
+ )
139
+
140
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
141
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
142
+ emb = torch.cat((freqs, freqs), dim=-1)
143
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
144
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
145
+
146
+ def forward(self, x, seq_len=None):
147
+ # x: [bs, num_attention_heads, seq_len, head_size]
148
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
149
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
150
+
151
+ return (
152
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
153
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
154
+ )
155
+
156
+
157
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2
158
+ class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
159
+ """DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
160
+
161
+ def __init__(
162
+ self,
163
+ dim,
164
+ max_position_embeddings=2048,
165
+ base=10000,
166
+ device=None,
167
+ scaling_factor=1.0,
168
+ ):
169
+ self.scaling_factor = scaling_factor
170
+ super().__init__(dim, max_position_embeddings, base, device)
171
+
172
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
173
+ self.max_seq_len_cached = seq_len
174
+ t = torch.arange(
175
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
176
+ )
177
+ t = t / self.scaling_factor
178
+
179
+ freqs = torch.outer(t, self.inv_freq)
180
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
181
+ emb = torch.cat((freqs, freqs), dim=-1)
182
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
183
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
184
+
185
+
186
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2
187
+ class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
188
+ """DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
189
+
190
+ def __init__(
191
+ self,
192
+ dim,
193
+ max_position_embeddings=2048,
194
+ base=10000,
195
+ device=None,
196
+ scaling_factor=1.0,
197
+ ):
198
+ self.scaling_factor = scaling_factor
199
+ super().__init__(dim, max_position_embeddings, base, device)
200
+
201
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
202
+ self.max_seq_len_cached = seq_len
203
+
204
+ if seq_len > self.max_position_embeddings:
205
+ base = self.base * (
206
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
207
+ - (self.scaling_factor - 1)
208
+ ) ** (self.dim / (self.dim - 2))
209
+ inv_freq = 1.0 / (
210
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
211
+ )
212
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
213
+
214
+ t = torch.arange(
215
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
216
+ )
217
+
218
+ freqs = torch.outer(t, self.inv_freq)
219
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
220
+ emb = torch.cat((freqs, freqs), dim=-1)
221
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
222
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
223
+
224
+
225
+ # Inverse dim formula to find dim based on number of rotations
226
+ def yarn_find_correction_dim(
227
+ num_rotations, dim, base=10000, max_position_embeddings=2048
228
+ ):
229
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
230
+ 2 * math.log(base)
231
+ )
232
+
233
+
234
+ # Find dim range bounds based on rotations
235
+ def yarn_find_correction_range(
236
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
237
+ ):
238
+ low = math.floor(
239
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
240
+ )
241
+ high = math.ceil(
242
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
243
+ )
244
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
245
+
246
+
247
+ def yarn_get_mscale(scale=1, mscale=1):
248
+ if scale <= 1:
249
+ return 1.0
250
+ return 0.1 * mscale * math.log(scale) + 1.0
251
+
252
+
253
+ def yarn_linear_ramp_mask(min, max, dim):
254
+ if min == max:
255
+ max += 0.001 # Prevent singularity
256
+
257
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
258
+ ramp_func = torch.clamp(linear_func, 0, 1)
259
+ return ramp_func
260
+
261
+
262
+ class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
263
+
264
+ def __init__(
265
+ self,
266
+ dim,
267
+ max_position_embeddings=2048,
268
+ base=10000,
269
+ device=None,
270
+ scaling_factor=1.0,
271
+ original_max_position_embeddings=4096,
272
+ beta_fast=32,
273
+ beta_slow=1,
274
+ mscale=1,
275
+ mscale_all_dim=0,
276
+ ):
277
+ self.scaling_factor = scaling_factor
278
+ self.original_max_position_embeddings = original_max_position_embeddings
279
+ self.beta_fast = beta_fast
280
+ self.beta_slow = beta_slow
281
+ self.mscale = mscale
282
+ self.mscale_all_dim = mscale_all_dim
283
+ super().__init__(dim, max_position_embeddings, base, device)
284
+
285
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
286
+ self.max_seq_len_cached = seq_len
287
+ dim = self.dim
288
+
289
+ freq_extra = 1.0 / (
290
+ self.base
291
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
292
+ )
293
+ freq_inter = 1.0 / (
294
+ self.scaling_factor
295
+ * self.base
296
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
297
+ )
298
+
299
+ low, high = yarn_find_correction_range(
300
+ self.beta_fast,
301
+ self.beta_slow,
302
+ dim,
303
+ self.base,
304
+ self.original_max_position_embeddings,
305
+ )
306
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
307
+ device=device, dtype=torch.float32
308
+ )
309
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
310
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
311
+
312
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
313
+
314
+ freqs = torch.outer(t, inv_freq)
315
+
316
+ _mscale = float(
317
+ yarn_get_mscale(self.scaling_factor, self.mscale)
318
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
319
+ )
320
+
321
+ emb = torch.cat((freqs, freqs), dim=-1)
322
+ self.register_buffer(
323
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
324
+ )
325
+ self.register_buffer(
326
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
327
+ )
328
+
329
+
330
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
331
+ def rotate_half(x):
332
+ """Rotates half the hidden dims of the input."""
333
+ x1 = x[..., : x.shape[-1] // 2]
334
+ x2 = x[..., x.shape[-1] // 2 :]
335
+ return torch.cat((-x2, x1), dim=-1)
336
+
337
+
338
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
339
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
340
+ """Applies Rotary Position Embedding to the query and key tensors.
341
+
342
+ Args:
343
+ q (`torch.Tensor`): The query tensor.
344
+ k (`torch.Tensor`): The key tensor.
345
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
346
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
347
+ position_ids (`torch.Tensor`):
348
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
349
+ used to pass offsetted position ids when working with a KV-cache.
350
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
351
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
352
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
353
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
354
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
355
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
356
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
357
+ Returns:
358
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
359
+ """
360
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
361
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
362
+
363
+ b, h, s, d = q.shape
364
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
365
+
366
+ b, h, s, d = k.shape
367
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
368
+
369
+ q_embed = (q * cos) + (rotate_half(q) * sin)
370
+ k_embed = (k * cos) + (rotate_half(k) * sin)
371
+ return q_embed, k_embed
372
+
373
+
374
+ class DeepseekV2MLP(nn.Module):
375
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
376
+ super().__init__()
377
+ self.config = config
378
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
379
+ self.intermediate_size = (
380
+ config.intermediate_size if intermediate_size is None else intermediate_size
381
+ )
382
+
383
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
384
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
385
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
386
+ self.act_fn = ACT2FN[config.hidden_act]
387
+
388
+ def forward(self, x):
389
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
390
+ return down_proj
391
+
392
+
393
+ class MoEGate(nn.Module):
394
+ def __init__(self, config):
395
+ super().__init__()
396
+ self.config = config
397
+ self.top_k = config.num_experts_per_tok
398
+ self.n_routed_experts = config.n_routed_experts
399
+ self.routed_scaling_factor = config.routed_scaling_factor
400
+ self.scoring_func = config.scoring_func
401
+ self.alpha = config.aux_loss_alpha
402
+ self.seq_aux = config.seq_aux
403
+ self.topk_method = config.topk_method
404
+ self.n_group = config.n_group
405
+ self.topk_group = config.topk_group
406
+
407
+ # topk selection algorithm
408
+ self.norm_topk_prob = config.norm_topk_prob
409
+ self.gating_dim = config.hidden_size
410
+ self.weight = nn.Parameter(
411
+ torch.empty((self.n_routed_experts, self.gating_dim))
412
+ )
413
+ self.reset_parameters()
414
+
415
+ def reset_parameters(self) -> None:
416
+ import torch.nn.init as init
417
+
418
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
419
+
420
+ def forward(self, hidden_states):
421
+ bsz, seq_len, h = hidden_states.shape
422
+ ### compute gating score
423
+ hidden_states = hidden_states.view(-1, h)
424
+ logits = F.linear(
425
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
426
+ )
427
+ if self.scoring_func == "softmax":
428
+ scores = logits.softmax(dim=-1, dtype=torch.float32)
429
+ else:
430
+ raise NotImplementedError(
431
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
432
+ )
433
+
434
+ ### select top-k experts
435
+ if self.topk_method == "greedy":
436
+ topk_weight, topk_idx = torch.topk(
437
+ scores, k=self.top_k, dim=-1, sorted=False
438
+ )
439
+ elif self.topk_method == "group_limited_greedy":
440
+ group_scores = (
441
+ scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
442
+ ) # [n, n_group]
443
+ group_idx = torch.topk(
444
+ group_scores, k=self.topk_group, dim=-1, sorted=False
445
+ )[
446
+ 1
447
+ ] # [n, top_k_group]
448
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
449
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
450
+ score_mask = (
451
+ group_mask.unsqueeze(-1)
452
+ .expand(
453
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
454
+ )
455
+ .reshape(bsz * seq_len, -1)
456
+ ) # [n, e]
457
+ tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
458
+ topk_weight, topk_idx = torch.topk(
459
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
460
+ )
461
+
462
+ ### norm gate to sum 1
463
+ if self.top_k > 1 and self.norm_topk_prob:
464
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
465
+ topk_weight = topk_weight / denominator
466
+ else:
467
+ topk_weight = topk_weight * self.routed_scaling_factor
468
+ ### expert-level computation auxiliary loss
469
+ if self.training and self.alpha > 0.0:
470
+ scores_for_aux = scores
471
+ aux_topk = self.top_k
472
+ # always compute aux loss based on the naive greedy topk method
473
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
474
+ if self.seq_aux:
475
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
476
+ ce = torch.zeros(
477
+ bsz, self.n_routed_experts, device=hidden_states.device
478
+ )
479
+ ce.scatter_add_(
480
+ 1,
481
+ topk_idx_for_aux_loss,
482
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
483
+ ).div_(seq_len * aux_topk / self.n_routed_experts)
484
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
485
+ dim=1
486
+ ).mean() * self.alpha
487
+ else:
488
+ mask_ce = F.one_hot(
489
+ topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
490
+ )
491
+ ce = mask_ce.float().mean(0)
492
+ Pi = scores_for_aux.mean(0)
493
+ fi = ce * self.n_routed_experts
494
+ aux_loss = (Pi * fi).sum() * self.alpha
495
+ else:
496
+ aux_loss = None
497
+ return topk_idx, topk_weight, aux_loss
498
+
499
+
500
+ class AddAuxiliaryLoss(torch.autograd.Function):
501
+ """
502
+ The trick function of adding auxiliary (aux) loss,
503
+ which includes the gradient of the aux loss during backpropagation.
504
+ """
505
+
506
+ @staticmethod
507
+ def forward(ctx, x, loss):
508
+ assert loss.numel() == 1
509
+ ctx.dtype = loss.dtype
510
+ ctx.required_aux_loss = loss.requires_grad
511
+ return x
512
+
513
+ @staticmethod
514
+ def backward(ctx, grad_output):
515
+ grad_loss = None
516
+ if ctx.required_aux_loss:
517
+ grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
518
+ return grad_output, grad_loss
519
+
520
+
521
+ class DeepseekV2MoE(nn.Module):
522
+ """
523
+ A mixed expert module containing shared experts.
524
+ """
525
+
526
+ def __init__(self, config):
527
+ super().__init__()
528
+ self.config = config
529
+ self.num_experts_per_tok = config.num_experts_per_tok
530
+
531
+ if hasattr(config, "ep_size") and config.ep_size > 1:
532
+ assert config.ep_size == dist.get_world_size()
533
+ self.ep_size = config.ep_size
534
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
535
+ self.ep_rank = dist.get_rank()
536
+ self.experts = nn.ModuleList(
537
+ [
538
+ (
539
+ DeepseekV2MLP(
540
+ config, intermediate_size=config.moe_intermediate_size
541
+ )
542
+ if i >= self.ep_rank * self.experts_per_rank
543
+ and i < (self.ep_rank + 1) * self.experts_per_rank
544
+ else None
545
+ )
546
+ for i in range(config.n_routed_experts)
547
+ ]
548
+ )
549
+ else:
550
+ self.ep_size = 1
551
+ self.experts_per_rank = config.n_routed_experts
552
+ self.ep_rank = 0
553
+ self.experts = nn.ModuleList(
554
+ [
555
+ DeepseekV2MLP(
556
+ config, intermediate_size=config.moe_intermediate_size
557
+ )
558
+ for i in range(config.n_routed_experts)
559
+ ]
560
+ )
561
+ self.gate = MoEGate(config)
562
+ if config.n_shared_experts is not None:
563
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
564
+ self.shared_experts = DeepseekV2MLP(
565
+ config=config, intermediate_size=intermediate_size
566
+ )
567
+
568
+ def forward_original(self, hidden_states):
569
+ """原始的forward方法,保留用于对比和回滚"""
570
+ identity = hidden_states
571
+ orig_shape = hidden_states.shape
572
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
573
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
574
+ flat_topk_idx = topk_idx.view(-1)
575
+ if self.training:
576
+ hidden_states = hidden_states.repeat_interleave(
577
+ self.num_experts_per_tok, dim=0
578
+ )
579
+ y = torch.empty_like(hidden_states)
580
+ for i, expert in enumerate(self.experts):
581
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
582
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
583
+ y = y.to(hidden_states.dtype).view(*orig_shape)
584
+ y = AddAuxiliaryLoss.apply(y, aux_loss)
585
+ else:
586
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
587
+ if self.config.n_shared_experts is not None:
588
+ y = y + self.shared_experts(identity)
589
+ return y
590
+
591
+ def forward(self, hidden_states):
592
+ """
593
+ 实现dense backward功能的前向传播:
594
+ 前向输出保持与官方相同(稀疏计算结果),但在反向传播时通过dense计算的梯度传递回来
595
+
596
+ Dense Backward机制说明:
597
+ 1. 前向传播时,只有top-k专家参与计算(稀疏前向)
598
+ 2. 反向传播时,所有专家都接收梯度(密集反向)
599
+ 3. 使用直通梯度技术:sparse_output.detach() + (dense_output - dense_output.detach())
600
+ 4. 通过register_hook确保只有被激活的专家才真正更新参数
601
+
602
+ Args:
603
+ hidden_states: 输入张量,形状为 (batch_size, seq_length, hidden_dim)
604
+
605
+ Returns:
606
+ 输出张量,形状为 (batch_size, seq_length, hidden_dim)
607
+ """
608
+ batch_size, seq_length, hidden_dim = hidden_states.shape
609
+ dtype = hidden_states.dtype
610
+ device = hidden_states.device
611
+
612
+ identity = hidden_states
613
+ orig_shape = hidden_states.shape
614
+
615
+ # Step 1: 计算路由逻辑,选择top-k专家
616
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
617
+ flat_hidden = hidden_states.view(-1, hidden_dim) # (B*seq_len, hidden_dim)
618
+ N_tokens = flat_hidden.size(0)
619
+ flat_topk_idx = topk_idx.view(-1)
620
+
621
+ # Step 2: 计算完整的路由权重(用于dense backward)
622
+ # 注意V2版本强制使用float32计算
623
+ router_logits = F.linear(
624
+ flat_hidden.type(torch.float32),
625
+ self.gate.weight.type(torch.float32),
626
+ None
627
+ )
628
+ if self.gate.scoring_func == 'softmax':
629
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float32) # (N_tokens, n_routed_experts)
630
+ else:
631
+ raise NotImplementedError(f'Unsupported scoring function: {self.gate.scoring_func}')
632
+
633
+ routing_weights = routing_weights.to(dtype=dtype)
634
+
635
+ # Step 3: 准备输出累加器
636
+ dense_outputs = torch.zeros((N_tokens, hidden_dim), dtype=dtype, device=device)
637
+ sparse_outputs = torch.zeros((N_tokens, hidden_dim), dtype=dtype, device=device)
638
+
639
+ # Step 4: 对每个专家进行计算
640
+ if self.training:
641
+ # 训练模式:实现dense backward
642
+ for expert_idx in range(self.config.n_routed_experts):
643
+ # V2版本的专家可能为None(在EP模式下)
644
+ if self.experts[expert_idx] is None:
645
+ continue
646
+
647
+ expert_layer = self.experts[expert_idx]
648
+
649
+ # 为所有tokens计算当前专家的输出(dense计算)
650
+ expert_output = expert_layer(flat_hidden) # (N_tokens, hidden_dim)
651
+
652
+ # 创建激活掩码:标记哪些token选择了该专家
653
+ activation_mask = (topk_idx == expert_idx).any(dim=1).float().unsqueeze(-1).to(dtype)
654
+
655
+ # 注册hook:只有被选中的token才能向该专家传递梯度
656
+ if expert_output.requires_grad:
657
+ expert_output.register_hook(lambda grad, mask=activation_mask: grad * mask)
658
+
659
+ expert_output = expert_output.to(dtype=dtype)
660
+
661
+ # Dense accumulation: 使用完整的路由权重
662
+ weight_full = routing_weights[:, expert_idx].unsqueeze(-1) # (N_tokens, 1)
663
+ dense_outputs = dense_outputs + expert_output * weight_full
664
+
665
+ # Sparse accumulation: 只累加被选中的专家输出
666
+ matches = (topk_idx == expert_idx)
667
+ if matches.any():
668
+ token_indices, k_indices = torch.where(matches)
669
+ weights_topk = topk_weight[token_indices, k_indices].unsqueeze(-1) # (num_matches, 1)
670
+ sparse_outputs[token_indices] = sparse_outputs[token_indices] + expert_output[token_indices] * weights_topk
671
+ else:
672
+ # 推理模式:使用原始的稀疏计算逻辑
673
+ sparse_outputs = self.moe_infer(flat_hidden, topk_idx, topk_weight)
674
+ # 推理时不需要dense_outputs
675
+ dense_outputs = sparse_outputs
676
+
677
+ # Step 5: 添加共享专家(如果有)
678
+ if self.config.n_shared_experts is not None:
679
+ shared_expert_output = self.shared_experts(identity)
680
+ sparse_outputs = sparse_outputs.view(*orig_shape) + shared_expert_output
681
+ dense_outputs = dense_outputs.view(*orig_shape) + shared_expert_output
682
+ else:
683
+ sparse_outputs = sparse_outputs.view(*orig_shape)
684
+ dense_outputs = dense_outputs.view(*orig_shape)
685
+
686
+ # Step 6: 使用直通梯度技术组合sparse前向和dense反向
687
+ if self.training:
688
+ # 前向用sparse,反向用dense
689
+ final_output = sparse_outputs.detach() + (dense_outputs - dense_outputs.detach())
690
+ # 添加辅助损失
691
+ final_output = AddAuxiliaryLoss.apply(final_output, aux_loss)
692
+ else:
693
+ final_output = sparse_outputs
694
+
695
+ return final_output
696
+
697
+ @torch.no_grad()
698
+ def moe_infer(self, x, topk_ids, topk_weight):
699
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
700
+ cnts.scatter_(1, topk_ids, 1)
701
+ tokens_per_expert = cnts.sum(dim=0)
702
+ idxs = topk_ids.view(-1).argsort()
703
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
704
+ sorted_tokens_shape = sorted_tokens.shape
705
+ if self.ep_size > 1:
706
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
707
+ tokens_per_expert_group = tokens_per_expert.new_empty(
708
+ tokens_per_expert.shape[0]
709
+ )
710
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
711
+ output_splits = (
712
+ tokens_per_expert_group.view(self.ep_size, -1)
713
+ .sum(1)
714
+ .cpu()
715
+ .numpy()
716
+ .tolist()
717
+ )
718
+ gathered_tokens = sorted_tokens.new_empty(
719
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
720
+ )
721
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
722
+ dist.all_to_all(
723
+ list(gathered_tokens.split(output_splits)),
724
+ list(sorted_tokens.split(input_split_sizes)),
725
+ )
726
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
727
+ self.ep_size, self.experts_per_rank
728
+ ).sum(dim=0)
729
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
730
+ s = 0
731
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
732
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
733
+ s += k
734
+ gatherd_idxs = gatherd_idxs.argsort()
735
+ sorted_tokens = gathered_tokens[gatherd_idxs]
736
+ tokens_per_expert = tokens_per_expert_post_gather
737
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
738
+
739
+ outputs = []
740
+ start_idx = 0
741
+ for i, num_tokens in enumerate(tokens_per_expert):
742
+ end_idx = start_idx + num_tokens
743
+ if num_tokens == 0:
744
+ continue
745
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
746
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
747
+ expert_out = expert(tokens_for_this_expert)
748
+ outputs.append(expert_out)
749
+ start_idx = end_idx
750
+
751
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
752
+ if self.ep_size > 1:
753
+ new_x = torch.empty_like(outs)
754
+ new_x[gatherd_idxs] = outs
755
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
756
+ dist.all_to_all(
757
+ list(gathered_tokens.split(input_split_sizes)),
758
+ list(new_x.split(output_splits)),
759
+ )
760
+ outs = gathered_tokens
761
+
762
+ new_x = torch.empty_like(outs)
763
+ new_x[idxs] = outs
764
+ final_out = (
765
+ new_x.view(*topk_ids.shape, -1)
766
+ .type(topk_weight.dtype)
767
+ .mul_(topk_weight.unsqueeze(dim=-1))
768
+ .sum(dim=1)
769
+ .type(new_x.dtype)
770
+ )
771
+ return final_out
772
+
773
+
774
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
775
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
776
+ """
777
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
778
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
779
+ """
780
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
781
+ if n_rep == 1:
782
+ return hidden_states
783
+ hidden_states = hidden_states[:, :, None, :, :].expand(
784
+ batch, num_key_value_heads, n_rep, slen, head_dim
785
+ )
786
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
787
+
788
+
789
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2
790
+ class DeepseekV2Attention(nn.Module):
791
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
792
+
793
+ def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None):
794
+ super().__init__()
795
+ self.config = config
796
+ self.layer_idx = layer_idx
797
+ if layer_idx is None:
798
+ logger.warning_once(
799
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
800
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
801
+ "when creating this class."
802
+ )
803
+
804
+ self.attention_dropout = config.attention_dropout
805
+ self.hidden_size = config.hidden_size
806
+ self.num_heads = config.num_attention_heads
807
+
808
+ self.max_position_embeddings = config.max_position_embeddings
809
+ self.rope_theta = config.rope_theta
810
+ self.q_lora_rank = config.q_lora_rank
811
+ self.qk_rope_head_dim = config.qk_rope_head_dim
812
+ self.kv_lora_rank = config.kv_lora_rank
813
+ self.v_head_dim = config.v_head_dim
814
+ self.qk_nope_head_dim = config.qk_nope_head_dim
815
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
816
+
817
+ self.is_causal = True
818
+
819
+ if self.q_lora_rank is None:
820
+ self.q_proj = nn.Linear(
821
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
822
+ )
823
+ else:
824
+ self.q_a_proj = nn.Linear(
825
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
826
+ )
827
+ self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank)
828
+ self.q_b_proj = nn.Linear(
829
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
830
+ )
831
+
832
+ self.kv_a_proj_with_mqa = nn.Linear(
833
+ self.hidden_size,
834
+ config.kv_lora_rank + config.qk_rope_head_dim,
835
+ bias=config.attention_bias,
836
+ )
837
+ self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank)
838
+ self.kv_b_proj = nn.Linear(
839
+ config.kv_lora_rank,
840
+ self.num_heads
841
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
842
+ bias=False,
843
+ )
844
+
845
+ self.o_proj = nn.Linear(
846
+ self.num_heads * self.v_head_dim,
847
+ self.hidden_size,
848
+ bias=config.attention_bias,
849
+ )
850
+ self._init_rope()
851
+
852
+ self.softmax_scale = self.q_head_dim ** (-0.5)
853
+ if self.config.rope_scaling is not None:
854
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
855
+ scaling_factor = self.config.rope_scaling["factor"]
856
+ if mscale_all_dim:
857
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
858
+ self.softmax_scale = self.softmax_scale * mscale * mscale
859
+
860
+ def _init_rope(self):
861
+ if self.config.rope_scaling is None:
862
+ self.rotary_emb = DeepseekV2RotaryEmbedding(
863
+ self.qk_rope_head_dim,
864
+ max_position_embeddings=self.max_position_embeddings,
865
+ base=self.rope_theta,
866
+ )
867
+ else:
868
+ scaling_type = self.config.rope_scaling["type"]
869
+ scaling_factor = self.config.rope_scaling["factor"]
870
+ if scaling_type == "linear":
871
+ self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
872
+ self.qk_rope_head_dim,
873
+ max_position_embeddings=self.max_position_embeddings,
874
+ scaling_factor=scaling_factor,
875
+ base=self.rope_theta,
876
+ )
877
+ elif scaling_type == "dynamic":
878
+ self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
879
+ self.qk_rope_head_dim,
880
+ max_position_embeddings=self.max_position_embeddings,
881
+ scaling_factor=scaling_factor,
882
+ base=self.rope_theta,
883
+ )
884
+ elif scaling_type == "yarn":
885
+ kwargs = {
886
+ key: self.config.rope_scaling[key]
887
+ for key in [
888
+ "original_max_position_embeddings",
889
+ "beta_fast",
890
+ "beta_slow",
891
+ "mscale",
892
+ "mscale_all_dim",
893
+ ]
894
+ if key in self.config.rope_scaling
895
+ }
896
+ self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
897
+ self.qk_rope_head_dim,
898
+ max_position_embeddings=self.max_position_embeddings,
899
+ scaling_factor=scaling_factor,
900
+ base=self.rope_theta,
901
+ **kwargs,
902
+ )
903
+ else:
904
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
905
+
906
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
907
+ return (
908
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
909
+ .transpose(1, 2)
910
+ .contiguous()
911
+ )
912
+
913
+ def forward(
914
+ self,
915
+ hidden_states: torch.Tensor,
916
+ attention_mask: Optional[torch.Tensor] = None,
917
+ position_ids: Optional[torch.LongTensor] = None,
918
+ past_key_value: Optional[Cache] = None,
919
+ output_attentions: bool = False,
920
+ use_cache: bool = False,
921
+ **kwargs,
922
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
923
+ if "padding_mask" in kwargs:
924
+ warnings.warn(
925
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
926
+ )
927
+ bsz, q_len, _ = hidden_states.size()
928
+
929
+ if self.q_lora_rank is None:
930
+ q = self.q_proj(hidden_states)
931
+ else:
932
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
933
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
934
+ q_nope, q_pe = torch.split(
935
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
936
+ )
937
+
938
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
939
+ compressed_kv, k_pe = torch.split(
940
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
941
+ )
942
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
943
+ kv = (
944
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
945
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
946
+ .transpose(1, 2)
947
+ )
948
+
949
+ k_nope, value_states = torch.split(
950
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
951
+ )
952
+ kv_seq_len = value_states.shape[-2]
953
+ if past_key_value is not None:
954
+ if self.layer_idx is None:
955
+ raise ValueError(
956
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
957
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
958
+ "with a layer index."
959
+ )
960
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
961
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
962
+
963
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
964
+
965
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
966
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
967
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
968
+
969
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
970
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
971
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
972
+ if past_key_value is not None:
973
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
974
+ key_states, value_states = past_key_value.update(
975
+ key_states, value_states, self.layer_idx, cache_kwargs
976
+ )
977
+
978
+ attn_weights = (
979
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
980
+ )
981
+
982
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
983
+ raise ValueError(
984
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
985
+ f" {attn_weights.size()}"
986
+ )
987
+ assert attention_mask is not None
988
+ if attention_mask is not None:
989
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
990
+ raise ValueError(
991
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
992
+ )
993
+ attn_weights = attn_weights + attention_mask
994
+
995
+ # upcast attention to fp32
996
+ attn_weights = nn.functional.softmax(
997
+ attn_weights, dim=-1, dtype=torch.float32
998
+ ).to(query_states.dtype)
999
+ attn_weights = nn.functional.dropout(
1000
+ attn_weights, p=self.attention_dropout, training=self.training
1001
+ )
1002
+ attn_output = torch.matmul(attn_weights, value_states)
1003
+
1004
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
1005
+ raise ValueError(
1006
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
1007
+ f" {attn_output.size()}"
1008
+ )
1009
+
1010
+ attn_output = attn_output.transpose(1, 2).contiguous()
1011
+
1012
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
1013
+
1014
+ attn_output = self.o_proj(attn_output)
1015
+
1016
+ if not output_attentions:
1017
+ attn_weights = None
1018
+
1019
+ return attn_output, attn_weights, past_key_value
1020
+
1021
+
1022
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2
1023
+ class DeepseekV2FlashAttention2(DeepseekV2Attention):
1024
+ """
1025
+ DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
1026
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
1027
+ flash attention and deal with padding tokens in case the input contains any of them.
1028
+ """
1029
+
1030
+ def __init__(self, *args, **kwargs):
1031
+ super().__init__(*args, **kwargs)
1032
+
1033
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1034
+ # 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.
1035
+ # 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).
1036
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1037
+
1038
+ def forward(
1039
+ self,
1040
+ hidden_states: torch.Tensor,
1041
+ attention_mask: Optional[torch.LongTensor] = None,
1042
+ position_ids: Optional[torch.LongTensor] = None,
1043
+ past_key_value: Optional[Cache] = None,
1044
+ output_attentions: bool = False,
1045
+ use_cache: bool = False,
1046
+ **kwargs,
1047
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1048
+ # DeepseekV2FlashAttention2 attention does not support output_attentions
1049
+ if "padding_mask" in kwargs:
1050
+ warnings.warn(
1051
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1052
+ )
1053
+
1054
+ # overwrite attention_mask with padding_mask
1055
+ attention_mask = kwargs.pop("padding_mask")
1056
+
1057
+ output_attentions = False
1058
+
1059
+ bsz, q_len, _ = hidden_states.size()
1060
+
1061
+ if self.q_lora_rank is None:
1062
+ q = self.q_proj(hidden_states)
1063
+ else:
1064
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1065
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1066
+ q_nope, q_pe = torch.split(
1067
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1068
+ )
1069
+
1070
+ # Flash attention requires the input to have the shape
1071
+ # batch_size x seq_length x head_dim x hidden_dim
1072
+ # therefore we just need to keep the original shape
1073
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1074
+ compressed_kv, k_pe = torch.split(
1075
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1076
+ )
1077
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1078
+ kv = (
1079
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1080
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1081
+ .transpose(1, 2)
1082
+ )
1083
+
1084
+ k_nope, value_states = torch.split(
1085
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1086
+ )
1087
+ kv_seq_len = value_states.shape[-2]
1088
+
1089
+ kv_seq_len = value_states.shape[-2]
1090
+ if past_key_value is not None:
1091
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1092
+
1093
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1094
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1095
+
1096
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1097
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1098
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1099
+
1100
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1101
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1102
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1103
+
1104
+ if self.q_head_dim != self.v_head_dim:
1105
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1106
+
1107
+ if past_key_value is not None:
1108
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1109
+ key_states, value_states = past_key_value.update(
1110
+ key_states, value_states, self.layer_idx, cache_kwargs
1111
+ )
1112
+
1113
+ # 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
1114
+ # to be able to avoid many of these transpose/reshape/view.
1115
+ query_states = query_states.transpose(1, 2)
1116
+ key_states = key_states.transpose(1, 2)
1117
+ value_states = value_states.transpose(1, 2)
1118
+
1119
+ dropout_rate = self.attention_dropout if self.training else 0.0
1120
+
1121
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1122
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1123
+ # cast them back in the correct dtype just to be sure everything works as expected.
1124
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1125
+ # in fp32. (DeepseekV2RMSNorm handles it correctly)
1126
+
1127
+ input_dtype = query_states.dtype
1128
+ if input_dtype == torch.float32:
1129
+ # Handle the case where the model is quantized
1130
+ if hasattr(self.config, "_pre_quantization_dtype"):
1131
+ target_dtype = self.config._pre_quantization_dtype
1132
+ elif torch.is_autocast_enabled():
1133
+ target_dtype = torch.get_autocast_gpu_dtype()
1134
+ else:
1135
+ target_dtype = (
1136
+ self.q_proj.weight.dtype
1137
+ if self.q_lora_rank is None
1138
+ else self.q_a_proj.weight.dtype
1139
+ )
1140
+
1141
+ logger.warning_once(
1142
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1143
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1144
+ f" {target_dtype}."
1145
+ )
1146
+
1147
+ query_states = query_states.to(target_dtype)
1148
+ key_states = key_states.to(target_dtype)
1149
+ value_states = value_states.to(target_dtype)
1150
+
1151
+ attn_output = self._flash_attention_forward(
1152
+ query_states,
1153
+ key_states,
1154
+ value_states,
1155
+ attention_mask,
1156
+ q_len,
1157
+ dropout=dropout_rate,
1158
+ softmax_scale=self.softmax_scale,
1159
+ )
1160
+ if self.q_head_dim != self.v_head_dim:
1161
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1162
+
1163
+ attn_output = attn_output.reshape(
1164
+ bsz, q_len, self.num_heads * self.v_head_dim
1165
+ ).contiguous()
1166
+ attn_output = self.o_proj(attn_output)
1167
+
1168
+ if not output_attentions:
1169
+ attn_weights = None
1170
+
1171
+ return attn_output, attn_weights, past_key_value
1172
+
1173
+ def _flash_attention_forward(
1174
+ self,
1175
+ query_states,
1176
+ key_states,
1177
+ value_states,
1178
+ attention_mask,
1179
+ query_length,
1180
+ dropout=0.0,
1181
+ softmax_scale=None,
1182
+ ):
1183
+ """
1184
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1185
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1186
+
1187
+ Args:
1188
+ query_states (`torch.Tensor`):
1189
+ Input query states to be passed to Flash Attention API
1190
+ key_states (`torch.Tensor`):
1191
+ Input key states to be passed to Flash Attention API
1192
+ value_states (`torch.Tensor`):
1193
+ Input value states to be passed to Flash Attention API
1194
+ attention_mask (`torch.Tensor`):
1195
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1196
+ position of padding tokens and 1 for the position of non-padding tokens.
1197
+ dropout (`int`, *optional*):
1198
+ Attention dropout
1199
+ softmax_scale (`float`, *optional*):
1200
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1201
+ """
1202
+ if not self._flash_attn_uses_top_left_mask:
1203
+ causal = self.is_causal
1204
+ else:
1205
+ # 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__.
1206
+ causal = self.is_causal and query_length != 1
1207
+
1208
+ # Contains at least one padding token in the sequence
1209
+ if attention_mask is not None:
1210
+ batch_size = query_states.shape[0]
1211
+ (
1212
+ query_states,
1213
+ key_states,
1214
+ value_states,
1215
+ indices_q,
1216
+ cu_seq_lens,
1217
+ max_seq_lens,
1218
+ ) = self._upad_input(
1219
+ query_states, key_states, value_states, attention_mask, query_length
1220
+ )
1221
+
1222
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1223
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1224
+
1225
+ attn_output_unpad = flash_attn_varlen_func(
1226
+ query_states,
1227
+ key_states,
1228
+ value_states,
1229
+ cu_seqlens_q=cu_seqlens_q,
1230
+ cu_seqlens_k=cu_seqlens_k,
1231
+ max_seqlen_q=max_seqlen_in_batch_q,
1232
+ max_seqlen_k=max_seqlen_in_batch_k,
1233
+ dropout_p=dropout,
1234
+ softmax_scale=softmax_scale,
1235
+ causal=causal,
1236
+ )
1237
+
1238
+ attn_output = pad_input(
1239
+ attn_output_unpad, indices_q, batch_size, query_length
1240
+ )
1241
+ else:
1242
+ attn_output = flash_attn_func(
1243
+ query_states,
1244
+ key_states,
1245
+ value_states,
1246
+ dropout,
1247
+ softmax_scale=softmax_scale,
1248
+ causal=causal,
1249
+ )
1250
+
1251
+ return attn_output
1252
+
1253
+ def _upad_input(
1254
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1255
+ ):
1256
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1257
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1258
+
1259
+ key_layer = index_first_axis(
1260
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1261
+ indices_k,
1262
+ )
1263
+ value_layer = index_first_axis(
1264
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1265
+ indices_k,
1266
+ )
1267
+ if query_length == kv_seq_len:
1268
+ query_layer = index_first_axis(
1269
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1270
+ indices_k,
1271
+ )
1272
+ cu_seqlens_q = cu_seqlens_k
1273
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1274
+ indices_q = indices_k
1275
+ elif query_length == 1:
1276
+ max_seqlen_in_batch_q = 1
1277
+ cu_seqlens_q = torch.arange(
1278
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1279
+ ) # There is a memcpy here, that is very bad.
1280
+ indices_q = cu_seqlens_q[:-1]
1281
+ query_layer = query_layer.squeeze(1)
1282
+ else:
1283
+ # The -q_len: slice assumes left padding.
1284
+ attention_mask = attention_mask[:, -query_length:]
1285
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1286
+ query_layer, attention_mask
1287
+ )
1288
+
1289
+ return (
1290
+ query_layer,
1291
+ key_layer,
1292
+ value_layer,
1293
+ indices_q,
1294
+ (cu_seqlens_q, cu_seqlens_k),
1295
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1296
+ )
1297
+
1298
+
1299
+ ATTENTION_CLASSES = {
1300
+ "eager": DeepseekV2Attention,
1301
+ "flash_attention_2": DeepseekV2FlashAttention2,
1302
+ }
1303
+
1304
+
1305
+ class DeepseekV2DecoderLayer(nn.Module):
1306
+ def __init__(self, config: DeepseekV2Config, layer_idx: int):
1307
+ super().__init__()
1308
+ self.hidden_size = config.hidden_size
1309
+
1310
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1311
+ config=config, layer_idx=layer_idx
1312
+ )
1313
+
1314
+ self.mlp = (
1315
+ DeepseekV2MoE(config)
1316
+ if (
1317
+ config.n_routed_experts is not None
1318
+ and layer_idx >= config.first_k_dense_replace
1319
+ and layer_idx % config.moe_layer_freq == 0
1320
+ )
1321
+ else DeepseekV2MLP(config)
1322
+ )
1323
+ self.input_layernorm = DeepseekV2RMSNorm(
1324
+ config.hidden_size, eps=config.rms_norm_eps
1325
+ )
1326
+ self.post_attention_layernorm = DeepseekV2RMSNorm(
1327
+ config.hidden_size, eps=config.rms_norm_eps
1328
+ )
1329
+
1330
+ def forward(
1331
+ self,
1332
+ hidden_states: torch.Tensor,
1333
+ attention_mask: Optional[torch.Tensor] = None,
1334
+ position_ids: Optional[torch.LongTensor] = None,
1335
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1336
+ output_attentions: Optional[bool] = False,
1337
+ use_cache: Optional[bool] = False,
1338
+ **kwargs,
1339
+ ) -> Tuple[
1340
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1341
+ ]:
1342
+ """
1343
+ Args:
1344
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1345
+ attention_mask (`torch.FloatTensor`, *optional*):
1346
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1347
+ query_sequence_length, key_sequence_length)` if default attention is used.
1348
+ output_attentions (`bool`, *optional*):
1349
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1350
+ returned tensors for more detail.
1351
+ use_cache (`bool`, *optional*):
1352
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1353
+ (see `past_key_values`).
1354
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1355
+ """
1356
+ if "padding_mask" in kwargs:
1357
+ warnings.warn(
1358
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1359
+ )
1360
+ residual = hidden_states
1361
+
1362
+ hidden_states = self.input_layernorm(hidden_states)
1363
+
1364
+ # Self Attention
1365
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1366
+ hidden_states=hidden_states,
1367
+ attention_mask=attention_mask,
1368
+ position_ids=position_ids,
1369
+ past_key_value=past_key_value,
1370
+ output_attentions=output_attentions,
1371
+ use_cache=use_cache,
1372
+ **kwargs,
1373
+ )
1374
+ hidden_states = residual + hidden_states
1375
+
1376
+ # Fully Connected
1377
+ residual = hidden_states
1378
+ hidden_states = self.post_attention_layernorm(hidden_states)
1379
+ hidden_states = self.mlp(hidden_states)
1380
+ hidden_states = residual + hidden_states
1381
+
1382
+ outputs = (hidden_states,)
1383
+
1384
+ if output_attentions:
1385
+ outputs += (self_attn_weights,)
1386
+
1387
+ if use_cache:
1388
+ outputs += (present_key_value,)
1389
+
1390
+ return outputs
1391
+
1392
+
1393
+ DeepseekV2_START_DOCSTRING = r"""
1394
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1395
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1396
+ etc.)
1397
+
1398
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1399
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1400
+ and behavior.
1401
+
1402
+ Parameters:
1403
+ config ([`DeepseekV2Config`]):
1404
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1405
+ load the weights associated with the model, only the configuration. Check out the
1406
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1407
+ """
1408
+
1409
+
1410
+ @add_start_docstrings(
1411
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1412
+ DeepseekV2_START_DOCSTRING,
1413
+ )
1414
+ class DeepseekV2PreTrainedModel(PreTrainedModel):
1415
+ config_class = DeepseekV2Config
1416
+ base_model_prefix = "model"
1417
+ supports_gradient_checkpointing = True
1418
+ _no_split_modules = ["DeepseekV2DecoderLayer"]
1419
+ _skip_keys_device_placement = "past_key_values"
1420
+ _supports_flash_attn_2 = True
1421
+ _supports_cache_class = True
1422
+
1423
+ def _init_weights(self, module):
1424
+ std = self.config.initializer_range
1425
+ if isinstance(module, nn.Linear):
1426
+ module.weight.data.normal_(mean=0.0, std=std)
1427
+ if module.bias is not None:
1428
+ module.bias.data.zero_()
1429
+ elif isinstance(module, nn.Embedding):
1430
+ module.weight.data.normal_(mean=0.0, std=std)
1431
+ if module.padding_idx is not None:
1432
+ module.weight.data[module.padding_idx].zero_()
1433
+
1434
+
1435
+ DeepseekV2_INPUTS_DOCSTRING = r"""
1436
+ Args:
1437
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1438
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1439
+ it.
1440
+
1441
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1442
+ [`PreTrainedTokenizer.__call__`] for details.
1443
+
1444
+ [What are input IDs?](../glossary#input-ids)
1445
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1446
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1447
+
1448
+ - 1 for tokens that are **not masked**,
1449
+ - 0 for tokens that are **masked**.
1450
+
1451
+ [What are attention masks?](../glossary#attention-mask)
1452
+
1453
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1454
+ [`PreTrainedTokenizer.__call__`] for details.
1455
+
1456
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1457
+ `past_key_values`).
1458
+
1459
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1460
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1461
+ information on the default strategy.
1462
+
1463
+ - 1 indicates the head is **not masked**,
1464
+ - 0 indicates the head is **masked**.
1465
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1466
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1467
+ config.n_positions - 1]`.
1468
+
1469
+ [What are position IDs?](../glossary#position-ids)
1470
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1471
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1472
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1473
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1474
+
1475
+ Two formats are allowed:
1476
+ - a [`~cache_utils.Cache`] instance;
1477
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1478
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1479
+ cache format.
1480
+
1481
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1482
+ legacy cache format will be returned.
1483
+
1484
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1485
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1486
+ of shape `(batch_size, sequence_length)`.
1487
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1488
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1489
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1490
+ model's internal embedding lookup matrix.
1491
+ use_cache (`bool`, *optional*):
1492
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1493
+ `past_key_values`).
1494
+ output_attentions (`bool`, *optional*):
1495
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1496
+ tensors for more detail.
1497
+ output_hidden_states (`bool`, *optional*):
1498
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1499
+ more detail.
1500
+ return_dict (`bool`, *optional*):
1501
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1502
+ """
1503
+
1504
+
1505
+ @add_start_docstrings(
1506
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1507
+ DeepseekV2_START_DOCSTRING,
1508
+ )
1509
+ class DeepseekV2Model(DeepseekV2PreTrainedModel):
1510
+ """
1511
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
1512
+
1513
+ Args:
1514
+ config: DeepseekV2Config
1515
+ """
1516
+
1517
+ def __init__(self, config: DeepseekV2Config):
1518
+ super().__init__(config)
1519
+ self.padding_idx = config.pad_token_id
1520
+ self.vocab_size = config.vocab_size
1521
+
1522
+ self.embed_tokens = nn.Embedding(
1523
+ config.vocab_size, config.hidden_size, self.padding_idx
1524
+ )
1525
+ self.layers = nn.ModuleList(
1526
+ [
1527
+ DeepseekV2DecoderLayer(config, layer_idx)
1528
+ for layer_idx in range(config.num_hidden_layers)
1529
+ ]
1530
+ )
1531
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1532
+ self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1533
+
1534
+ self.gradient_checkpointing = False
1535
+ # Initialize weights and apply final processing
1536
+ self.post_init()
1537
+
1538
+ def get_input_embeddings(self):
1539
+ return self.embed_tokens
1540
+
1541
+ def set_input_embeddings(self, value):
1542
+ self.embed_tokens = value
1543
+
1544
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1545
+ def forward(
1546
+ self,
1547
+ input_ids: torch.LongTensor = None,
1548
+ attention_mask: Optional[torch.Tensor] = None,
1549
+ position_ids: Optional[torch.LongTensor] = None,
1550
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1551
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1552
+ use_cache: Optional[bool] = None,
1553
+ output_attentions: Optional[bool] = None,
1554
+ output_hidden_states: Optional[bool] = None,
1555
+ return_dict: Optional[bool] = None,
1556
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1557
+ output_attentions = (
1558
+ output_attentions
1559
+ if output_attentions is not None
1560
+ else self.config.output_attentions
1561
+ )
1562
+ output_hidden_states = (
1563
+ output_hidden_states
1564
+ if output_hidden_states is not None
1565
+ else self.config.output_hidden_states
1566
+ )
1567
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1568
+
1569
+ return_dict = (
1570
+ return_dict if return_dict is not None else self.config.use_return_dict
1571
+ )
1572
+
1573
+ # retrieve input_ids and inputs_embeds
1574
+ if input_ids is not None and inputs_embeds is not None:
1575
+ raise ValueError(
1576
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1577
+ )
1578
+ elif input_ids is not None:
1579
+ batch_size, seq_length = input_ids.shape[:2]
1580
+ elif inputs_embeds is not None:
1581
+ batch_size, seq_length = inputs_embeds.shape[:2]
1582
+ else:
1583
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1584
+
1585
+ if self.gradient_checkpointing and self.training:
1586
+ if use_cache:
1587
+ logger.warning_once(
1588
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1589
+ )
1590
+ use_cache = False
1591
+
1592
+ past_key_values_length = 0
1593
+ if use_cache:
1594
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1595
+ if use_legacy_cache:
1596
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1597
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1598
+
1599
+ if position_ids is None:
1600
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1601
+ position_ids = torch.arange(
1602
+ past_key_values_length,
1603
+ seq_length + past_key_values_length,
1604
+ dtype=torch.long,
1605
+ device=device,
1606
+ )
1607
+ position_ids = position_ids.unsqueeze(0)
1608
+
1609
+ if inputs_embeds is None:
1610
+ inputs_embeds = self.embed_tokens(input_ids)
1611
+
1612
+ if self._use_flash_attention_2:
1613
+ # 2d mask is passed through the layers
1614
+ attention_mask = (
1615
+ attention_mask
1616
+ if (attention_mask is not None and 0 in attention_mask)
1617
+ else None
1618
+ )
1619
+ else:
1620
+ # 4d mask is passed through the layers
1621
+ attention_mask = _prepare_4d_causal_attention_mask(
1622
+ attention_mask,
1623
+ (batch_size, seq_length),
1624
+ inputs_embeds,
1625
+ past_key_values_length,
1626
+ )
1627
+
1628
+ # embed positions
1629
+ hidden_states = inputs_embeds
1630
+
1631
+ # decoder layers
1632
+ all_hidden_states = () if output_hidden_states else None
1633
+ all_self_attns = () if output_attentions else None
1634
+ next_decoder_cache = None
1635
+
1636
+ for decoder_layer in self.layers:
1637
+ if output_hidden_states:
1638
+ all_hidden_states += (hidden_states,)
1639
+
1640
+ if self.gradient_checkpointing and self.training:
1641
+ layer_outputs = self._gradient_checkpointing_func(
1642
+ decoder_layer.__call__,
1643
+ hidden_states,
1644
+ attention_mask,
1645
+ position_ids,
1646
+ past_key_values,
1647
+ output_attentions,
1648
+ use_cache,
1649
+ )
1650
+ else:
1651
+ layer_outputs = decoder_layer(
1652
+ hidden_states,
1653
+ attention_mask=attention_mask,
1654
+ position_ids=position_ids,
1655
+ past_key_value=past_key_values,
1656
+ output_attentions=output_attentions,
1657
+ use_cache=use_cache,
1658
+ )
1659
+
1660
+ hidden_states = layer_outputs[0]
1661
+
1662
+ if use_cache:
1663
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1664
+
1665
+ if output_attentions:
1666
+ all_self_attns += (layer_outputs[1],)
1667
+
1668
+ hidden_states = self.norm(hidden_states)
1669
+
1670
+ # add hidden states from the last decoder layer
1671
+ if output_hidden_states:
1672
+ all_hidden_states += (hidden_states,)
1673
+
1674
+ next_cache = None
1675
+ if use_cache:
1676
+ next_cache = (
1677
+ next_decoder_cache.to_legacy_cache()
1678
+ if use_legacy_cache
1679
+ else next_decoder_cache
1680
+ )
1681
+ if not return_dict:
1682
+ return tuple(
1683
+ v
1684
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1685
+ if v is not None
1686
+ )
1687
+ return BaseModelOutputWithPast(
1688
+ last_hidden_state=hidden_states,
1689
+ past_key_values=next_cache,
1690
+ hidden_states=all_hidden_states,
1691
+ attentions=all_self_attns,
1692
+ )
1693
+
1694
+
1695
+ class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
1696
+ _tied_weights_keys = ["lm_head.weight"]
1697
+
1698
+ def __init__(self, config):
1699
+ super().__init__(config)
1700
+ self.model = DeepseekV2Model(config)
1701
+ self.vocab_size = config.vocab_size
1702
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1703
+
1704
+ # Initialize weights and apply final processing
1705
+ self.post_init()
1706
+
1707
+ def get_input_embeddings(self):
1708
+ return self.model.embed_tokens
1709
+
1710
+ def set_input_embeddings(self, value):
1711
+ self.model.embed_tokens = value
1712
+
1713
+ def get_output_embeddings(self):
1714
+ return self.lm_head
1715
+
1716
+ def set_output_embeddings(self, new_embeddings):
1717
+ self.lm_head = new_embeddings
1718
+
1719
+ def set_decoder(self, decoder):
1720
+ self.model = decoder
1721
+
1722
+ def get_decoder(self):
1723
+ return self.model
1724
+
1725
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1726
+ @replace_return_docstrings(
1727
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1728
+ )
1729
+ def forward(
1730
+ self,
1731
+ input_ids: torch.LongTensor = None,
1732
+ attention_mask: Optional[torch.Tensor] = None,
1733
+ position_ids: Optional[torch.LongTensor] = None,
1734
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1735
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1736
+ labels: Optional[torch.LongTensor] = None,
1737
+ use_cache: Optional[bool] = None,
1738
+ output_attentions: Optional[bool] = None,
1739
+ output_hidden_states: Optional[bool] = None,
1740
+ return_dict: Optional[bool] = None,
1741
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1742
+ r"""
1743
+ Args:
1744
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1745
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1746
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1747
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1748
+
1749
+ Returns:
1750
+
1751
+ Example:
1752
+
1753
+ ```python
1754
+ >>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
1755
+
1756
+ >>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1757
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1758
+
1759
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1760
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1761
+
1762
+ >>> # Generate
1763
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1764
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1765
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1766
+ ```"""
1767
+ output_attentions = (
1768
+ output_attentions
1769
+ if output_attentions is not None
1770
+ else self.config.output_attentions
1771
+ )
1772
+ output_hidden_states = (
1773
+ output_hidden_states
1774
+ if output_hidden_states is not None
1775
+ else self.config.output_hidden_states
1776
+ )
1777
+ return_dict = (
1778
+ return_dict if return_dict is not None else self.config.use_return_dict
1779
+ )
1780
+
1781
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1782
+ outputs = self.model(
1783
+ input_ids=input_ids,
1784
+ attention_mask=attention_mask,
1785
+ position_ids=position_ids,
1786
+ past_key_values=past_key_values,
1787
+ inputs_embeds=inputs_embeds,
1788
+ use_cache=use_cache,
1789
+ output_attentions=output_attentions,
1790
+ output_hidden_states=output_hidden_states,
1791
+ return_dict=return_dict,
1792
+ )
1793
+
1794
+ hidden_states = outputs[0]
1795
+ logits = self.lm_head(hidden_states)
1796
+ logits = logits.float()
1797
+
1798
+ loss = None
1799
+ if labels is not None:
1800
+ # Shift so that tokens < n predict n
1801
+ shift_logits = logits[..., :-1, :].contiguous()
1802
+ shift_labels = labels[..., 1:].contiguous()
1803
+ # Flatten the tokens
1804
+ loss_fct = CrossEntropyLoss()
1805
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1806
+ shift_labels = shift_labels.view(-1)
1807
+ # Enable model parallelism
1808
+ shift_labels = shift_labels.to(shift_logits.device)
1809
+ loss = loss_fct(shift_logits, shift_labels)
1810
+
1811
+ if not return_dict:
1812
+ output = (logits,) + outputs[1:]
1813
+ return (loss,) + output if loss is not None else output
1814
+
1815
+ return CausalLMOutputWithPast(
1816
+ loss=loss,
1817
+ logits=logits,
1818
+ past_key_values=outputs.past_key_values,
1819
+ hidden_states=outputs.hidden_states,
1820
+ attentions=outputs.attentions,
1821
+ )
1822
+
1823
+ def prepare_inputs_for_generation(
1824
+ self,
1825
+ input_ids,
1826
+ past_key_values=None,
1827
+ attention_mask=None,
1828
+ inputs_embeds=None,
1829
+ **kwargs,
1830
+ ):
1831
+ if past_key_values is not None:
1832
+ if isinstance(past_key_values, Cache):
1833
+ cache_length = past_key_values.get_seq_length()
1834
+ past_length = past_key_values.seen_tokens
1835
+ max_cache_length = past_key_values.get_max_length()
1836
+ else:
1837
+ cache_length = past_length = past_key_values[0][0].shape[2]
1838
+ max_cache_length = None
1839
+
1840
+ # Keep only the unprocessed tokens:
1841
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1842
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1843
+ # input)
1844
+ if (
1845
+ attention_mask is not None
1846
+ and attention_mask.shape[1] > input_ids.shape[1]
1847
+ ):
1848
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1849
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1850
+ # input_ids based on the past_length.
1851
+ elif past_length < input_ids.shape[1]:
1852
+ input_ids = input_ids[:, past_length:]
1853
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1854
+
1855
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1856
+ if (
1857
+ max_cache_length is not None
1858
+ and attention_mask is not None
1859
+ and cache_length + input_ids.shape[1] > max_cache_length
1860
+ ):
1861
+ attention_mask = attention_mask[:, -max_cache_length:]
1862
+
1863
+ position_ids = kwargs.get("position_ids", None)
1864
+ if attention_mask is not None and position_ids is None:
1865
+ # create position_ids on the fly for batch generation
1866
+ position_ids = attention_mask.long().cumsum(-1) - 1
1867
+ position_ids.masked_fill_(attention_mask == 0, 1)
1868
+ if past_key_values:
1869
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1870
+
1871
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1872
+ if inputs_embeds is not None and past_key_values is None:
1873
+ model_inputs = {"inputs_embeds": inputs_embeds}
1874
+ else:
1875
+ model_inputs = {"input_ids": input_ids}
1876
+
1877
+ model_inputs.update(
1878
+ {
1879
+ "position_ids": position_ids,
1880
+ "past_key_values": past_key_values,
1881
+ "use_cache": kwargs.get("use_cache"),
1882
+ "attention_mask": attention_mask,
1883
+ }
1884
+ )
1885
+ return model_inputs
1886
+
1887
+ @staticmethod
1888
+ def _reorder_cache(past_key_values, beam_idx):
1889
+ reordered_past = ()
1890
+ for layer_past in past_key_values:
1891
+ reordered_past += (
1892
+ tuple(
1893
+ past_state.index_select(0, beam_idx.to(past_state.device))
1894
+ for past_state in layer_past
1895
+ ),
1896
+ )
1897
+ return reordered_past
1898
+
1899
+
1900
+ @add_start_docstrings(
1901
+ """
1902
+ The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
1903
+
1904
+ [`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1905
+ (e.g. GPT-2) do.
1906
+
1907
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1908
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1909
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1910
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1911
+ each row of the batch).
1912
+ """,
1913
+ DeepseekV2_START_DOCSTRING,
1914
+ )
1915
+ class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel):
1916
+ def __init__(self, config):
1917
+ super().__init__(config)
1918
+ self.num_labels = config.num_labels
1919
+ self.model = DeepseekV2Model(config)
1920
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1921
+
1922
+ # Initialize weights and apply final processing
1923
+ self.post_init()
1924
+
1925
+ def get_input_embeddings(self):
1926
+ return self.model.embed_tokens
1927
+
1928
+ def set_input_embeddings(self, value):
1929
+ self.model.embed_tokens = value
1930
+
1931
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1932
+ def forward(
1933
+ self,
1934
+ input_ids: torch.LongTensor = None,
1935
+ attention_mask: Optional[torch.Tensor] = None,
1936
+ position_ids: Optional[torch.LongTensor] = None,
1937
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1938
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1939
+ labels: Optional[torch.LongTensor] = None,
1940
+ use_cache: Optional[bool] = None,
1941
+ output_attentions: Optional[bool] = None,
1942
+ output_hidden_states: Optional[bool] = None,
1943
+ return_dict: Optional[bool] = None,
1944
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1945
+ r"""
1946
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1947
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1948
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1949
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1950
+ """
1951
+ return_dict = (
1952
+ return_dict if return_dict is not None else self.config.use_return_dict
1953
+ )
1954
+
1955
+ transformer_outputs = self.model(
1956
+ input_ids,
1957
+ attention_mask=attention_mask,
1958
+ position_ids=position_ids,
1959
+ past_key_values=past_key_values,
1960
+ inputs_embeds=inputs_embeds,
1961
+ use_cache=use_cache,
1962
+ output_attentions=output_attentions,
1963
+ output_hidden_states=output_hidden_states,
1964
+ return_dict=return_dict,
1965
+ )
1966
+ hidden_states = transformer_outputs[0]
1967
+ logits = self.score(hidden_states)
1968
+
1969
+ if input_ids is not None:
1970
+ batch_size = input_ids.shape[0]
1971
+ else:
1972
+ batch_size = inputs_embeds.shape[0]
1973
+
1974
+ if self.config.pad_token_id is None and batch_size != 1:
1975
+ raise ValueError(
1976
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1977
+ )
1978
+ if self.config.pad_token_id is None:
1979
+ sequence_lengths = -1
1980
+ else:
1981
+ if input_ids is not None:
1982
+ sequence_lengths = (
1983
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1984
+ ).to(logits.device)
1985
+ else:
1986
+ sequence_lengths = -1
1987
+
1988
+ pooled_logits = logits[
1989
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1990
+ ]
1991
+
1992
+ loss = None
1993
+ if labels is not None:
1994
+ labels = labels.to(logits.device)
1995
+ if self.config.problem_type is None:
1996
+ if self.num_labels == 1:
1997
+ self.config.problem_type = "regression"
1998
+ elif self.num_labels > 1 and (
1999
+ labels.dtype == torch.long or labels.dtype == torch.int
2000
+ ):
2001
+ self.config.problem_type = "single_label_classification"
2002
+ else:
2003
+ self.config.problem_type = "multi_label_classification"
2004
+
2005
+ if self.config.problem_type == "regression":
2006
+ loss_fct = MSELoss()
2007
+ if self.num_labels == 1:
2008
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2009
+ else:
2010
+ loss = loss_fct(pooled_logits, labels)
2011
+ elif self.config.problem_type == "single_label_classification":
2012
+ loss_fct = CrossEntropyLoss()
2013
+ loss = loss_fct(
2014
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2015
+ )
2016
+ elif self.config.problem_type == "multi_label_classification":
2017
+ loss_fct = BCEWithLogitsLoss()
2018
+ loss = loss_fct(pooled_logits, labels)
2019
+ if not return_dict:
2020
+ output = (pooled_logits,) + transformer_outputs[1:]
2021
+ return ((loss,) + output) if loss is not None else output
2022
+
2023
+ return SequenceClassifierOutputWithPast(
2024
+ loss=loss,
2025
+ logits=pooled_logits,
2026
+ past_key_values=transformer_outputs.past_key_values,
2027
+ hidden_states=transformer_outputs.hidden_states,
2028
+ attentions=transformer_outputs.attentions,
2029
+ )
tokenization_deepseek_fast.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Union
2
+
3
+
4
+ from transformers.models.llama import LlamaTokenizerFast
5
+
6
+
7
+ class DeepseekTokenizerFast(LlamaTokenizerFast):
8
+
9
+ def convert_ids_to_tokens(
10
+ self, ids: Union[int, List[int]], skip_special_tokens: bool = False
11
+ ) -> Union[str, List[str]]:
12
+ """
13
+ Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and
14
+ added tokens.
15
+
16
+ Args:
17
+ ids (`int` or `List[int]`):
18
+ The token id (or token ids) to convert to tokens.
19
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
20
+ Whether or not to remove special tokens in the decoding.
21
+
22
+ Returns:
23
+ `str` or `List[str]`: The decoded token(s).
24
+ """
25
+ if isinstance(ids, int):
26
+ return self._convert_id_to_token(ids)
27
+ tokens = []
28
+ for index in ids:
29
+ index = int(index)
30
+ if skip_special_tokens and index in self.all_special_ids:
31
+ continue
32
+ token = self._tokenizer.id_to_token(index)
33
+ tokens.append(token if token is not None else "")
34
+ return tokens
35
+
36
+ def _convert_id_to_token(self, index: int) -> Optional[str]:
37
+ token = self._tokenizer.id_to_token(int(index))
38
+ return token if token is not None else ""
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<|begin▁of▁sentence|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|end▁of▁sentence|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": true,
22
+ "model_max_length": 16384,
23
+ "pad_token": {
24
+ "__type": "AddedToken",
25
+ "content": "<|end▁of▁sentence|>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "sp_model_kwargs": {},
32
+ "unk_token": null,
33
+ "tokenizer_class": "LlamaTokenizerFast",
34
+ "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 %}"
35
+ }