agreeupon commited on
Commit
1565152
·
verified ·
1 Parent(s): b2747a9

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. DeepSeek-V3-Base/.gitattributes +35 -0
  2. DeepSeek-V3-Base/LICENSE-CODE +21 -0
  3. DeepSeek-V3-Base/LICENSE-MODEL +91 -0
  4. DeepSeek-V3-Base/README.md +336 -0
  5. DeepSeek-V3-Base/README_WEIGHTS.md +94 -0
  6. DeepSeek-V3-Base/configuration_deepseek.py +199 -0
  7. DeepSeek-V3-Base/figures/benchmark.png +3 -0
  8. DeepSeek-V3-Base/inference/configs/config_16B.json +19 -0
  9. DeepSeek-V3-Base/inference/configs/config_236B.json +20 -0
  10. DeepSeek-V3-Base/inference/configs/config_671B.json +22 -0
  11. DeepSeek-V3-Base/inference/convert.py +84 -0
  12. DeepSeek-V3-Base/inference/fp8_cast_bf16.py +81 -0
  13. DeepSeek-V3-Base/inference/generate.py +137 -0
  14. DeepSeek-V3-Base/inference/kernel.py +108 -0
  15. DeepSeek-V3-Base/inference/model.py +421 -0
  16. DeepSeek-V3-Base/inference/requirements.txt +4 -0
  17. DeepSeek-V3-Base/model-00064-of-000163.safetensors +3 -0
  18. DeepSeek-V3-Base/model-00069-of-000163.safetensors +3 -0
  19. DeepSeek-V3-Base/model-00073-of-000163.safetensors +3 -0
  20. DeepSeek-V3-Base/model-00082-of-000163.safetensors +3 -0
  21. DeepSeek-V3-Base/model-00084-of-000163.safetensors +3 -0
  22. DeepSeek-V3-Base/model-00085-of-000163.safetensors +3 -0
  23. DeepSeek-V3-Base/model-00088-of-000163.safetensors +3 -0
  24. DeepSeek-V3-Base/model-00090-of-000163.safetensors +3 -0
  25. DeepSeek-V3-Base/model-00091-of-000163.safetensors +3 -0
  26. DeepSeek-V3-Base/model-00092-of-000163.safetensors +3 -0
  27. DeepSeek-V3-Base/model-00093-of-000163.safetensors +3 -0
  28. DeepSeek-V3-Base/model-00094-of-000163.safetensors +3 -0
  29. DeepSeek-V3-Base/model-00098-of-000163.safetensors +3 -0
  30. DeepSeek-V3-Base/model-00110-of-000163.safetensors +3 -0
  31. DeepSeek-V3-Base/model-00116-of-000163.safetensors +3 -0
  32. DeepSeek-V3-Base/model-00118-of-000163.safetensors +3 -0
  33. DeepSeek-V3-Base/model-00135-of-000163.safetensors +3 -0
  34. DeepSeek-V3-Base/model-00149-of-000163.safetensors +3 -0
  35. DeepSeek-V3-Base/model-00154-of-000163.safetensors +3 -0
  36. flash-attention/.gitignore +27 -0
  37. flash-attention/.gitmodules +3 -0
  38. flash-attention/AUTHORS +1 -0
  39. flash-attention/LICENSE +29 -0
  40. flash-attention/MANIFEST.in +11 -0
  41. flash-attention/Makefile +9 -0
  42. flash-attention/README.md +417 -0
  43. flash-attention/setup.py +386 -0
  44. flash-attention/tests/models/test_vit.py +48 -0
  45. flash-attention/tests/modules/test_embedding_parallel.py +106 -0
  46. flash-attention/tests/modules/test_mha_parallel.py +160 -0
  47. flash-attention/tests/modules/test_mlp_parallel.py +143 -0
  48. flash-attention/tests/ops/test_dropout_layer_norm.py +1189 -0
  49. flash-attention/tests/ops/test_fused_dense.py +172 -0
  50. flash-attention/tests/ops/test_fused_dense_parallel.py +237 -0
DeepSeek-V3-Base/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
DeepSeek-V3-Base/LICENSE-CODE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
DeepSeek-V3-Base/LICENSE-MODEL 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.
DeepSeek-V3-Base/README.md ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- markdownlint-disable first-line-h1 -->
2
+ <!-- markdownlint-disable html -->
3
+ <!-- markdownlint-disable no-duplicate-header -->
4
+
5
+ <div align="center">
6
+ <img src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/logo.svg?raw=true" width="60%" alt="DeepSeek-V3" />
7
+ </div>
8
+ <hr>
9
+ <div align="center" style="line-height: 1;">
10
+ <a href="https://www.deepseek.com/" target="_blank" style="margin: 2px;">
11
+ <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;"/>
12
+ </a>
13
+ <a href="https://chat.deepseek.com/" target="_blank" style="margin: 2px;">
14
+ <img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-DeepSeek%20V3-536af5?color=536af5&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
15
+ </a>
16
+ <a href="https://huggingface.co/deepseek-ai" target="_blank" style="margin: 2px;">
17
+ <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;"/>
18
+ </a>
19
+ </div>
20
+
21
+ <div align="center" style="line-height: 1;">
22
+ <a href="https://discord.gg/Tc7c45Zzu5" target="_blank" style="margin: 2px;">
23
+ <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;"/>
24
+ </a>
25
+ <a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/qr.jpeg?raw=true" target="_blank" style="margin: 2px;">
26
+ <img alt="Wechat" src="https://img.shields.io/badge/WeChat-DeepSeek%20AI-brightgreen?logo=wechat&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
27
+ </a>
28
+ <a href="https://twitter.com/deepseek_ai" target="_blank" style="margin: 2px;">
29
+ <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;"/>
30
+ </a>
31
+ </div>
32
+
33
+ <div align="center" style="line-height: 1;">
34
+ <a href="https://github.com/deepseek-ai/DeepSeek-V3/blob/main/LICENSE-CODE" style="margin: 2px;">
35
+ <img alt="Code License" src="https://img.shields.io/badge/Code_License-MIT-f5de53?&color=f5de53" style="display: inline-block; vertical-align: middle;"/>
36
+ </a>
37
+ <a href="https://github.com/deepseek-ai/DeepSeek-V3/blob/main/LICENSE-MODEL" style="margin: 2px;">
38
+ <img alt="Model License" src="https://img.shields.io/badge/Model_License-Model_Agreement-f5de53?&color=f5de53" style="display: inline-block; vertical-align: middle;"/>
39
+ </a>
40
+ </div>
41
+
42
+
43
+ <p align="center">
44
+ <a href="https://github.com/deepseek-ai/DeepSeek-V3/blob/main/DeepSeek_V3.pdf"><b>Paper Link</b>👁️</a>
45
+ </p>
46
+
47
+
48
+ ## 1. Introduction
49
+
50
+ We present DeepSeek-V3, a strong Mixture-of-Experts (MoE) language model with 671B total parameters with 37B activated for each token.
51
+ To achieve efficient inference and cost-effective training, DeepSeek-V3 adopts Multi-head Latent Attention (MLA) and DeepSeekMoE architectures, which were thoroughly validated in DeepSeek-V2.
52
+ Furthermore, DeepSeek-V3 pioneers an auxiliary-loss-free strategy for load balancing and sets a multi-token prediction training objective for stronger performance.
53
+ We pre-train DeepSeek-V3 on 14.8 trillion diverse and high-quality tokens, followed by Supervised Fine-Tuning and Reinforcement Learning stages to fully harness its capabilities.
54
+ Comprehensive evaluations reveal that DeepSeek-V3 outperforms other open-source models and achieves performance comparable to leading closed-source models.
55
+ Despite its excellent performance, DeepSeek-V3 requires only 2.788M H800 GPU hours for its full training.
56
+ In addition, its training process is remarkably stable.
57
+ Throughout the entire training process, we did not experience any irrecoverable loss spikes or perform any rollbacks.
58
+ <p align="center">
59
+ <img width="80%" src="figures/benchmark.png">
60
+ </p>
61
+
62
+ ## 2. Model Summary
63
+
64
+ ---
65
+
66
+ **Architecture: Innovative Load Balancing Strategy and Training Objective**
67
+
68
+ - On top of the efficient architecture of DeepSeek-V2, we pioneer an auxiliary-loss-free strategy for load balancing, which minimizes the performance degradation that arises from encouraging load balancing.
69
+ - We investigate a Multi-Token Prediction (MTP) objective and prove it beneficial to model performance.
70
+ It can also be used for speculative decoding for inference acceleration.
71
+
72
+ ---
73
+
74
+ **Pre-Training: Towards Ultimate Training Efficiency**
75
+
76
+ - We design an FP8 mixed precision training framework and, for the first time, validate the feasibility and effectiveness of FP8 training on an extremely large-scale model.
77
+ - Through co-design of algorithms, frameworks, and hardware, we overcome the communication bottleneck in cross-node MoE training, nearly achieving full computation-communication overlap.
78
+ This significantly enhances our training efficiency and reduces the training costs, enabling us to further scale up the model size without additional overhead.
79
+ - At an economical cost of only 2.664M H800 GPU hours, we complete the pre-training of DeepSeek-V3 on 14.8T tokens, producing the currently strongest open-source base model. The subsequent training stages after pre-training require only 0.1M GPU hours.
80
+
81
+ ---
82
+
83
+ **Post-Training: Knowledge Distillation from DeepSeek-R1**
84
+
85
+ - We introduce an innovative methodology to distill reasoning capabilities from the long-Chain-of-Thought (CoT) model, specifically from one of the DeepSeek R1 series models, into standard LLMs, particularly DeepSeek-V3. Our pipeline elegantly incorporates the verification and reflection patterns of R1 into DeepSeek-V3 and notably improves its reasoning performance. Meanwhile, we also maintain a control over the output style and length of DeepSeek-V3.
86
+
87
+ ---
88
+
89
+
90
+ ## 3. Model Downloads
91
+
92
+ <div align="center">
93
+
94
+ | **Model** | **#Total Params** | **#Activated Params** | **Context Length** | **Download** |
95
+ | :------------: | :------------: | :------------: | :------------: | :------------: |
96
+ | DeepSeek-V3-Base | 671B | 37B | 128K | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-V3-Base) |
97
+ | DeepSeek-V3 | 671B | 37B | 128K | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-V3) |
98
+
99
+ </div>
100
+
101
+ **NOTE: The total size of DeepSeek-V3 models on HuggingFace is 685B, which includes 671B of the Main Model weights and 14B of the Multi-Token Prediction (MTP) Module weights.**
102
+
103
+ To ensure optimal performance and flexibility, we have partnered with open-source communities and hardware vendors to provide multiple ways to run the model locally. For step-by-step guidance, check out Section 6: [How_to Run_Locally](#6-how-to-run-locally).
104
+
105
+ For developers looking to dive deeper, we recommend exploring [README_WEIGHTS.md](./README_WEIGHTS.md) for details on the Main Model weights and the Multi-Token Prediction (MTP) Modules. Please note that MTP support is currently under active development within the community, and we welcome your contributions and feedback.
106
+
107
+ ## 4. Evaluation Results
108
+ ### Base Model
109
+ #### Standard Benchmarks
110
+
111
+ <div align="center">
112
+
113
+
114
+ | | Benchmark (Metric) | # Shots | DeepSeek-V2 | Qwen2.5 72B | LLaMA3.1 405B | DeepSeek-V3 |
115
+ |---|-------------------|----------|--------|-------------|---------------|---------|
116
+ | | Architecture | - | MoE | Dense | Dense | MoE |
117
+ | | # Activated Params | - | 21B | 72B | 405B | 37B |
118
+ | | # Total Params | - | 236B | 72B | 405B | 671B |
119
+ | English | Pile-test (BPB) | - | 0.606 | 0.638 | **0.542** | 0.548 |
120
+ | | BBH (EM) | 3-shot | 78.8 | 79.8 | 82.9 | **87.5** |
121
+ | | MMLU (Acc.) | 5-shot | 78.4 | 85.0 | 84.4 | **87.1** |
122
+ | | MMLU-Redux (Acc.) | 5-shot | 75.6 | 83.2 | 81.3 | **86.2** |
123
+ | | MMLU-Pro (Acc.) | 5-shot | 51.4 | 58.3 | 52.8 | **64.4** |
124
+ | | DROP (F1) | 3-shot | 80.4 | 80.6 | 86.0 | **89.0** |
125
+ | | ARC-Easy (Acc.) | 25-shot | 97.6 | 98.4 | 98.4 | **98.9** |
126
+ | | ARC-Challenge (Acc.) | 25-shot | 92.2 | 94.5 | **95.3** | **95.3** |
127
+ | | HellaSwag (Acc.) | 10-shot | 87.1 | 84.8 | **89.2** | 88.9 |
128
+ | | PIQA (Acc.) | 0-shot | 83.9 | 82.6 | **85.9** | 84.7 |
129
+ | | WinoGrande (Acc.) | 5-shot | **86.3** | 82.3 | 85.2 | 84.9 |
130
+ | | RACE-Middle (Acc.) | 5-shot | 73.1 | 68.1 | **74.2** | 67.1 |
131
+ | | RACE-High (Acc.) | 5-shot | 52.6 | 50.3 | **56.8** | 51.3 |
132
+ | | TriviaQA (EM) | 5-shot | 80.0 | 71.9 | **82.7** | **82.9** |
133
+ | | NaturalQuestions (EM) | 5-shot | 38.6 | 33.2 | **41.5** | 40.0 |
134
+ | | AGIEval (Acc.) | 0-shot | 57.5 | 75.8 | 60.6 | **79.6** |
135
+ | Code | HumanEval (Pass@1) | 0-shot | 43.3 | 53.0 | 54.9 | **65.2** |
136
+ | | MBPP (Pass@1) | 3-shot | 65.0 | 72.6 | 68.4 | **75.4** |
137
+ | | LiveCodeBench-Base (Pass@1) | 3-shot | 11.6 | 12.9 | 15.5 | **19.4** |
138
+ | | CRUXEval-I (Acc.) | 2-shot | 52.5 | 59.1 | 58.5 | **67.3** |
139
+ | | CRUXEval-O (Acc.) | 2-shot | 49.8 | 59.9 | 59.9 | **69.8** |
140
+ | Math | GSM8K (EM) | 8-shot | 81.6 | 88.3 | 83.5 | **89.3** |
141
+ | | MATH (EM) | 4-shot | 43.4 | 54.4 | 49.0 | **61.6** |
142
+ | | MGSM (EM) | 8-shot | 63.6 | 76.2 | 69.9 | **79.8** |
143
+ | | CMath (EM) | 3-shot | 78.7 | 84.5 | 77.3 | **90.7** |
144
+ | Chinese | CLUEWSC (EM) | 5-shot | 82.0 | 82.5 | **83.0** | 82.7 |
145
+ | | C-Eval (Acc.) | 5-shot | 81.4 | 89.2 | 72.5 | **90.1** |
146
+ | | CMMLU (Acc.) | 5-shot | 84.0 | **89.5** | 73.7 | 88.8 |
147
+ | | CMRC (EM) | 1-shot | **77.4** | 75.8 | 76.0 | 76.3 |
148
+ | | C3 (Acc.) | 0-shot | 77.4 | 76.7 | **79.7** | 78.6 |
149
+ | | CCPM (Acc.) | 0-shot | **93.0** | 88.5 | 78.6 | 92.0 |
150
+ | Multilingual | MMMLU-non-English (Acc.) | 5-shot | 64.0 | 74.8 | 73.8 | **79.4** |
151
+
152
+ </div>
153
+
154
+ Note: Best results are shown in bold. Scores with a gap not exceeding 0.3 are considered to be at the same level. DeepSeek-V3 achieves the best performance on most benchmarks, especially on math and code tasks.
155
+ For more evaluation details, please check our paper.
156
+
157
+ #### Context Window
158
+ <p align="center">
159
+ <img width="80%" src="figures/niah.png">
160
+ </p>
161
+
162
+ Evaluation results on the ``Needle In A Haystack`` (NIAH) tests. DeepSeek-V3 performs well across all context window lengths up to **128K**.
163
+
164
+ ### Chat Model
165
+ #### Standard Benchmarks (Models larger than 67B)
166
+ <div align="center">
167
+
168
+ | | **Benchmark (Metric)** | **DeepSeek V2-0506** | **DeepSeek V2.5-0905** | **Qwen2.5 72B-Inst.** | **Llama3.1 405B-Inst.** | **Claude-3.5-Sonnet-1022** | **GPT-4o 0513** | **DeepSeek V3** |
169
+ |---|---------------------|---------------------|----------------------|---------------------|----------------------|---------------------------|----------------|----------------|
170
+ | | Architecture | MoE | MoE | Dense | Dense | - | - | MoE |
171
+ | | # Activated Params | 21B | 21B | 72B | 405B | - | - | 37B |
172
+ | | # Total Params | 236B | 236B | 72B | 405B | - | - | 671B |
173
+ | English | MMLU (EM) | 78.2 | 80.6 | 85.3 | **88.6** | **88.3** | 87.2 | **88.5** |
174
+ | | MMLU-Redux (EM) | 77.9 | 80.3 | 85.6 | 86.2 | **88.9** | 88.0 | **89.1** |
175
+ | | MMLU-Pro (EM) | 58.5 | 66.2 | 71.6 | 73.3 | **78.0** | 72.6 | 75.9 |
176
+ | | DROP (3-shot F1) | 83.0 | 87.8 | 76.7 | 88.7 | 88.3 | 83.7 | **91.6** |
177
+ | | IF-Eval (Prompt Strict) | 57.7 | 80.6 | 84.1 | 86.0 | **86.5** | 84.3 | 86.1 |
178
+ | | GPQA-Diamond (Pass@1) | 35.3 | 41.3 | 49.0 | 51.1 | **65.0** | 49.9 | 59.1 |
179
+ | | SimpleQA (Correct) | 9.0 | 10.2 | 9.1 | 17.1 | 28.4 | **38.2** | 24.9 |
180
+ | | FRAMES (Acc.) | 66.9 | 65.4 | 69.8 | 70.0 | 72.5 | **80.5** | 73.3 |
181
+ | | LongBench v2 (Acc.) | 31.6 | 35.4 | 39.4 | 36.1 | 41.0 | 48.1 | **48.7** |
182
+ | Code | HumanEval-Mul (Pass@1) | 69.3 | 77.4 | 77.3 | 77.2 | 81.7 | 80.5 | **82.6** |
183
+ | | LiveCodeBench (Pass@1-COT) | 18.8 | 29.2 | 31.1 | 28.4 | 36.3 | 33.4 | **40.5** |
184
+ | | LiveCodeBench (Pass@1) | 20.3 | 28.4 | 28.7 | 30.1 | 32.8 | 34.2 | **37.6** |
185
+ | | Codeforces (Percentile) | 17.5 | 35.6 | 24.8 | 25.3 | 20.3 | 23.6 | **51.6** |
186
+ | | SWE Verified (Resolved) | - | 22.6 | 23.8 | 24.5 | **50.8** | 38.8 | 42.0 |
187
+ | | Aider-Edit (Acc.) | 60.3 | 71.6 | 65.4 | 63.9 | **84.2** | 72.9 | 79.7 |
188
+ | | Aider-Polyglot (Acc.) | - | 18.2 | 7.6 | 5.8 | 45.3 | 16.0 | **49.6** |
189
+ | Math | AIME 2024 (Pass@1) | 4.6 | 16.7 | 23.3 | 23.3 | 16.0 | 9.3 | **39.2** |
190
+ | | MATH-500 (EM) | 56.3 | 74.7 | 80.0 | 73.8 | 78.3 | 74.6 | **90.2** |
191
+ | | CNMO 2024 (Pass@1) | 2.8 | 10.8 | 15.9 | 6.8 | 13.1 | 10.8 | **43.2** |
192
+ | Chinese | CLUEWSC (EM) | 89.9 | 90.4 | **91.4** | 84.7 | 85.4 | 87.9 | 90.9 |
193
+ | | C-Eval (EM) | 78.6 | 79.5 | 86.1 | 61.5 | 76.7 | 76.0 | **86.5** |
194
+ | | C-SimpleQA (Correct) | 48.5 | 54.1 | 48.4 | 50.4 | 51.3 | 59.3 | **64.8** |
195
+
196
+ Note: All models are evaluated in a configuration that limits the output length to 8K. Benchmarks containing fewer than 1000 samples are tested multiple times using varying temperature settings to derive robust final results. DeepSeek-V3 stands as the best-performing open-source model, and also exhibits competitive performance against frontier closed-source models.
197
+
198
+ </div>
199
+
200
+
201
+ #### Open Ended Generation Evaluation
202
+
203
+ <div align="center">
204
+
205
+
206
+
207
+ | Model | Arena-Hard | AlpacaEval 2.0 |
208
+ |-------|------------|----------------|
209
+ | DeepSeek-V2.5-0905 | 76.2 | 50.5 |
210
+ | Qwen2.5-72B-Instruct | 81.2 | 49.1 |
211
+ | LLaMA-3.1 405B | 69.3 | 40.5 |
212
+ | GPT-4o-0513 | 80.4 | 51.1 |
213
+ | Claude-Sonnet-3.5-1022 | 85.2 | 52.0 |
214
+ | DeepSeek-V3 | **85.5** | **70.0** |
215
+
216
+ Note: English open-ended conversation evaluations. For AlpacaEval 2.0, we use the length-controlled win rate as the metric.
217
+ </div>
218
+
219
+
220
+ ## 5. Chat Website & API Platform
221
+ You can chat with DeepSeek-V3 on DeepSeek's official website: [chat.deepseek.com](https://chat.deepseek.com/sign_in)
222
+
223
+ We also provide OpenAI-Compatible API at DeepSeek Platform: [platform.deepseek.com](https://platform.deepseek.com/)
224
+
225
+ ## 6. How to Run Locally
226
+
227
+ DeepSeek-V3 can be deployed locally using the following hardware and open-source community software:
228
+
229
+ 1. **DeepSeek-Infer Demo**: We provide a simple and lightweight demo for FP8 and BF16 inference.
230
+ 2. **SGLang**: Fully support the DeepSeek-V3 model in both BF16 and FP8 inference modes.
231
+ 3. **LMDeploy**: Enables efficient FP8 and BF16 inference for local and cloud deployment.
232
+ 4. **TensorRT-LLM**: Currently supports BF16 inference and INT4/8 quantization, with FP8 support coming soon.
233
+ 5. **vLLM**: Support DeekSeek-V3 model with FP8 and BF16 modes for tensor parallelism and pipeline parallelism.
234
+ 6. **AMD GPU**: Enables running the DeepSeek-V3 model on AMD GPUs via SGLang in both BF16 and FP8 modes.
235
+ 7. **Huawei Ascend NPU**: Supports running DeepSeek-V3 on Huawei Ascend devices.
236
+
237
+ Since FP8 training is natively adopted in our framework, we only provide FP8 weights. If you require BF16 weights for experimentation, you can use the provided conversion script to perform the transformation.
238
+
239
+ Here is an example of converting FP8 weights to BF16:
240
+
241
+ ```shell
242
+ cd inference
243
+ python fp8_cast_bf16.py --input-fp8-hf-path /path/to/fp8_weights --output-bf16-hf-path /path/to/bf16_weights
244
+ ```
245
+
246
+ **NOTE: Huggingface's Transformers has not been directly supported yet.**
247
+
248
+ ### 6.1 Inference with DeepSeek-Infer Demo (example only)
249
+
250
+ #### Model Weights & Demo Code Preparation
251
+
252
+ First, clone our DeepSeek-V3 GitHub repository:
253
+
254
+ ```shell
255
+ git clone https://github.com/deepseek-ai/DeepSeek-V3.git
256
+ ```
257
+
258
+ Navigate to the `inference` folder and install dependencies listed in `requirements.txt`.
259
+
260
+ ```shell
261
+ cd DeepSeek-V3/inference
262
+ pip install -r requirements.txt
263
+ ```
264
+
265
+ Download the model weights from HuggingFace, and put them into `/path/to/DeepSeek-V3` folder.
266
+
267
+ #### Model Weights Conversion
268
+
269
+ Convert HuggingFace model weights to a specific format:
270
+
271
+ ```shell
272
+ python convert.py --hf-ckpt-path /path/to/DeepSeek-V3 --save-path /path/to/DeepSeek-V3-Demo --n-experts 256 --model-parallel 16
273
+ ```
274
+
275
+ #### Run
276
+
277
+ Then you can chat with DeepSeek-V3:
278
+
279
+ ```shell
280
+ torchrun --nnodes 2 --nproc-per-node 8 generate.py --node-rank $RANK --master-addr $ADDR --ckpt-path /path/to/DeepSeek-V3-Demo --config configs/config_671B.json --interactive --temperature 0.7 --max-new-tokens 200
281
+ ```
282
+
283
+ Or batch inference on a given file:
284
+
285
+ ```shell
286
+ torchrun --nnodes 2 --nproc-per-node 8 generate.py --node-rank $RANK --master-addr $ADDR --ckpt-path /path/to/DeepSeek-V3-Demo --config configs/config_671B.json --input-file $FILE
287
+ ```
288
+
289
+ ### 6.2 Inference with SGLang (recommended)
290
+
291
+ [SGLang](https://github.com/sgl-project/sglang) currently supports MLA optimizations, FP8 (W8A8), FP8 KV Cache, and Torch Compile, delivering state-of-the-art latency and throughput performance among open-source frameworks.
292
+
293
+ Notably, [SGLang v0.4.1](https://github.com/sgl-project/sglang/releases/tag/v0.4.1) fully supports running DeepSeek-V3 on both **NVIDIA and AMD GPUs**, making it a highly versatile and robust solution.
294
+
295
+ Here are the launch instructions from the SGLang team: https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3
296
+
297
+ ### 6.3 Inference with LMDeploy (recommended)
298
+ [LMDeploy](https://github.com/InternLM/lmdeploy), a flexible and high-performance inference and serving framework tailored for large language models, now supports DeepSeek-V3. It offers both offline pipeline processing and online deployment capabilities, seamlessly integrating with PyTorch-based workflows.
299
+
300
+ For comprehensive step-by-step instructions on running DeepSeek-V3 with LMDeploy, please refer to here: https://github.com/InternLM/lmdeploy/issues/2960
301
+
302
+
303
+ ### 6.4 Inference with TRT-LLM (recommended)
304
+
305
+ [TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM) now supports the DeepSeek-V3 model, offering precision options such as BF16 and INT4/INT8 weight-only. Support for FP8 is currently in progress and will be released soon. You can access the custom branch of TRTLLM specifically for DeepSeek-V3 support through the following link to experience the new features directly: https://github.com/NVIDIA/TensorRT-LLM/tree/deepseek/examples/deepseek_v3.
306
+
307
+ ### 6.5 Inference with vLLM (recommended)
308
+
309
+ [vLLM](https://github.com/vllm-project/vllm) v0.6.6 supports DeepSeek-V3 inference for FP8 and BF16 modes on both NVIDIA and AMD GPUs. Aside from standard techniques, vLLM offers _pipeline parallelism_ allowing you to run this model on multiple machines connected by networks. For detailed guidance, please refer to the [vLLM instructions](https://docs.vllm.ai/en/latest/serving/distributed_serving.html). Please feel free to follow [the enhancement plan](https://github.com/vllm-project/vllm/issues/11539) as well.
310
+
311
+ ### 6.6 Recommended Inference Functionality with AMD GPUs
312
+
313
+ In collaboration with the AMD team, we have achieved Day-One support for AMD GPUs using SGLang, with full compatibility for both FP8 and BF16 precision. For detailed guidance, please refer to the [SGLang instructions](#63-inference-with-lmdeploy-recommended).
314
+
315
+ ### 6.7 Recommended Inference Functionality with Huawei Ascend NPUs
316
+ The [MindIE](https://www.hiascend.com/en/software/mindie) framework from the Huawei Ascend community has successfully adapted the BF16 version of DeepSeek-V3. For step-by-step guidance on Ascend NPUs, please follow the [instructions here](https://modelers.cn/models/MindIE/deepseekv3).
317
+
318
+
319
+ ## 7. License
320
+ This code repository is licensed under [the MIT License](LICENSE-CODE). The use of DeepSeek-V3 Base/Chat models is subject to [the Model License](LICENSE-MODEL). DeepSeek-V3 series (including Base and Chat) supports commercial use.
321
+
322
+ ## 8. Citation
323
+ ```
324
+ @misc{deepseekai2024deepseekv3technicalreport,
325
+ title={DeepSeek-V3 Technical Report},
326
+ author={DeepSeek-AI},
327
+ year={2024},
328
+ eprint={2412.19437},
329
+ archivePrefix={arXiv},
330
+ primaryClass={cs.CL},
331
+ url={https://arxiv.org/abs/2412.19437},
332
+ }
333
+ ```
334
+
335
+ ## 9. Contact
336
+ If you have any questions, please raise an issue or contact us at [[email protected]]([email protected]).
DeepSeek-V3-Base/README_WEIGHTS.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DeepSeek-V3 Weight File Documentation
2
+
3
+ ## New Fields in `config.json`
4
+
5
+ - **model_type**: Specifies the model type, which is updated to `deepseek_v3` in this release.
6
+ - **num_nextn_predict_layers**: Indicates the number of Multi-Token Prediction (MTP) Modules. The open-sourced V3 weights include **1 MTP Module** .
7
+ - **quantization_config**: Describes the configuration for FP8 quantization.
8
+
9
+ ---
10
+
11
+ ## Weight Structure Overview
12
+
13
+ The DeepSeek-V3 weight file consists of two main components: **Main Model Weights** and **MTP Modules**.
14
+
15
+ ### 1. Main Model Weights
16
+
17
+ - **Composition**:
18
+ - Input/output embedding layers and a complete set of 61 Transformer hidden layers.
19
+ - **Parameter Count**:
20
+ - Total parameters: **671B**
21
+ - Activation parameters: **36.6B** (including 0.9B for the output Head).
22
+
23
+ #### Structural Details
24
+
25
+ - **Embedding Layer**:
26
+ - `model.embed_tokens.weight`
27
+ - **Transformer Hidden Layers**:
28
+ - `model.layers.0` to `model.layers.60`, totaling `num_hidden_layers` layers.
29
+ - **Output Layer**:
30
+ - `model.norm.weight`
31
+ - `lm_head.weight`
32
+
33
+ ### 2. Multi-Token Prediction (MTP) Modules
34
+
35
+ - **Composition**:
36
+ - Additional MTP Modules defined by the `num_nextn_predict_layers` field. In this model, the value is set to 1.
37
+ - **Parameter Count**:
38
+ - Parameters: **11.5B unique parameters** (excluding the shared 0.9B Embedding and 0.9B output Head).
39
+ - Activation parameters: **1.5B** (including 0.9B for the output Head).
40
+
41
+ #### Structural Details
42
+
43
+ - **embed_tokens**: **Shares parameters** with the Embedding layer of the Main Model weights.
44
+ - **enorm & hnorm**: RMSNorm parameters required for speculative decoding.
45
+ - **eh_proj**: Parameters for dimensionality reduction projection on the norm results.
46
+ - **Additional Transformer Hidden Layer**:
47
+ - `model.layers.61.self_attn & mlp` (structure identical to the Main Model hidden layers).
48
+ - **shared_head**: **Shares parameters** with the output Head of the Main Model weights.
49
+
50
+ ---
51
+
52
+ ### Loading Rules
53
+
54
+ - **Main Model Weights**: Loaded via the `num_hidden_layers` parameter in `config.json`.
55
+ - **MTP Modules**: Loaded via the `num_nextn_predict_layers` parameter, with layer IDs appended immediately after the Main Model hidden layers. For example:
56
+ - If `num_hidden_layers = 61` and `num_nextn_predict_layers = 1`, the MTP Module's layer ID is `61`.
57
+
58
+ ---
59
+
60
+ ## FP8 Weight Documentation
61
+
62
+ DeepSeek-V3 natively supports FP8 weight format with 128x128 block scaling.
63
+
64
+ ### FP8 Configuration
65
+
66
+ The FP8 weight file introduces a `quantization_config` field to describe the quantization method. Below is an example configuration:
67
+
68
+ ```json
69
+ "quantization_config": {
70
+ "activation_scheme": "dynamic",
71
+ "fmt": "e4m3",
72
+ "quant_method": "fp8",
73
+ "weight_block_size": [128, 128]
74
+ }
75
+ ```
76
+
77
+ - **Quantization Format**:
78
+ - Format type: `fp8` and `e4m3` (corresponding to `torch.float8_e4m3fn`).
79
+ - Weight block size: `128x128`.
80
+ - **Activation Quantization Scheme**:
81
+ - Utilizes dynamic activation quantization (`dynamic`).
82
+
83
+ ### Dequantization Method
84
+
85
+ The FP8 weight file includes a `weight_scale_inv` field, which stores the dequantization scale for each weight block.
86
+
87
+ - **Storage Format**: `float32 Tensor`, stored alongside the weight data.
88
+ - **Dequantization Formula**:
89
+ - If the weight block is not aligned to 128, it is zero-padded to 128 before calculating the scale. After quantization, the padded portion is removed.
90
+ - The dequantization process is performed as: `(128x128 weight block) * weight_scale_inv`.
91
+
92
+ Through dequantization of the FP8 weights, runtime operations enable online quantization at a granularity of `per-token-per-128-channel`.
93
+
94
+ ---
DeepSeek-V3-Base/configuration_deepseek.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ logger = logging.get_logger(__name__)
5
+
6
+ DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
7
+ class DeepseekV3Config(PretrainedConfig):
8
+ r"""
9
+ This is the configuration class to store the configuration of a [`DeepseekV3Model`]. It is used to instantiate an DeepSeek
10
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
11
+ defaults will yield a similar configuration to that of the DeepSeek-V3.
12
+
13
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
14
+ documentation from [`PretrainedConfig`] for more information.
15
+
16
+
17
+ Args:
18
+ vocab_size (`int`, *optional*, defaults to 129280):
19
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
20
+ `inputs_ids` passed when calling [`DeepseekV3Model`]
21
+ hidden_size (`int`, *optional*, defaults to 4096):
22
+ Dimension of the hidden representations.
23
+ intermediate_size (`int`, *optional*, defaults to 11008):
24
+ Dimension of the MLP representations.
25
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
26
+ Dimension of the MoE representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer decoder.
29
+ num_nextn_predict_layers (`int`, *optional*, defaults to 1):
30
+ Number of nextn predict layers in the DeepSeekV3 Model.
31
+ num_attention_heads (`int`, *optional*, defaults to 32):
32
+ Number of attention heads for each attention layer in the Transformer decoder.
33
+ n_shared_experts (`int`, *optional*, defaults to None):
34
+ Number of shared experts, None means dense model.
35
+ n_routed_experts (`int`, *optional*, defaults to None):
36
+ Number of routed experts, None means dense model.
37
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
38
+ Scaling factor or routed experts.
39
+ topk_method (`str`, *optional*, defaults to `gready`):
40
+ Topk method used in routed gate.
41
+ n_group (`int`, *optional*, defaults to None):
42
+ Number of groups for routed experts.
43
+ topk_group (`int`, *optional*, defaults to None):
44
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
45
+ num_experts_per_tok (`int`, *optional*, defaults to None):
46
+ Number of selected experts, None means dense model.
47
+ moe_layer_freq (`int`, *optional*, defaults to 1):
48
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
49
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
50
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
51
+ \--k dense layers--/
52
+ norm_topk_prob (`bool`, *optional*, defaults to False):
53
+ Whether to normalize the weights of the routed experts.
54
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
55
+ Method of computing expert weights.
56
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
57
+ Auxiliary loss weight coefficient.
58
+ seq_aux = (`bool`, *optional*, defaults to True):
59
+ Whether to compute the auxiliary loss for each individual sample.
60
+ num_key_value_heads (`int`, *optional*):
61
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
62
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
63
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
64
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
65
+ by meanpooling all the original heads within that group. For more details checkout [this
66
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
67
+ `num_attention_heads`.
68
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
69
+ The non-linear activation function (function or string) in the decoder.
70
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
71
+ The maximum sequence length that this model might ever be used with.
72
+ initializer_range (`float`, *optional*, defaults to 0.02):
73
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
74
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
75
+ The epsilon used by the rms normalization layers.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ pad_token_id (`int`, *optional*):
80
+ Padding token id.
81
+ bos_token_id (`int`, *optional*, defaults to 1):
82
+ Beginning of stream token id.
83
+ eos_token_id (`int`, *optional*, defaults to 2):
84
+ End of stream token id.
85
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
86
+ Whether to tie weight embeddings
87
+ rope_theta (`float`, *optional*, defaults to 10000.0):
88
+ The base period of the RoPE embeddings.
89
+ rope_scaling (`Dict`, *optional*):
90
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
91
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
92
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
93
+ `max_position_embeddings` to the expected new maximum.
94
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
95
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
96
+ attention_dropout (`float`, *optional*, defaults to 0.0):
97
+ The dropout ratio for the attention probabilities.
98
+
99
+ ```python
100
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
101
+
102
+ >>> # Initializing a Deepseek-V3 style configuration
103
+ >>> configuration = DeepseekV3Config()
104
+
105
+ >>> # Accessing the model configuration
106
+ >>> configuration = model.config
107
+ ```"""
108
+
109
+ model_type = "deepseek_v3"
110
+ keys_to_ignore_at_inference = ["past_key_values"]
111
+
112
+ def __init__(
113
+ self,
114
+ vocab_size=129280,
115
+ hidden_size=7168,
116
+ intermediate_size=18432,
117
+ moe_intermediate_size = 2048,
118
+ num_hidden_layers=61,
119
+ num_nextn_predict_layers=1,
120
+ num_attention_heads=128,
121
+ num_key_value_heads=128,
122
+ n_shared_experts = 1,
123
+ n_routed_experts = 256,
124
+ ep_size = 1,
125
+ routed_scaling_factor = 2.5,
126
+ kv_lora_rank = 512,
127
+ q_lora_rank = 1536,
128
+ qk_rope_head_dim = 64,
129
+ v_head_dim = 128,
130
+ qk_nope_head_dim = 128,
131
+ topk_method = 'noaux_tc',
132
+ n_group = 8,
133
+ topk_group = 4,
134
+ num_experts_per_tok = 8,
135
+ moe_layer_freq = 1,
136
+ first_k_dense_replace = 3,
137
+ norm_topk_prob = True,
138
+ scoring_func = 'sigmoid',
139
+ hidden_act="silu",
140
+ max_position_embeddings=4096,
141
+ initializer_range=0.02,
142
+ rms_norm_eps=1e-6,
143
+ use_cache=True,
144
+ pad_token_id=None,
145
+ bos_token_id=0,
146
+ eos_token_id=1,
147
+ tie_word_embeddings=False,
148
+ rope_theta=10000.0,
149
+ rope_scaling=None,
150
+ attention_bias=False,
151
+ attention_dropout=0.0,
152
+ **kwargs,
153
+ ):
154
+ self.vocab_size = vocab_size
155
+ self.max_position_embeddings = max_position_embeddings
156
+ self.hidden_size = hidden_size
157
+ self.intermediate_size = intermediate_size
158
+ self.moe_intermediate_size = moe_intermediate_size
159
+ self.num_hidden_layers = num_hidden_layers
160
+ self.num_nextn_predict_layers = num_nextn_predict_layers
161
+ self.num_attention_heads = num_attention_heads
162
+ self.n_shared_experts = n_shared_experts
163
+ self.n_routed_experts = n_routed_experts
164
+ self.ep_size = ep_size
165
+ self.routed_scaling_factor = routed_scaling_factor
166
+ self.kv_lora_rank = kv_lora_rank
167
+ self.q_lora_rank = q_lora_rank
168
+ self.qk_rope_head_dim = qk_rope_head_dim
169
+ self.v_head_dim = v_head_dim
170
+ self.qk_nope_head_dim = qk_nope_head_dim
171
+ self.topk_method = topk_method
172
+ self.n_group = n_group
173
+ self.topk_group = topk_group
174
+ self.num_experts_per_tok = num_experts_per_tok
175
+ self.moe_layer_freq = moe_layer_freq
176
+ self.first_k_dense_replace = first_k_dense_replace
177
+ self.norm_topk_prob = norm_topk_prob
178
+ self.scoring_func = scoring_func
179
+ # for backward compatibility
180
+ if num_key_value_heads is None:
181
+ num_key_value_heads = num_attention_heads
182
+
183
+ self.num_key_value_heads = num_key_value_heads
184
+ self.hidden_act = hidden_act
185
+ self.initializer_range = initializer_range
186
+ self.rms_norm_eps = rms_norm_eps
187
+ self.use_cache = use_cache
188
+ self.rope_theta = rope_theta
189
+ self.rope_scaling = rope_scaling
190
+ self.attention_bias = attention_bias
191
+ self.attention_dropout = attention_dropout
192
+
193
+ super().__init__(
194
+ pad_token_id=pad_token_id,
195
+ bos_token_id=bos_token_id,
196
+ eos_token_id=eos_token_id,
197
+ tie_word_embeddings=tie_word_embeddings,
198
+ **kwargs,
199
+ )
DeepSeek-V3-Base/figures/benchmark.png ADDED

Git LFS Details

  • SHA256: f3d639a39f1e264ace9ba5974e3a51b51de8c69419fa936457b1c19e0e1898e9
  • Pointer size: 131 Bytes
  • Size of remote file: 184 kB
DeepSeek-V3-Base/inference/configs/config_16B.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vocab_size": 102400,
3
+ "dim": 2048,
4
+ "inter_dim": 10944,
5
+ "moe_inter_dim": 1408,
6
+ "n_layers": 27,
7
+ "n_dense_layers": 1,
8
+ "n_heads": 16,
9
+ "n_routed_experts": 64,
10
+ "n_shared_experts": 2,
11
+ "n_activated_experts": 6,
12
+ "route_scale": 1.0,
13
+ "q_lora_rank": 0,
14
+ "kv_lora_rank": 512,
15
+ "qk_nope_head_dim": 128,
16
+ "qk_rope_head_dim": 64,
17
+ "v_head_dim": 128,
18
+ "mscale": 0.707
19
+ }
DeepSeek-V3-Base/inference/configs/config_236B.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vocab_size": 102400,
3
+ "dim": 5120,
4
+ "inter_dim": 12288,
5
+ "moe_inter_dim": 1536,
6
+ "n_layers": 60,
7
+ "n_dense_layers": 1,
8
+ "n_heads": 128,
9
+ "n_routed_experts": 160,
10
+ "n_shared_experts": 2,
11
+ "n_activated_experts": 6,
12
+ "n_expert_groups": 8,
13
+ "n_limited_groups": 3,
14
+ "route_scale": 16.0,
15
+ "q_lora_rank": 1536,
16
+ "kv_lora_rank": 512,
17
+ "qk_nope_head_dim": 128,
18
+ "qk_rope_head_dim": 64,
19
+ "v_head_dim": 128
20
+ }
DeepSeek-V3-Base/inference/configs/config_671B.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vocab_size": 129280,
3
+ "dim": 7168,
4
+ "inter_dim": 18432,
5
+ "moe_inter_dim": 2048,
6
+ "n_layers": 61,
7
+ "n_dense_layers": 3,
8
+ "n_heads": 128,
9
+ "n_routed_experts": 256,
10
+ "n_shared_experts": 1,
11
+ "n_activated_experts": 8,
12
+ "n_expert_groups": 8,
13
+ "n_limited_groups": 4,
14
+ "route_scale": 2.5,
15
+ "score_func": "sigmoid",
16
+ "q_lora_rank": 1536,
17
+ "kv_lora_rank": 512,
18
+ "qk_nope_head_dim": 128,
19
+ "qk_rope_head_dim": 64,
20
+ "v_head_dim": 128,
21
+ "dtype": "fp8"
22
+ }
DeepSeek-V3-Base/inference/convert.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from argparse import ArgumentParser
4
+ from glob import glob
5
+ from tqdm import tqdm, trange
6
+
7
+ import torch
8
+ from safetensors.torch import safe_open, save_file
9
+
10
+
11
+ mapping = {
12
+ "embed_tokens": ("embed", 0),
13
+ "input_layernorm": ("attn_norm", None),
14
+ "post_attention_layernorm": ("ffn_norm", None),
15
+ "q_proj": ("wq", 0),
16
+ "q_a_proj": ("wq_a", None),
17
+ "q_a_layernorm": ("q_norm", None),
18
+ "q_b_proj": ("wq_b", 0),
19
+ "kv_a_proj_with_mqa": ("wkv_a", None),
20
+ "kv_a_layernorm": ("kv_norm", None),
21
+ "kv_b_proj": ("wkv_b", 0),
22
+ "o_proj": ("wo", 1),
23
+ "gate": ("gate", None),
24
+ "gate_proj": ("w1", 0),
25
+ "down_proj": ("w2", 1),
26
+ "up_proj": ("w3", 0),
27
+ "norm": ("norm", None),
28
+ "lm_head": ("head", 0),
29
+ "scale": ("scale", None),
30
+ }
31
+
32
+
33
+ def main(hf_ckpt_path, save_path, n_experts, mp):
34
+ torch.set_num_threads(8)
35
+ n_local_experts = n_experts // mp
36
+ state_dicts = [{} for _ in range(mp)]
37
+
38
+ for file_path in tqdm(glob(os.path.join(hf_ckpt_path, "*.safetensors"))):
39
+ with safe_open(file_path, framework="pt", device="cpu") as f:
40
+ for name in f.keys():
41
+ if "model.layers.61" in name:
42
+ continue
43
+ param: torch.Tensor = f.get_tensor(name)
44
+ if name.startswith("model."):
45
+ name = name[len("model."):]
46
+ name = name.replace("self_attn", "attn")
47
+ name = name.replace("mlp", "ffn")
48
+ name = name.replace("weight_scale_inv", "scale")
49
+ name = name.replace("e_score_correction_bias", "bias")
50
+ key = name.split(".")[-2]
51
+ assert key in mapping
52
+ new_key, dim = mapping[key]
53
+ name = name.replace(key, new_key)
54
+ for i in range(mp):
55
+ new_param = param
56
+ if "experts" in name and "shared_experts" not in name:
57
+ idx = int(name.split(".")[-3])
58
+ if idx < i * n_local_experts or idx >= (i + 1) * n_local_experts:
59
+ continue
60
+ elif dim is not None:
61
+ assert param.size(dim) % mp == 0
62
+ shard_size = param.size(dim) // mp
63
+ new_param = param.narrow(dim, i * shard_size, shard_size).contiguous()
64
+ state_dicts[i][name] = new_param
65
+
66
+ os.makedirs(save_path, exist_ok=True)
67
+
68
+ for i in trange(mp):
69
+ save_file(state_dicts[i], os.path.join(save_path, f"model{i}-mp{mp}.safetensors"))
70
+
71
+ for file_path in glob(os.path.join(hf_ckpt_path, "*token*")):
72
+ new_file_path = os.path.join(save_path, os.path.basename(file_path))
73
+ shutil.copyfile(file_path, new_file_path)
74
+
75
+
76
+ if __name__ == "__main__":
77
+ parser = ArgumentParser()
78
+ parser.add_argument("--hf-ckpt-path", type=str, required=True)
79
+ parser.add_argument("--save-path", type=str, required=True)
80
+ parser.add_argument("--n-experts", type=int, required=True)
81
+ parser.add_argument("--model-parallel", type=int, default=1)
82
+ args = parser.parse_args()
83
+ assert args.n_experts % args.model_parallel == 0
84
+ main(args.hf_ckpt_path, args.save_path, args.n_experts, args.model_parallel)
DeepSeek-V3-Base/inference/fp8_cast_bf16.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from argparse import ArgumentParser
4
+ from glob import glob
5
+ from tqdm import tqdm
6
+
7
+ import torch
8
+ from safetensors.torch import load_file, save_file
9
+
10
+ from kernel import weight_dequant
11
+
12
+ def main(fp8_path, bf16_path):
13
+ torch.set_default_dtype(torch.bfloat16)
14
+ os.makedirs(bf16_path, exist_ok=True)
15
+ model_index_file = os.path.join(fp8_path, "model.safetensors.index.json")
16
+ with open(model_index_file, "r") as f:
17
+ model_index = json.load(f)
18
+ weight_map = model_index["weight_map"]
19
+
20
+ # Cache for loaded safetensor files
21
+ loaded_files = {}
22
+ fp8_weight_names = []
23
+
24
+ # Helper function to get tensor from the correct file
25
+ def get_tensor(tensor_name):
26
+ file_name = weight_map[tensor_name]
27
+ if file_name not in loaded_files:
28
+ file_path = os.path.join(fp8_path, file_name)
29
+ loaded_files[file_name] = load_file(file_path, device="cuda")
30
+ return loaded_files[file_name][tensor_name]
31
+
32
+ safetensor_files = list(glob(os.path.join(fp8_path, "*.safetensors")))
33
+ safetensor_files.sort()
34
+ for safetensor_file in tqdm(safetensor_files):
35
+ file_name = os.path.basename(safetensor_file)
36
+ current_state_dict = load_file(safetensor_file, device="cuda")
37
+ loaded_files[file_name] = current_state_dict
38
+
39
+ new_state_dict = {}
40
+ for weight_name, weight in current_state_dict.items():
41
+ if weight_name.endswith("_scale_inv"):
42
+ continue
43
+ elif weight.element_size() == 1: # FP8 weight
44
+ scale_inv_name = f"{weight_name}_scale_inv"
45
+ try:
46
+ # Get scale_inv from the correct file
47
+ scale_inv = get_tensor(scale_inv_name)
48
+ fp8_weight_names.append(weight_name)
49
+ new_state_dict[weight_name] = weight_dequant(weight, scale_inv)
50
+ except KeyError:
51
+ print(f"Warning: Missing scale_inv tensor for {weight_name}, skipping conversion")
52
+ new_state_dict[weight_name] = weight
53
+ else:
54
+ new_state_dict[weight_name] = weight
55
+
56
+ new_safetensor_file = os.path.join(bf16_path, file_name)
57
+ save_file(new_state_dict, new_safetensor_file)
58
+
59
+ # Memory management: keep only the 2 most recently used files
60
+ if len(loaded_files) > 2:
61
+ oldest_file = next(iter(loaded_files))
62
+ del loaded_files[oldest_file]
63
+ torch.cuda.empty_cache()
64
+
65
+ # Update model index
66
+ new_model_index_file = os.path.join(bf16_path, "model.safetensors.index.json")
67
+ for weight_name in fp8_weight_names:
68
+ scale_inv_name = f"{weight_name}_scale_inv"
69
+ if scale_inv_name in weight_map:
70
+ weight_map.pop(scale_inv_name)
71
+ with open(new_model_index_file, "w") as f:
72
+ json.dump({"metadata": {}, "weight_map": weight_map}, f, indent=2)
73
+
74
+
75
+ if __name__ == "__main__":
76
+ parser = ArgumentParser()
77
+ parser.add_argument("--input-fp8-hf-path", type=str, required=True)
78
+ parser.add_argument("--output-bf16-hf-path", type=str, required=True)
79
+ args = parser.parse_args()
80
+ main(args.input_fp8_hf_path, args.output_bf16_hf_path)
81
+
DeepSeek-V3-Base/inference/generate.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from argparse import ArgumentParser
4
+ from typing import List
5
+
6
+ import torch
7
+ import torch.distributed as dist
8
+ from transformers import AutoTokenizer
9
+ from safetensors.torch import load_model
10
+
11
+ from model import Transformer, ModelArgs
12
+
13
+
14
+ def sample(logits, temperature: float = 1.0):
15
+ logits = logits / max(temperature, 1e-5)
16
+ probs = torch.softmax(logits, dim=-1)
17
+ return probs.div_(torch.empty_like(probs).exponential_(1)).argmax(dim=-1)
18
+
19
+
20
+ @torch.inference_mode()
21
+ def generate(
22
+ model: Transformer,
23
+ prompt_tokens: List[List[int]],
24
+ max_new_tokens: int,
25
+ eos_id: int,
26
+ temperature: float = 1.0
27
+ ) -> List[List[int]]:
28
+ prompt_lens = [len(t) for t in prompt_tokens]
29
+ assert max(prompt_lens) <= model.max_seq_len
30
+ total_len = min(model.max_seq_len, max_new_tokens + max(prompt_lens))
31
+ tokens = torch.full((len(prompt_tokens), total_len), -1, dtype=torch.long, device="cuda")
32
+ for i, t in enumerate(prompt_tokens):
33
+ tokens[i, :len(t)] = torch.tensor(t, dtype=torch.long, device="cuda")
34
+ prev_pos = 0
35
+ finished = torch.tensor([False] * len(prompt_tokens), device="cuda")
36
+ prompt_mask = tokens != -1
37
+ for cur_pos in range(min(prompt_lens), total_len):
38
+ logits = model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
39
+ if temperature > 0:
40
+ next_token = sample(logits, temperature)
41
+ else:
42
+ next_token = logits.argmax(dim=-1)
43
+ next_token = torch.where(prompt_mask[:, cur_pos], tokens[:, cur_pos], next_token)
44
+ tokens[:, cur_pos] = next_token
45
+ finished |= torch.logical_and(~prompt_mask[:, cur_pos], next_token == eos_id)
46
+ prev_pos = cur_pos
47
+ if finished.all():
48
+ break
49
+ completion_tokens = []
50
+ for i, toks in enumerate(tokens.tolist()):
51
+ toks = toks[prompt_lens[i]:prompt_lens[i]+max_new_tokens]
52
+ if eos_id in toks:
53
+ toks = toks[:toks.index(eos_id)]
54
+ completion_tokens.append(toks)
55
+ return completion_tokens
56
+
57
+
58
+ def main(
59
+ ckpt_path: str,
60
+ config: str,
61
+ input_file: str = "",
62
+ interactive: bool = True,
63
+ max_new_tokens: int = 100,
64
+ temperature: float = 1.0,
65
+ ) -> None:
66
+ world_size = int(os.getenv("WORLD_SIZE", "1"))
67
+ rank = int(os.getenv("RANK", "0"))
68
+ local_rank = int(os.getenv("LOCAL_RANK", "0"))
69
+ if world_size > 1:
70
+ dist.init_process_group("nccl")
71
+ global print
72
+ if rank != 0:
73
+ print = lambda *_, **__: None
74
+ torch.cuda.set_device(local_rank)
75
+ torch.set_default_dtype(torch.bfloat16)
76
+ torch.set_num_threads(8)
77
+ torch.manual_seed(965)
78
+ with open(config) as f:
79
+ args = ModelArgs(**json.load(f))
80
+ print(args)
81
+ with torch.device("cuda"):
82
+ model = Transformer(args)
83
+ tokenizer = AutoTokenizer.from_pretrained(ckpt_path)
84
+ tokenizer.decode(generate(model, [tokenizer.encode("DeepSeek")], 2, -1, 1.)[0])
85
+ load_model(model, os.path.join(ckpt_path, f"model{rank}-mp{world_size}.safetensors"))
86
+
87
+ if interactive:
88
+ messages = []
89
+ while True:
90
+ if world_size == 1:
91
+ prompt = input(">>> ")
92
+ elif rank == 0:
93
+ prompt = input(">>> ")
94
+ objects = [prompt]
95
+ dist.broadcast_object_list(objects, 0)
96
+ else:
97
+ objects = [None]
98
+ dist.broadcast_object_list(objects, 0)
99
+ prompt = objects[0]
100
+ if prompt == "/exit":
101
+ break
102
+ elif prompt == "/clear":
103
+ messages.clear()
104
+ continue
105
+ messages.append({"role": "user", "content": prompt})
106
+ prompt_tokens = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
107
+ completion_tokens = generate(model, [prompt_tokens], max_new_tokens, tokenizer.eos_token_id, temperature)
108
+ completion = tokenizer.decode(completion_tokens[0], skip_special_tokens=True)
109
+ print(completion)
110
+ messages.append({"role": "assistant", "content": completion})
111
+ else:
112
+ with open(input_file) as f:
113
+ prompts = [line.strip() for line in f.readlines()]
114
+ assert len(prompts) <= args.max_batch_size
115
+ prompt_tokens = [tokenizer.apply_chat_template([{"role": "user", "content": prompt}], add_generation_prompt=True) for prompt in prompts]
116
+ completion_tokens = generate(model, prompt_tokens, max_new_tokens, tokenizer.eos_token_id, temperature)
117
+ completions = tokenizer.batch_decode(completion_tokens, skip_special_tokens=True)
118
+ for prompt, completion in zip(prompts, completions):
119
+ print("Prompt:", prompt)
120
+ print("Completion:", completion)
121
+ print()
122
+
123
+ if world_size > 1:
124
+ dist.destroy_process_group()
125
+
126
+
127
+ if __name__ == "__main__":
128
+ parser = ArgumentParser()
129
+ parser.add_argument("--ckpt-path", type=str, required=True)
130
+ parser.add_argument("--config", type=str, required=True)
131
+ parser.add_argument("--input-file", type=str, default="")
132
+ parser.add_argument("--interactive", action="store_true")
133
+ parser.add_argument("--max-new-tokens", type=int, default=200)
134
+ parser.add_argument("--temperature", type=float, default=0.2)
135
+ args = parser.parse_args()
136
+ assert args.input_file or args.interactive
137
+ main(args.ckpt_path, args.config, args.input_file, args.interactive, args.max_new_tokens, args.temperature)
DeepSeek-V3-Base/inference/kernel.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+
3
+ import torch
4
+ import triton
5
+ import triton.language as tl
6
+ from triton import Config
7
+
8
+
9
+ @triton.jit
10
+ def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr):
11
+ pid = tl.program_id(axis=0)
12
+ offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
13
+ x = tl.load(x_ptr + offs).to(tl.float32)
14
+ s = tl.max(tl.abs(x)) / 448.
15
+ y = x / s
16
+ y = y.to(y_ptr.dtype.element_ty)
17
+ tl.store(y_ptr + offs, y)
18
+ tl.store(s_ptr + pid, s)
19
+
20
+
21
+ def act_quant(x: torch.Tensor, block_size: int = 128) -> Tuple[torch.Tensor, torch.Tensor]:
22
+ assert x.is_contiguous()
23
+ assert x.size(-1) % block_size == 0
24
+ y = torch.empty_like(x, dtype=torch.float8_e4m3fn)
25
+ s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
26
+ grid = lambda meta: (triton.cdiv(x.numel(), meta['BLOCK_SIZE']), )
27
+ act_quant_kernel[grid](x, y, s, BLOCK_SIZE=block_size)
28
+ return y, s
29
+
30
+
31
+ @triton.jit
32
+ def weight_dequant_kernel(x_ptr, s_ptr, y_ptr, M, N, BLOCK_SIZE: tl.constexpr):
33
+ pid_m = tl.program_id(axis=0)
34
+ pid_n = tl.program_id(axis=1)
35
+ n = tl.cdiv(N, BLOCK_SIZE)
36
+ offs_m = pid_m * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
37
+ offs_n = pid_n * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
38
+ offs = offs_m[:, None] * N + offs_n[None, :]
39
+ mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)
40
+ x = tl.load(x_ptr + offs, mask=mask).to(tl.float32)
41
+ s = tl.load(s_ptr + pid_m * n + pid_n)
42
+ y = x * s
43
+ tl.store(y_ptr + offs, y, mask=mask)
44
+
45
+
46
+ def weight_dequant(x: torch.Tensor, s: torch.Tensor, block_size: int = 128) -> torch.Tensor:
47
+ assert x.is_contiguous() and s.is_contiguous()
48
+ assert x.dim() == 2 and s.dim() == 2
49
+ M, N = x.size()
50
+ y = torch.empty_like(x, dtype=torch.get_default_dtype())
51
+ grid = lambda meta: (triton.cdiv(M, meta['BLOCK_SIZE']), triton.cdiv(N, meta['BLOCK_SIZE']))
52
+ weight_dequant_kernel[grid](x, s, y, M, N, BLOCK_SIZE=block_size)
53
+ return y
54
+
55
+
56
+ fp8_gemm_configs = [
57
+ Config({'BLOCK_SIZE_M': block_m, 'BLOCK_SIZE_N': block_n, 'BLOCK_SIZE_K': 128}, num_stages=num_stages, num_warps=8)
58
+ for block_m in [16, 32, 64] for block_n in [32, 64, 128] for num_stages in [3, 4, 5, 6]
59
+ ]
60
+
61
+ @triton.autotune(configs=fp8_gemm_configs, key=['N', 'K'])
62
+ @triton.jit
63
+ def fp8_gemm_kernel(a_ptr, b_ptr, c_ptr,
64
+ a_s_ptr, b_s_ptr,
65
+ M, N: tl.constexpr, K: tl.constexpr,
66
+ BLOCK_SIZE_M: tl.constexpr,
67
+ BLOCK_SIZE_N: tl.constexpr,
68
+ BLOCK_SIZE_K: tl.constexpr):
69
+ pid_m = tl.program_id(axis=0)
70
+ pid_n = tl.program_id(axis=1)
71
+ k = tl.cdiv(K, BLOCK_SIZE_K)
72
+ offs_m = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
73
+ offs_n = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
74
+ offs_k = tl.arange(0, BLOCK_SIZE_K)
75
+ a_ptrs = a_ptr + offs_m[:, None] * K + offs_k[None, :]
76
+ b_ptrs = b_ptr + offs_n[None, :] * K + offs_k[:, None]
77
+ a_s_ptrs = a_s_ptr + offs_m * k
78
+ b_s_ptrs = b_s_ptr + (offs_n // BLOCK_SIZE_K) * k
79
+
80
+ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
81
+ for i in range(k):
82
+ a = tl.load(a_ptrs, mask=offs_k[None, :] < K - i * BLOCK_SIZE_K, other=0.0)
83
+ b = tl.load(b_ptrs, mask=offs_k[:, None] < K - i * BLOCK_SIZE_K, other=0.0)
84
+ a_s = tl.load(a_s_ptrs)
85
+ b_s = tl.load(b_s_ptrs)
86
+ accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
87
+ a_ptrs += BLOCK_SIZE_K
88
+ b_ptrs += BLOCK_SIZE_K
89
+ a_s_ptrs += 1
90
+ b_s_ptrs += 1
91
+ c = accumulator.to(c_ptr.dtype.element_ty)
92
+ offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
93
+ offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
94
+ c_ptrs = c_ptr + offs_m[:, None] * N + offs_n[None, :]
95
+ mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)
96
+ tl.store(c_ptrs, c, mask=mask)
97
+
98
+
99
+ def fp8_gemm(a: torch.Tensor, a_s: torch.Tensor, b: torch.Tensor, b_s: torch.Tensor):
100
+ assert a.is_contiguous() and b.is_contiguous()
101
+ assert a_s.is_contiguous() and b_s.is_contiguous()
102
+ K = a.size(-1)
103
+ M = a.numel() // K
104
+ N = b.size(0)
105
+ c = a.new_empty(*a.size()[:-1], N, dtype=torch.get_default_dtype())
106
+ grid = lambda META: (triton.cdiv(M, META['BLOCK_SIZE_M']), triton.cdiv(N, META['BLOCK_SIZE_N']))
107
+ fp8_gemm_kernel[grid](a, b, c, a_s, b_s, M, N, K)
108
+ return c
DeepSeek-V3-Base/inference/model.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Tuple, Optional, Literal
4
+
5
+ import torch
6
+ from torch import nn
7
+ import torch.nn.functional as F
8
+ import torch.distributed as dist
9
+
10
+ from kernel import act_quant, weight_dequant, fp8_gemm
11
+
12
+
13
+ world_size = 1
14
+ rank = 0
15
+ block_size = 128
16
+ gemm_impl: Literal["bf16", "fp8"] = "bf16"
17
+ attn_impl: Literal["naive", "absorb"] = "absorb"
18
+
19
+ @dataclass
20
+ class ModelArgs:
21
+ max_batch_size: int = 8
22
+ max_seq_len: int = 4096 * 4
23
+ dtype: Literal["bf16", "fp8"] = "bf16"
24
+ vocab_size: int = 102400
25
+ dim: int = 2048
26
+ inter_dim: int = 10944
27
+ moe_inter_dim: int = 1408
28
+ n_layers: int = 27
29
+ n_dense_layers: int = 1
30
+ n_heads: int = 16
31
+ # moe
32
+ n_routed_experts: int = 64
33
+ n_shared_experts: int = 2
34
+ n_activated_experts: int = 6
35
+ n_expert_groups: int = 1
36
+ n_limited_groups: int = 1
37
+ score_func: Literal["softmax", "sigmoid"] = "softmax"
38
+ route_scale: float = 1.
39
+ # mla
40
+ q_lora_rank: int = 0
41
+ kv_lora_rank: int = 512
42
+ qk_nope_head_dim: int = 128
43
+ qk_rope_head_dim: int = 64
44
+ v_head_dim: int = 128
45
+ # yarn
46
+ original_seq_len: int = 4096
47
+ rope_theta: float = 10000.0
48
+ rope_factor: float = 40
49
+ beta_fast: int = 32
50
+ beta_slow: int = 1
51
+ mscale: float = 1.
52
+
53
+
54
+ class ParallelEmbedding(nn.Module):
55
+ def __init__(self, vocab_size: int, dim: int):
56
+ super().__init__()
57
+ self.vocab_size = vocab_size
58
+ self.dim = dim
59
+ assert vocab_size % world_size == 0
60
+ self.part_vocab_size = (vocab_size // world_size)
61
+ self.vocab_start_idx = rank * self.part_vocab_size
62
+ self.vocab_end_idx = self.vocab_start_idx + self.part_vocab_size
63
+ self.weight = nn.Parameter(torch.empty(self.part_vocab_size, self.dim))
64
+
65
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
66
+ if world_size > 1:
67
+ mask = (x < self.vocab_start_idx) | (x >= self.vocab_end_idx)
68
+ x = x - self.vocab_start_idx
69
+ x[mask] = 0
70
+ y = F.embedding(x, self.weight)
71
+ if world_size > 1:
72
+ y[mask] = 0
73
+ dist.all_reduce(y)
74
+ return y
75
+
76
+
77
+ def linear(x: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor] = None) -> torch.Tensor:
78
+ if weight.element_size() > 1:
79
+ return F.linear(x, weight, bias)
80
+ elif gemm_impl == "bf16":
81
+ weight = weight_dequant(weight, weight.scale)
82
+ return F.linear(x, weight, bias)
83
+ else:
84
+ x, scale = act_quant(x, block_size)
85
+ y = fp8_gemm(x, scale, weight, weight.scale)
86
+ if bias is not None:
87
+ y += bias
88
+ return y
89
+
90
+
91
+ class Linear(nn.Module):
92
+ dtype = torch.bfloat16
93
+
94
+ def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None):
95
+ super().__init__()
96
+ self.in_features = in_features
97
+ self.out_features = out_features
98
+ self.weight = nn.Parameter(torch.empty(out_features, in_features, dtype=dtype or Linear.dtype))
99
+ if self.weight.element_size() == 1:
100
+ scale_out_features = (out_features + block_size - 1) // block_size
101
+ scale_in_features = (in_features + block_size - 1) // block_size
102
+ self.weight.scale = self.scale = nn.Parameter(torch.empty(scale_out_features, scale_in_features, dtype=torch.float32))
103
+ else:
104
+ self.register_parameter("scale", None)
105
+ if bias:
106
+ self.bias = nn.Parameter(torch.empty(self.part_out_features))
107
+ else:
108
+ self.register_parameter("bias", None)
109
+
110
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
111
+ return linear(x, self.weight, self.bias)
112
+
113
+
114
+ class ColumnParallelLinear(Linear):
115
+ def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None):
116
+ assert out_features % world_size == 0
117
+ self.part_out_features = out_features // world_size
118
+ super().__init__(in_features, self.part_out_features, bias, dtype)
119
+
120
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
121
+ y = linear(x, self.weight, self.bias)
122
+ return y
123
+
124
+
125
+ class RowParallelLinear(Linear):
126
+ def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None):
127
+ assert in_features % world_size == 0
128
+ self.part_in_features = in_features // world_size
129
+ super().__init__(self.part_in_features, out_features, bias, dtype)
130
+
131
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
132
+ y = linear(x, self.weight)
133
+ if world_size > 1:
134
+ dist.all_reduce(y)
135
+ if self.bias is not None:
136
+ y += self.bias
137
+ return y
138
+
139
+
140
+ class RMSNorm(nn.Module):
141
+ def __init__(self, dim: int, eps: float = 1e-6):
142
+ super().__init__()
143
+ self.eps = eps
144
+ self.weight = nn.Parameter(torch.ones(dim))
145
+
146
+ def forward(self, x: torch.Tensor):
147
+ x = x.float()
148
+ y = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
149
+ return y.type_as(self.weight) * self.weight
150
+
151
+
152
+ def precompute_freqs_cis(args: ModelArgs) -> torch.Tensor:
153
+ dim = args.qk_rope_head_dim
154
+ seqlen = args.max_seq_len
155
+ beta_fast = args.beta_fast
156
+ beta_slow = args.beta_slow
157
+ base = args.rope_theta
158
+ factor = args.rope_factor
159
+
160
+ def find_correction_dim(num_rotations, dim, base, max_seq_len):
161
+ return dim * math.log(max_seq_len / (num_rotations * 2 * math.pi)) / (2 * math.log(base))
162
+
163
+ def find_correction_range(low_rot, high_rot, dim, base, max_seq_len):
164
+ low = math.floor(find_correction_dim(low_rot, dim, base, max_seq_len))
165
+ high = math.ceil(find_correction_dim(high_rot, dim, base, max_seq_len))
166
+ return max(low, 0), min(high, dim-1)
167
+
168
+ def linear_ramp_factor(min, max, dim):
169
+ if min == max:
170
+ max += 0.001
171
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
172
+ ramp_func = torch.clamp(linear_func, 0, 1)
173
+ return ramp_func
174
+
175
+ freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
176
+ if seqlen > args.original_seq_len:
177
+ low, high = find_correction_range(beta_fast, beta_slow, dim, base, args.original_seq_len)
178
+ smooth = 1 - linear_ramp_factor(low, high, dim // 2)
179
+ freqs = freqs / factor * (1 - smooth) + freqs * smooth
180
+
181
+ t = torch.arange(seqlen)
182
+ freqs = torch.outer(t, freqs)
183
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
184
+ return freqs_cis
185
+
186
+
187
+ def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
188
+ dtype = x.dtype
189
+ x = torch.view_as_complex(x.float().view(*x.shape[:-1], -1, 2))
190
+ freqs_cis = freqs_cis.view(1, x.size(1), 1, x.size(-1))
191
+ y = torch.view_as_real(x * freqs_cis).flatten(3)
192
+ return y.to(dtype)
193
+
194
+
195
+ class MLA(nn.Module):
196
+ def __init__(self, args: ModelArgs):
197
+ super().__init__()
198
+ self.dim = args.dim
199
+ self.n_heads = args.n_heads
200
+ self.n_local_heads = args.n_heads // world_size
201
+ self.q_lora_rank = args.q_lora_rank
202
+ self.kv_lora_rank = args.kv_lora_rank
203
+ self.qk_nope_head_dim = args.qk_nope_head_dim
204
+ self.qk_rope_head_dim = args.qk_rope_head_dim
205
+ self.qk_head_dim = args.qk_nope_head_dim + args.qk_rope_head_dim
206
+ self.v_head_dim = args.v_head_dim
207
+
208
+ if self.q_lora_rank == 0:
209
+ self.wq = ColumnParallelLinear(self.dim, self.n_heads * self.qk_head_dim)
210
+ else:
211
+ self.wq_a = Linear(self.dim, self.q_lora_rank)
212
+ self.q_norm = RMSNorm(self.q_lora_rank)
213
+ self.wq_b = ColumnParallelLinear(self.q_lora_rank, self.n_heads * self.qk_head_dim)
214
+ self.wkv_a = Linear(self.dim, self.kv_lora_rank + self.qk_rope_head_dim)
215
+ self.kv_norm = RMSNorm(self.kv_lora_rank)
216
+ self.wkv_b = ColumnParallelLinear(self.kv_lora_rank, self.n_heads * (self.qk_nope_head_dim + self.v_head_dim))
217
+ self.wo = RowParallelLinear(self.n_heads * self.v_head_dim, self.dim)
218
+ self.softmax_scale = self.qk_head_dim ** -0.5
219
+ if args.max_seq_len > args.original_seq_len:
220
+ mscale = 0.1 * args.mscale * math.log(args.rope_factor) + 1.0
221
+ self.softmax_scale = self.softmax_scale * mscale * mscale
222
+
223
+ if attn_impl == "naive":
224
+ self.register_buffer("k_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.n_local_heads, self.qk_head_dim), persistent=False)
225
+ self.register_buffer("v_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.n_local_heads, self.v_head_dim), persistent=False)
226
+ else:
227
+ self.register_buffer("kv_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.kv_lora_rank), persistent=False)
228
+ self.register_buffer("pe_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.qk_rope_head_dim), persistent=False)
229
+
230
+ def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]):
231
+ bsz, seqlen, _ = x.size()
232
+ end_pos = start_pos + seqlen
233
+ if self.q_lora_rank == 0:
234
+ q = self.wq(x)
235
+ else:
236
+ q = self.wq_b(self.q_norm(self.wq_a(x)))
237
+ q = q.view(bsz, seqlen, self.n_local_heads, self.qk_head_dim)
238
+ q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
239
+ q_pe = apply_rotary_emb(q_pe, freqs_cis)
240
+ kv = self.wkv_a(x)
241
+ kv, k_pe = torch.split(kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
242
+ k_pe = apply_rotary_emb(k_pe.unsqueeze(2), freqs_cis)
243
+ if attn_impl == "naive":
244
+ q = torch.cat([q_nope, q_pe], dim=-1)
245
+ kv = self.wkv_b(self.kv_norm(kv))
246
+ kv = kv.view(bsz, seqlen, self.n_local_heads, self.qk_nope_head_dim + self.v_head_dim)
247
+ k_nope, v = torch.split(kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
248
+ k = torch.cat([k_nope, k_pe.expand(-1, -1, self.n_local_heads, -1)], dim=-1)
249
+ self.k_cache[:bsz, start_pos:end_pos] = k
250
+ self.v_cache[:bsz, start_pos:end_pos] = v
251
+ scores = torch.einsum("bshd,bthd->bsht", q, self.k_cache[:bsz, :end_pos]) * self.softmax_scale
252
+ else:
253
+ wkv_b = self.wkv_b.weight if self.wkv_b.scale is None else weight_dequant(self.wkv_b.weight, self.wkv_b.scale, block_size)
254
+ wkv_b = wkv_b.view(self.n_local_heads, -1, self.kv_lora_rank)
255
+ q_nope = torch.einsum("bshd,hdc->bshc", q_nope, wkv_b[:, :self.qk_nope_head_dim])
256
+ self.kv_cache[:bsz, start_pos:end_pos] = self.kv_norm(kv)
257
+ self.pe_cache[:bsz, start_pos:end_pos] = k_pe.squeeze(2)
258
+ scores = (torch.einsum("bshc,btc->bsht", q_nope, self.kv_cache[:bsz, :end_pos]) +
259
+ torch.einsum("bshr,btr->bsht", q_pe, self.pe_cache[:bsz, :end_pos])) * self.softmax_scale
260
+ if mask is not None:
261
+ scores += mask.unsqueeze(1)
262
+ scores = scores.softmax(dim=-1, dtype=torch.float32).type_as(x)
263
+ if attn_impl == "naive":
264
+ x = torch.einsum("bsht,bthd->bshd", scores, self.v_cache[:bsz, :end_pos])
265
+ else:
266
+ x = torch.einsum("bsht,btc->bshc", scores, self.kv_cache[:bsz, :end_pos])
267
+ x = torch.einsum("bshc,hdc->bshd", x, wkv_b[:, -self.v_head_dim:])
268
+ x = self.wo(x.flatten(2))
269
+ return x
270
+
271
+
272
+ class MLP(nn.Module):
273
+ def __init__(self, dim: int, inter_dim: int):
274
+ super().__init__()
275
+ self.w1 = ColumnParallelLinear(dim, inter_dim)
276
+ self.w2 = RowParallelLinear(inter_dim, dim)
277
+ self.w3 = ColumnParallelLinear(dim, inter_dim)
278
+
279
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
280
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
281
+
282
+
283
+ class Gate(nn.Module):
284
+ def __init__(self, args: ModelArgs):
285
+ super().__init__()
286
+ self.dim = args.dim
287
+ self.topk = args.n_activated_experts
288
+ self.n_groups = args.n_expert_groups
289
+ self.topk_groups = args.n_limited_groups
290
+ self.score_func = args.score_func
291
+ self.route_scale = args.route_scale
292
+ self.weight = nn.Parameter(torch.empty(args.n_routed_experts, args.dim))
293
+ self.bias = nn.Parameter(torch.empty(args.n_routed_experts)) if self.dim == 7168 else None
294
+
295
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
296
+ scores = linear(x, self.weight)
297
+ if self.score_func == "softmax":
298
+ scores = scores.softmax(dim=-1, dtype=torch.float32)
299
+ else:
300
+ scores = scores.sigmoid()
301
+ original_scores = scores
302
+ if self.bias is not None:
303
+ scores = scores + self.bias
304
+ if self.n_groups > 1:
305
+ scores = scores.view(x.size(0), self.n_groups, -1)
306
+ if self.bias is None:
307
+ group_scores = scores.amax(dim=-1)
308
+ else:
309
+ group_scores = scores.topk(2, dim=-1)[0].sum(dim=-1)
310
+ indices = group_scores.topk(self.topk_groups, dim=-1)[1]
311
+ mask = torch.zeros_like(scores[..., 0]).scatter_(1, indices, True)
312
+ scores = (scores * mask.unsqueeze(-1)).flatten(1)
313
+ indices = torch.topk(scores, self.topk, dim=-1)[1]
314
+ weights = original_scores.gather(1, indices)
315
+ if self.score_func == "sigmoid":
316
+ weights /= weights.sum(dim=-1, keepdim=True)
317
+ weights *= self.route_scale
318
+ return weights.type_as(x), indices
319
+
320
+
321
+ class Expert(nn.Module):
322
+ def __init__(self, dim: int, inter_dim: int):
323
+ super().__init__()
324
+ self.w1 = Linear(dim, inter_dim)
325
+ self.w2 = Linear(inter_dim, dim)
326
+ self.w3 = Linear(dim, inter_dim)
327
+
328
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
329
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
330
+
331
+
332
+ class MoE(nn.Module):
333
+ def __init__(self, args: ModelArgs):
334
+ super().__init__()
335
+ self.dim = args.dim
336
+ assert args.n_routed_experts % world_size == 0
337
+ self.n_routed_experts = args.n_routed_experts
338
+ self.n_local_experts = args.n_routed_experts // world_size
339
+ self.n_activated_experts = args.n_activated_experts
340
+ self.experts_start_idx = rank * self.n_local_experts
341
+ self.experts_end_idx = self.experts_start_idx + self.n_local_experts
342
+ self.gate = Gate(args)
343
+ self.experts = nn.ModuleList([Expert(args.dim, args.moe_inter_dim) if self.experts_start_idx <= i < self.experts_end_idx else None
344
+ for i in range(self.n_routed_experts)])
345
+ self.shared_experts = MLP(args.dim, args.n_shared_experts * args.moe_inter_dim)
346
+
347
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
348
+ shape = x.size()
349
+ x = x.view(-1, self.dim)
350
+ weights, indices = self.gate(x)
351
+ y = torch.zeros_like(x)
352
+ counts = torch.bincount(indices.flatten(), minlength=self.n_routed_experts).tolist()
353
+ for i in range(self.experts_start_idx, self.experts_end_idx):
354
+ if counts[i] == 0:
355
+ continue
356
+ expert = self.experts[i]
357
+ idx, top = torch.where(indices == i)
358
+ y[idx] += expert(x[idx]) * weights[idx, top, None]
359
+ z = self.shared_experts(x)
360
+ if world_size > 1:
361
+ dist.all_reduce(y)
362
+ return (y + z).view(shape)
363
+
364
+
365
+ class Block(nn.Module):
366
+ def __init__(self, layer_id: int, args: ModelArgs):
367
+ super().__init__()
368
+ self.attn = MLA(args)
369
+ self.ffn = MLP(args.dim, args.inter_dim) if layer_id < args.n_dense_layers else MoE(args)
370
+ self.attn_norm = RMSNorm(args.dim)
371
+ self.ffn_norm = RMSNorm(args.dim)
372
+
373
+ def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]) -> torch.Tensor:
374
+ x = x + self.attn(self.attn_norm(x), start_pos, freqs_cis, mask)
375
+ x = x + self.ffn(self.ffn_norm(x))
376
+ return x
377
+
378
+
379
+ class Transformer(nn.Module):
380
+ def __init__(self, args: ModelArgs):
381
+ global world_size, rank
382
+ world_size = dist.get_world_size() if dist.is_initialized() else 1
383
+ rank = dist.get_rank() if dist.is_initialized() else 0
384
+ Linear.dtype = torch.float8_e4m3fn if args.dtype == "fp8" else torch.bfloat16
385
+ super().__init__()
386
+ self.max_seq_len = args.max_seq_len
387
+ self.embed = ParallelEmbedding(args.vocab_size, args.dim)
388
+ self.layers = torch.nn.ModuleList()
389
+ for layer_id in range(args.n_layers):
390
+ self.layers.append(Block(layer_id, args))
391
+ self.norm = RMSNorm(args.dim)
392
+ self.head = ColumnParallelLinear(args.dim, args.vocab_size, dtype=torch.get_default_dtype())
393
+ self.register_buffer("freqs_cis", precompute_freqs_cis(args), persistent=False)
394
+
395
+ @torch.inference_mode()
396
+ def forward(self, tokens: torch.Tensor, start_pos: int = 0):
397
+ seqlen = tokens.size(1)
398
+ h = self.embed(tokens)
399
+ freqs_cis = self.freqs_cis[start_pos:start_pos+seqlen]
400
+ mask = None
401
+ if seqlen > 1:
402
+ mask = torch.full((seqlen, seqlen), float("-inf"), device=tokens.device).triu_(1)
403
+ for layer in self.layers:
404
+ h = layer(h, start_pos, freqs_cis, mask)
405
+ h = self.norm(h)[:, -1]
406
+ logits = self.head(h)
407
+ if world_size > 1:
408
+ all_logits = [torch.empty_like(logits) for _ in range(world_size)]
409
+ dist.all_gather(all_logits, logits)
410
+ logits = torch.cat(all_logits, dim=-1)
411
+ return logits
412
+
413
+
414
+ if __name__ == "__main__":
415
+ torch.set_default_dtype(torch.bfloat16)
416
+ torch.set_default_device("cuda")
417
+ torch.manual_seed(0)
418
+ args = ModelArgs()
419
+ x = torch.randint(0, args.vocab_size, (2, 128))
420
+ model = Transformer(args)
421
+ print(model(x).size())
DeepSeek-V3-Base/inference/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch==2.4.1
2
+ triton==3.0.0
3
+ transformers==4.46.3
4
+ safetensors==0.4.5
DeepSeek-V3-Base/model-00064-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0885a795d53d6ad311a52e95ceea534001b6d5c286bf289e692bb487f5cb178
3
+ size 4302384963
DeepSeek-V3-Base/model-00069-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4253c118e4d644760b84ed9bf6e2548d0a6d4741609ecc6c71cfe9fedef915d8
3
+ size 4302384961
DeepSeek-V3-Base/model-00073-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:715341606b17564265e3501b189bcc7e44fa835022150f1a8b01a2607ec5adbe
3
+ size 4302350448
DeepSeek-V3-Base/model-00082-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2345f79d6fbac4dfcaddee6c87353b282890c2dfe0d38a964e92c72a63ac607b
3
+ size 4302384518
DeepSeek-V3-Base/model-00084-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6351c0ad501600e343628c13267595c19ae8248358faf3f8f86bceed845635d
3
+ size 4302350602
DeepSeek-V3-Base/model-00085-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a666a949436810287696ec5b64e98dcadc313caa02f6c01741f87cbfa397864a
3
+ size 4302384710
DeepSeek-V3-Base/model-00088-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57e28d50941c47e7b4269b27a341e8a151cb60a274983738e05375aff93c3d6e
3
+ size 4302384900
DeepSeek-V3-Base/model-00090-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a7ce55b854ca9b5de72c0d3a9912418d1806deaa04baca3ba2def5e3af69bb6
3
+ size 4302384504
DeepSeek-V3-Base/model-00091-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f12c8d76842664034f68e4d40adec945382d2fb21f745cff110ae3c739854d3
3
+ size 4302384961
DeepSeek-V3-Base/model-00092-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6bbfd1f208673e9a262970b5cfd0f1b4393df1f19df80bf9e7af1e8b4f37b0fc
3
+ size 4302350620
DeepSeek-V3-Base/model-00093-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:299f42c2a197a4c01a732bfbab61c6e8e49dc32dd5af6fd4650e4119b9855bfd
3
+ size 4302384692
DeepSeek-V3-Base/model-00094-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:097a51858b709da50670411463ae20e39ade48218d99c485b7b093002249f059
3
+ size 4302384963
DeepSeek-V3-Base/model-00098-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:509289b16b2d717ba671162450803bc961b8cca07b3376f5a471f0e97871d88c
3
+ size 4302384488
DeepSeek-V3-Base/model-00110-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6bc5d168729511efd3b80e4fc89b7cd19897ecad3778bd7e5112a8f98d694ddf
3
+ size 4302384900
DeepSeek-V3-Base/model-00116-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a6a24f97970c50f160ef7afae57c340bbb8f293e6f4033282224fac830b40e3
3
+ size 4302384963
DeepSeek-V3-Base/model-00118-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8fb725e541e450463fd5a96be319f70ddcbd0214060981005ecaf270d472162f
3
+ size 4302384884
DeepSeek-V3-Base/model-00135-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a73e5bc54b533ab7cdfacfc9b5478ab109d45778f87fffc3455a6fbede8814a1
3
+ size 4302384961
DeepSeek-V3-Base/model-00149-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2007465688b8a8b2c5fb5f835dbfd98cd6dad012a3242f87183981b46e710320
3
+ size 4302384963
DeepSeek-V3-Base/model-00154-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d5544dfa1d120a9666947245537659d51e0e11f000a22bcbdbf20dbb81096b8f
3
+ size 4302384961
flash-attention/.gitignore ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+
5
+ # C extensions
6
+ *.so
7
+
8
+ # Distribution / packaging
9
+ bin/
10
+ build/
11
+ develop-eggs/
12
+ dist/
13
+ eggs/
14
+ lib/
15
+ lib64/
16
+ parts/
17
+ sdist/
18
+ var/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+
23
+ # IDE-related
24
+ .idea/
25
+
26
+ # Dev
27
+ venv
flash-attention/.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "csrc/cutlass"]
2
+ path = csrc/cutlass
3
+ url = https://github.com/NVIDIA/cutlass.git
flash-attention/AUTHORS ADDED
@@ -0,0 +1 @@
 
 
1
+ Tri Dao, [email protected]
flash-attention/LICENSE ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file.
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
flash-attention/MANIFEST.in ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ recursive-include csrc *.cu
2
+ recursive-include csrc *.h
3
+ recursive-include csrc *.cuh
4
+ recursive-include csrc *.cpp
5
+ recursive-include csrc *.hpp
6
+
7
+ recursive-include flash_attn *.cu
8
+ recursive-include flash_attn *.h
9
+ recursive-include flash_attn *.cuh
10
+ recursive-include flash_attn *.cpp
11
+ recursive-include flash_attn *.hpp
flash-attention/Makefile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ clean_dist:
3
+ rm -rf dist/*
4
+
5
+ create_dist: clean_dist
6
+ python setup.py sdist
7
+
8
+ upload_package: create_dist
9
+ twine upload dist/*
flash-attention/README.md ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FlashAttention
2
+ This repository provides the official implementation of FlashAttention and
3
+ FlashAttention-2 from the
4
+ following papers.
5
+
6
+ **FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness**
7
+ Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, Christopher Ré
8
+ Paper: https://arxiv.org/abs/2205.14135
9
+ IEEE Spectrum [article](https://spectrum.ieee.org/mlperf-rankings-2022) about our submission to the MLPerf 2.0 benchmark using FlashAttention.
10
+ ![FlashAttention](assets/flashattn_banner.jpg)
11
+
12
+ **FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning**
13
+ Tri Dao
14
+
15
+ Paper: https://tridao.me/publications/flash2/flash2.pdf
16
+
17
+ ![FlashAttention-2](assets/flashattention_logo.png)
18
+
19
+
20
+ ## Usage
21
+
22
+ We've been very happy to see FlashAttention being widely adopted in such a short
23
+ time after its release. This [page](https://github.com/Dao-AILab/flash-attention/blob/main/usage.md)
24
+ contains a partial list of places where FlashAttention is being used.
25
+
26
+ FlashAttention and FlashAttention-2 are free to use and modify (see LICENSE).
27
+ Please cite and credit FlashAttention if you use it.
28
+
29
+ ## Installation and features
30
+
31
+ Requirements:
32
+ - CUDA 11.6 and above.
33
+ - PyTorch 1.12 and above.
34
+ - Linux. Might work for Windows starting v2.3.2 (we've seen a few positive [reports](https://github.com/Dao-AILab/flash-attention/issues/595)) but Windows compilation still requires more testing. If you have ideas on how to set up prebuilt CUDA wheels for Windows, please reach out via Github issue.
35
+
36
+ We recommend the
37
+ [Pytorch](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/pytorch)
38
+ container from Nvidia, which has all the required tools to install FlashAttention.
39
+
40
+ To install:
41
+ 1. Make sure that PyTorch is installed.
42
+ 2. Make sure that `packaging` is installed (`pip install packaging`)
43
+ 3. Make sure that `ninja` is installed and that it works correctly (e.g. `ninja
44
+ --version` then `echo $?` should return exit code 0). If not (sometimes `ninja
45
+ --version` then `echo $?` returns a nonzero exit code), uninstall then reinstall
46
+ `ninja` (`pip uninstall -y ninja && pip install ninja`). Without `ninja`,
47
+ compiling can take a very long time (2h) since it does not use multiple CPU
48
+ cores. With `ninja` compiling takes 3-5 minutes on a 64-core machine.
49
+ 4. Then:
50
+ ```sh
51
+ pip install flash-attn --no-build-isolation
52
+ ```
53
+ Alternatively you can compile from source:
54
+ ```sh
55
+ python setup.py install
56
+ ```
57
+
58
+ If your machine has less than 96GB of RAM and lots of CPU cores, `ninja` might
59
+ run too many parallel compilation jobs that could exhaust the amount of RAM. To
60
+ limit the number of parallel compilation jobs, you can set the environment
61
+ variable `MAX_JOBS`:
62
+ ```sh
63
+ MAX_JOBS=4 pip install flash-attn --no-build-isolation
64
+ ```
65
+
66
+ Interface: `src/flash_attention_interface.py`
67
+
68
+ FlashAttention-2 currently supports:
69
+ 1. Ampere, Ada, or Hopper GPUs (e.g., A100, RTX 3090, RTX 4090, H100). Support for Turing
70
+ GPUs (T4, RTX 2080) is coming soon, please use FlashAttention 1.x for Turing
71
+ GPUs for now.
72
+ 2. Datatype fp16 and bf16 (bf16 requires Ampere, Ada, or Hopper GPUs).
73
+ 3. All head dimensions up to 256. ~~Head dim > 192 backward requires A100/A800 or H100/H800~~. Head dim 256 backward now works on consumer GPUs (if there's no dropout) as of flash-attn 2.5.5.
74
+
75
+
76
+ ## How to use FlashAttention
77
+
78
+ The main functions implement scaled dot product attention (softmax(Q @ K^T *
79
+ softmax_scale) @ V):
80
+ ```python
81
+ from flash_attn import flash_attn_qkvpacked_func, flash_attn_func
82
+ ```
83
+
84
+ ```python
85
+ flash_attn_qkvpacked_func(qkv, dropout_p=0.0, softmax_scale=None, causal=False,
86
+ window_size=(-1, -1), alibi_slopes=None, deterministic=False):
87
+ """dropout_p should be set to 0.0 during evaluation
88
+ If Q, K, V are already stacked into 1 tensor, this function will be faster than
89
+ calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation
90
+ of the gradients of Q, K, V.
91
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
92
+ will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive.
93
+ Arguments:
94
+ qkv: (batch_size, seqlen, 3, nheads, headdim)
95
+ dropout_p: float. Dropout probability.
96
+ softmax_scale: float. The scaling of QK^T before applying softmax.
97
+ Default to 1 / sqrt(headdim).
98
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
99
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
100
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) is added to
101
+ the attention score of query i and key j.
102
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
103
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
104
+ Return:
105
+ out: (batch_size, seqlen, nheads, headdim).
106
+ """
107
+ ```
108
+
109
+ ```python
110
+ flash_attn_func(q, k, v, dropout_p=0.0, softmax_scale=None, causal=False,
111
+ window_size=(-1, -1), alibi_slopes=None, deterministic=False):
112
+ """dropout_p should be set to 0.0 during evaluation
113
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
114
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
115
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
116
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
117
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
118
+ will only attend to keys between
119
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
120
+
121
+ Arguments:
122
+ q: (batch_size, seqlen, nheads, headdim)
123
+ k: (batch_size, seqlen, nheads_k, headdim)
124
+ v: (batch_size, seqlen, nheads_k, headdim)
125
+ dropout_p: float. Dropout probability.
126
+ softmax_scale: float. The scaling of QK^T before applying softmax.
127
+ Default to 1 / sqrt(headdim).
128
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
129
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
130
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of
131
+ (-alibi_slope * |i + seqlen_k - seqlen_q - j|)
132
+ is added to the attention score of query i and key j.
133
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
134
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
135
+ Return:
136
+ out: (batch_size, seqlen, nheads, headdim).
137
+ """
138
+ ```
139
+
140
+ ```python
141
+ def flash_attn_with_kvcache(
142
+ q,
143
+ k_cache,
144
+ v_cache,
145
+ k=None,
146
+ v=None,
147
+ rotary_cos=None,
148
+ rotary_sin=None,
149
+ cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None,
150
+ cache_batch_idx: Optional[torch.Tensor] = None,
151
+ block_table: Optional[torch.Tensor] = None,
152
+ softmax_scale=None,
153
+ causal=False,
154
+ window_size=(-1, -1), # -1 means infinite context window
155
+ rotary_interleaved=True,
156
+ alibi_slopes=None,
157
+ ):
158
+ """
159
+ If k and v are not None, k_cache and v_cache will be updated *inplace* with the new values from
160
+ k and v. This is useful for incremental decoding: you can pass in the cached keys/values from
161
+ the previous step, and update them with the new keys/values from the current step, and do
162
+ attention with the updated cache, all in 1 kernel.
163
+
164
+ If you pass in k / v, you must make sure that the cache is large enough to hold the new values.
165
+ For example, the KV cache could be pre-allocated with the max sequence length, and you can use
166
+ cache_seqlens to keep track of the current sequence lengths of each sequence in the batch.
167
+
168
+ Also apply rotary embedding if rotary_cos and rotary_sin are passed in. The key @k will be
169
+ rotated by rotary_cos and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
170
+ If causal or local (i.e., window_size != (-1, -1)), the query @q will be rotated by rotary_cos
171
+ and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
172
+ If not causal and not local, the query @q will be rotated by rotary_cos and rotary_sin at
173
+ indices cache_seqlens only (i.e. we consider all tokens in @q to be at position cache_seqlens).
174
+
175
+ See tests/test_flash_attn.py::test_flash_attn_kvcache for examples of how to use this function.
176
+
177
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
178
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
179
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
180
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
181
+
182
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
183
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
184
+ 1 1 1 1 0
185
+ 1 1 1 1 1
186
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
187
+ 0 0
188
+ 0 0
189
+ 0 0
190
+ 1 0
191
+ 1 1
192
+ If the row of the mask is all zero, the output will be zero.
193
+
194
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
195
+ will only attend to keys between
196
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
197
+
198
+ Note: Does not support backward pass.
199
+
200
+ Arguments:
201
+ q: (batch_size, seqlen, nheads, headdim)
202
+ k_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no block_table,
203
+ or (num_blocks, page_block_size, nheads_k, headdim) if there's a block_table (i.e. paged KV cache)
204
+ page_block_size must be a multiple of 256.
205
+ v_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no block_table,
206
+ or (num_blocks, page_block_size, nheads_k, headdim) if there's a block_table (i.e. paged KV cache)
207
+ k [optional]: (batch_size, seqlen_new, nheads_k, headdim). If not None, we concatenate
208
+ k with k_cache, starting at the indices specified by cache_seqlens.
209
+ v [optional]: (batch_size, seqlen_new, nheads_k, headdim). Similar to k.
210
+ rotary_cos [optional]: (seqlen_ro, rotary_dim / 2). If not None, we apply rotary embedding
211
+ to k and q. Only applicable if k and v are passed in. rotary_dim must be divisible by 16.
212
+ rotary_sin [optional]: (seqlen_ro, rotary_dim / 2). Similar to rotary_cos.
213
+ cache_seqlens: int, or (batch_size,), dtype torch.int32. The sequence lengths of the
214
+ KV cache.
215
+ block_table [optional]: (batch_size, max_num_blocks_per_seq), dtype torch.int32.
216
+ cache_batch_idx: (batch_size,), dtype torch.int32. The indices used to index into the KV cache.
217
+ If None, we assume that the batch indices are [0, 1, 2, ..., batch_size - 1].
218
+ If the indices are not distinct, and k and v are provided, the values updated in the cache
219
+ might come from any of the duplicate indices.
220
+ softmax_scale: float. The scaling of QK^T before applying softmax.
221
+ Default to 1 / sqrt(headdim).
222
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
223
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
224
+ rotary_interleaved: bool. Only applicable if rotary_cos and rotary_sin are passed in.
225
+ If True, rotary embedding will combine dimensions 0 & 1, 2 & 3, etc. If False,
226
+ rotary embedding will combine dimensions 0 & rotary_dim / 2, 1 & rotary_dim / 2 + 1
227
+ (i.e. GPT-NeoX style).
228
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of
229
+ (-alibi_slope * |i + seqlen_k - seqlen_q - j|)
230
+ is added to the attention score of query i and key j.
231
+
232
+ Return:
233
+ out: (batch_size, seqlen, nheads, headdim).
234
+ """
235
+ ```
236
+
237
+ To see how these functions are used in a multi-head attention layer (which
238
+ includes QKV projection, output projection), see the MHA [implementation](https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/modules/mha.py).
239
+
240
+ ## Changelog
241
+
242
+ ### 2.0: Complete rewrite, 2x faster
243
+ Upgrading from FlashAttention (1.x) to FlashAttention-2
244
+
245
+ These functions have been renamed:
246
+ - `flash_attn_unpadded_func` -> `flash_attn_varlen_func`
247
+ - `flash_attn_unpadded_qkvpacked_func` -> `flash_attn_varlen_qkvpacked_func`
248
+ - `flash_attn_unpadded_kvpacked_func` -> `flash_attn_varlen_kvpacked_func`
249
+
250
+ If the inputs have the same sequence lengths in the same batch, it is simpler
251
+ and faster to use these functions:
252
+ ```python
253
+ flash_attn_qkvpacked_func(qkv, dropout_p=0.0, softmax_scale=None, causal=False)
254
+ ```
255
+ ```python
256
+ flash_attn_func(q, k, v, dropout_p=0.0, softmax_scale=None, causal=False)
257
+ ```
258
+ ### 2.1: Change behavior of causal flag
259
+
260
+ If seqlen_q != seqlen_k and causal=True, the causal mask is aligned to the
261
+ bottom right corner of the attention matrix, instead of the top-left corner.
262
+
263
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 =
264
+ masked out) is:
265
+ v2.0:
266
+ 1 0 0 0 0
267
+ 1 1 0 0 0
268
+ v2.1:
269
+ 1 1 1 1 0
270
+ 1 1 1 1 1
271
+
272
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
273
+ v2.0:
274
+ 1 0
275
+ 1 1
276
+ 1 1
277
+ 1 1
278
+ 1 1
279
+ v2.1:
280
+ 0 0
281
+ 0 0
282
+ 0 0
283
+ 1 0
284
+ 1 1
285
+ If the row of the mask is all zero, the output will be zero.
286
+
287
+ ### 2.2: Optimize for inference
288
+
289
+ Optimize for inference (iterative decoding) when query has very small sequence
290
+ length (e.g., query sequence length = 1). The bottleneck here is to load KV
291
+ cache as fast as possible, and we split the loading across different thread
292
+ blocks, with a separate kernel to combine results.
293
+
294
+ See the function `flash_attn_with_kvcache` with more features for inference
295
+ (perform rotary embedding, updating KV cache inplace).
296
+
297
+ Thanks to the xformers team, and in particular Daniel Haziza, for this
298
+ collaboration.
299
+
300
+ ### 2.3: Local (i.e., sliding window) attention
301
+
302
+ Implement sliding window attention (i.e., local attention). Thanks to [Mistral
303
+ AI](https://mistral.ai/) and in particular Timothée Lacroix for this
304
+ contribution. Sliding window was used in the [Mistral 7B](https://mistral.ai/news/announcing-mistral-7b/) model.
305
+
306
+ ### 2.4: ALiBi (attention with linear bias), deterministic backward pass.
307
+
308
+ Implement ALiBi (Press et al., 2021). Thanks to Sanghun Cho from Kakao Brain for this contribution.
309
+
310
+ Implement deterministic backward pass. Thanks to engineers from [Meituan](www.meituan.com) for this contribution.
311
+
312
+ ### 2.5: Paged KV cache.
313
+
314
+ Support paged KV cache (i.e., [PagedAttention](https://arxiv.org/abs/2309.06180)).
315
+ Thanks to @beginlner for this contribution.
316
+
317
+ ### 2.6: Softcapping.
318
+
319
+ Support attention with softcapping, as used in Gemma-2 and Grok models.
320
+ Thanks to @Narsil for this contribution.
321
+
322
+ ## Performance
323
+
324
+ We present expected speedup (combined forward + backward pass) and memory savings from using FlashAttention against PyTorch standard attention, depending on sequence length, on different GPUs (speedup depends on memory bandwidth - we see more speedup on slower GPU memory).
325
+
326
+ We currently have benchmarks for these GPUs:
327
+ * [A100](#a100)
328
+ * [H100](#h100)
329
+ <!-- * [RTX 3090](#rtx-3090) -->
330
+ <!-- * [T4](#t4) -->
331
+
332
+ ### A100
333
+
334
+ We display FlashAttention speedup using these parameters:
335
+ * Head dimension 64 or 128, hidden dimension 2048 (i.e. either 32 or 16 heads).
336
+ * Sequence length 512, 1k, 2k, 4k, 8k, 16k.
337
+ * Batch size set to 16k / seqlen.
338
+
339
+ #### Speedup
340
+
341
+ ![FlashAttention speedup on A100 80GB SXM5 with FP16/BF16](assets/flash2_a100_fwd_bwd_benchmark.png)
342
+
343
+ #### Memory
344
+
345
+ ![FlashAttention memory](assets/flashattn_memory.jpg)
346
+
347
+ We show memory savings in this graph (note that memory footprint is the same no matter if you use dropout or masking).
348
+ Memory savings are proportional to sequence length -- since standard attention has memory quadratic in sequence length, whereas FlashAttention has memory linear in sequence length.
349
+ We see 10X memory savings at sequence length 2K, and 20X at 4K.
350
+ As a result, FlashAttention can scale to much longer sequence lengths.
351
+
352
+ ### H100
353
+
354
+ ![FlashAttention speedup on H100 SXM5 with FP16/BF16](assets/flash2_h100_fwd_bwd_benchmark.png)
355
+
356
+ ## Full model code and training script
357
+
358
+ We have released the full GPT model
359
+ [implementation](https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/models/gpt.py).
360
+ We also provide optimized implementations of other layers (e.g., MLP, LayerNorm,
361
+ cross-entropy loss, rotary embedding). Overall this speeds up training by 3-5x
362
+ compared to the baseline implementation from Huggingface, reaching up to 225
363
+ TFLOPs/sec per A100, equivalent to 72% model FLOPs utilization (we don't need
364
+ any activation checkpointing).
365
+
366
+ We also include a training
367
+ [script](https://github.com/Dao-AILab/flash-attention/tree/main/training) to
368
+ train GPT2 on Openwebtext and GPT3 on The Pile.
369
+
370
+ ## Triton implementation of FlashAttention
371
+
372
+ Phil Tillet (OpenAI) has an experimental implementation of FlashAttention in Triton:
373
+ https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
374
+
375
+ As Triton is a higher-level language than CUDA, it might be easier to understand
376
+ and experiment with. The notations in the Triton implementation are also closer
377
+ to what's used in our paper.
378
+
379
+ We also have an experimental implementation in Triton that support attention
380
+ bias (e.g. ALiBi):
381
+ https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/flash_attn_triton.py
382
+
383
+
384
+ ## Tests
385
+ We test that FlashAttention produces the same output and gradient as a reference
386
+ implementation, up to some numerical tolerance. In particular, we check that the
387
+ maximum numerical error of FlashAttention is at most twice the numerical error
388
+ of a baseline implementation in Pytorch (for different head dimensions, input
389
+ dtype, sequence length, causal / non-causal).
390
+
391
+ To run the tests:
392
+ ```sh
393
+ pytest -q -s tests/test_flash_attn.py
394
+ ```
395
+ ## When you encounter issues
396
+
397
+ This new release of FlashAttention-2 has been tested on several GPT-style
398
+ models, mostly on A100 GPUs.
399
+
400
+ If you encounter bugs, please open a GitHub Issue!
401
+
402
+ ## Citation
403
+ If you use this codebase, or otherwise found our work valuable, please cite:
404
+ ```
405
+ @inproceedings{dao2022flashattention,
406
+ title={Flash{A}ttention: Fast and Memory-Efficient Exact Attention with {IO}-Awareness},
407
+ author={Dao, Tri and Fu, Daniel Y. and Ermon, Stefano and Rudra, Atri and R{\'e}, Christopher},
408
+ booktitle={Advances in Neural Information Processing Systems (NeurIPS)},
409
+ year={2022}
410
+ }
411
+ @inproceedings{dao2023flashattention2,
412
+ title={Flash{A}ttention-2: Faster Attention with Better Parallelism and Work Partitioning},
413
+ author={Dao, Tri},
414
+ booktitle={International Conference on Learning Representations (ICLR)},
415
+ year={2024}
416
+ }
417
+ ```
flash-attention/setup.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ import sys
4
+ import warnings
5
+ import os
6
+ import re
7
+ import ast
8
+ from pathlib import Path
9
+ from packaging.version import parse, Version
10
+ import platform
11
+
12
+ from setuptools import setup, find_packages
13
+ import subprocess
14
+
15
+ import urllib.request
16
+ import urllib.error
17
+ from wheel.bdist_wheel import bdist_wheel as _bdist_wheel
18
+
19
+ import torch
20
+ from torch.utils.cpp_extension import (
21
+ BuildExtension,
22
+ CppExtension,
23
+ CUDAExtension,
24
+ CUDA_HOME,
25
+ )
26
+
27
+
28
+ with open("README.md", "r", encoding="utf-8") as fh:
29
+ long_description = fh.read()
30
+
31
+
32
+ # ninja build does not work unless include_dirs are abs path
33
+ this_dir = os.path.dirname(os.path.abspath(__file__))
34
+
35
+ PACKAGE_NAME = "flash_attn"
36
+
37
+ BASE_WHEEL_URL = (
38
+ "https://github.com/Dao-AILab/flash-attention/releases/download/{tag_name}/{wheel_name}"
39
+ )
40
+
41
+ # FORCE_BUILD: Force a fresh build locally, instead of attempting to find prebuilt wheels
42
+ # SKIP_CUDA_BUILD: Intended to allow CI to use a simple `python setup.py sdist` run to copy over raw files, without any cuda compilation
43
+ FORCE_BUILD = os.getenv("FLASH_ATTENTION_FORCE_BUILD", "FALSE") == "TRUE"
44
+ SKIP_CUDA_BUILD = os.getenv("FLASH_ATTENTION_SKIP_CUDA_BUILD", "FALSE") == "TRUE"
45
+ # For CI, we want the option to build with C++11 ABI since the nvcr images use C++11 ABI
46
+ FORCE_CXX11_ABI = os.getenv("FLASH_ATTENTION_FORCE_CXX11_ABI", "FALSE") == "TRUE"
47
+
48
+
49
+ def get_platform():
50
+ """
51
+ Returns the platform name as used in wheel filenames.
52
+ """
53
+ if sys.platform.startswith("linux"):
54
+ return f'linux_{platform.uname().machine}'
55
+ elif sys.platform == "darwin":
56
+ mac_version = ".".join(platform.mac_ver()[0].split(".")[:2])
57
+ return f"macosx_{mac_version}_x86_64"
58
+ elif sys.platform == "win32":
59
+ return "win_amd64"
60
+ else:
61
+ raise ValueError("Unsupported platform: {}".format(sys.platform))
62
+
63
+
64
+ def get_cuda_bare_metal_version(cuda_dir):
65
+ raw_output = subprocess.check_output([cuda_dir + "/bin/nvcc", "-V"], universal_newlines=True)
66
+ output = raw_output.split()
67
+ release_idx = output.index("release") + 1
68
+ bare_metal_version = parse(output[release_idx].split(",")[0])
69
+
70
+ return raw_output, bare_metal_version
71
+
72
+
73
+ def check_if_cuda_home_none(global_option: str) -> None:
74
+ if CUDA_HOME is not None:
75
+ return
76
+ # warn instead of error because user could be downloading prebuilt wheels, so nvcc won't be necessary
77
+ # in that case.
78
+ warnings.warn(
79
+ f"{global_option} was requested, but nvcc was not found. Are you sure your environment has nvcc available? "
80
+ "If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, "
81
+ "only images whose names contain 'devel' will provide nvcc."
82
+ )
83
+
84
+
85
+ def append_nvcc_threads(nvcc_extra_args):
86
+ nvcc_threads = os.getenv("NVCC_THREADS") or "4"
87
+ return nvcc_extra_args + ["--threads", nvcc_threads]
88
+
89
+
90
+ cmdclass = {}
91
+ ext_modules = []
92
+
93
+ # We want this even if SKIP_CUDA_BUILD because when we run python setup.py sdist we want the .hpp
94
+ # files included in the source distribution, in case the user compiles from source.
95
+ subprocess.run(["git", "submodule", "update", "--init", "csrc/cutlass"])
96
+
97
+ if not SKIP_CUDA_BUILD:
98
+ print("\n\ntorch.__version__ = {}\n\n".format(torch.__version__))
99
+ TORCH_MAJOR = int(torch.__version__.split(".")[0])
100
+ TORCH_MINOR = int(torch.__version__.split(".")[1])
101
+
102
+ # Check, if ATen/CUDAGeneratorImpl.h is found, otherwise use ATen/cuda/CUDAGeneratorImpl.h
103
+ # See https://github.com/pytorch/pytorch/pull/70650
104
+ generator_flag = []
105
+ torch_dir = torch.__path__[0]
106
+ if os.path.exists(os.path.join(torch_dir, "include", "ATen", "CUDAGeneratorImpl.h")):
107
+ generator_flag = ["-DOLD_GENERATOR_PATH"]
108
+
109
+ check_if_cuda_home_none("flash_attn")
110
+ # Check, if CUDA11 is installed for compute capability 8.0
111
+ cc_flag = []
112
+ if CUDA_HOME is not None:
113
+ _, bare_metal_version = get_cuda_bare_metal_version(CUDA_HOME)
114
+ if bare_metal_version < Version("11.6"):
115
+ raise RuntimeError(
116
+ "FlashAttention is only supported on CUDA 11.6 and above. "
117
+ "Note: make sure nvcc has a supported version by running nvcc -V."
118
+ )
119
+ # cc_flag.append("-gencode")
120
+ # cc_flag.append("arch=compute_75,code=sm_75")
121
+ cc_flag.append("-gencode")
122
+ cc_flag.append("arch=compute_80,code=sm_80")
123
+ if CUDA_HOME is not None:
124
+ if bare_metal_version >= Version("11.8"):
125
+ cc_flag.append("-gencode")
126
+ cc_flag.append("arch=compute_90,code=sm_90")
127
+
128
+ # HACK: The compiler flag -D_GLIBCXX_USE_CXX11_ABI is set to be the same as
129
+ # torch._C._GLIBCXX_USE_CXX11_ABI
130
+ # https://github.com/pytorch/pytorch/blob/8472c24e3b5b60150096486616d98b7bea01500b/torch/utils/cpp_extension.py#L920
131
+ if FORCE_CXX11_ABI:
132
+ torch._C._GLIBCXX_USE_CXX11_ABI = True
133
+ ext_modules.append(
134
+ CUDAExtension(
135
+ name="flash_attn_2_cuda",
136
+ sources=[
137
+ "csrc/flash_attn/flash_api.cpp",
138
+ "csrc/flash_attn/src/flash_fwd_hdim32_fp16_sm80.cu",
139
+ "csrc/flash_attn/src/flash_fwd_hdim32_bf16_sm80.cu",
140
+ "csrc/flash_attn/src/flash_fwd_hdim64_fp16_sm80.cu",
141
+ "csrc/flash_attn/src/flash_fwd_hdim64_bf16_sm80.cu",
142
+ "csrc/flash_attn/src/flash_fwd_hdim96_fp16_sm80.cu",
143
+ "csrc/flash_attn/src/flash_fwd_hdim96_bf16_sm80.cu",
144
+ "csrc/flash_attn/src/flash_fwd_hdim128_fp16_sm80.cu",
145
+ "csrc/flash_attn/src/flash_fwd_hdim128_bf16_sm80.cu",
146
+ "csrc/flash_attn/src/flash_fwd_hdim160_fp16_sm80.cu",
147
+ "csrc/flash_attn/src/flash_fwd_hdim160_bf16_sm80.cu",
148
+ "csrc/flash_attn/src/flash_fwd_hdim192_fp16_sm80.cu",
149
+ "csrc/flash_attn/src/flash_fwd_hdim192_bf16_sm80.cu",
150
+ "csrc/flash_attn/src/flash_fwd_hdim224_fp16_sm80.cu",
151
+ "csrc/flash_attn/src/flash_fwd_hdim224_bf16_sm80.cu",
152
+ "csrc/flash_attn/src/flash_fwd_hdim256_fp16_sm80.cu",
153
+ "csrc/flash_attn/src/flash_fwd_hdim256_bf16_sm80.cu",
154
+ "csrc/flash_attn/src/flash_fwd_hdim32_fp16_causal_sm80.cu",
155
+ "csrc/flash_attn/src/flash_fwd_hdim32_bf16_causal_sm80.cu",
156
+ "csrc/flash_attn/src/flash_fwd_hdim64_fp16_causal_sm80.cu",
157
+ "csrc/flash_attn/src/flash_fwd_hdim64_bf16_causal_sm80.cu",
158
+ "csrc/flash_attn/src/flash_fwd_hdim96_fp16_causal_sm80.cu",
159
+ "csrc/flash_attn/src/flash_fwd_hdim96_bf16_causal_sm80.cu",
160
+ "csrc/flash_attn/src/flash_fwd_hdim128_fp16_causal_sm80.cu",
161
+ "csrc/flash_attn/src/flash_fwd_hdim128_bf16_causal_sm80.cu",
162
+ "csrc/flash_attn/src/flash_fwd_hdim160_fp16_causal_sm80.cu",
163
+ "csrc/flash_attn/src/flash_fwd_hdim160_bf16_causal_sm80.cu",
164
+ "csrc/flash_attn/src/flash_fwd_hdim192_fp16_causal_sm80.cu",
165
+ "csrc/flash_attn/src/flash_fwd_hdim192_bf16_causal_sm80.cu",
166
+ "csrc/flash_attn/src/flash_fwd_hdim224_fp16_causal_sm80.cu",
167
+ "csrc/flash_attn/src/flash_fwd_hdim224_bf16_causal_sm80.cu",
168
+ "csrc/flash_attn/src/flash_fwd_hdim256_fp16_causal_sm80.cu",
169
+ "csrc/flash_attn/src/flash_fwd_hdim256_bf16_causal_sm80.cu",
170
+ "csrc/flash_attn/src/flash_bwd_hdim32_fp16_sm80.cu",
171
+ "csrc/flash_attn/src/flash_bwd_hdim32_bf16_sm80.cu",
172
+ "csrc/flash_attn/src/flash_bwd_hdim64_fp16_sm80.cu",
173
+ "csrc/flash_attn/src/flash_bwd_hdim64_bf16_sm80.cu",
174
+ "csrc/flash_attn/src/flash_bwd_hdim96_fp16_sm80.cu",
175
+ "csrc/flash_attn/src/flash_bwd_hdim96_bf16_sm80.cu",
176
+ "csrc/flash_attn/src/flash_bwd_hdim128_fp16_sm80.cu",
177
+ "csrc/flash_attn/src/flash_bwd_hdim128_bf16_sm80.cu",
178
+ "csrc/flash_attn/src/flash_bwd_hdim160_fp16_sm80.cu",
179
+ "csrc/flash_attn/src/flash_bwd_hdim160_bf16_sm80.cu",
180
+ "csrc/flash_attn/src/flash_bwd_hdim192_fp16_sm80.cu",
181
+ "csrc/flash_attn/src/flash_bwd_hdim192_bf16_sm80.cu",
182
+ "csrc/flash_attn/src/flash_bwd_hdim224_fp16_sm80.cu",
183
+ "csrc/flash_attn/src/flash_bwd_hdim224_bf16_sm80.cu",
184
+ "csrc/flash_attn/src/flash_bwd_hdim256_fp16_sm80.cu",
185
+ "csrc/flash_attn/src/flash_bwd_hdim256_bf16_sm80.cu",
186
+ "csrc/flash_attn/src/flash_fwd_split_hdim32_fp16_sm80.cu",
187
+ "csrc/flash_attn/src/flash_fwd_split_hdim32_bf16_sm80.cu",
188
+ "csrc/flash_attn/src/flash_fwd_split_hdim64_fp16_sm80.cu",
189
+ "csrc/flash_attn/src/flash_fwd_split_hdim64_bf16_sm80.cu",
190
+ "csrc/flash_attn/src/flash_fwd_split_hdim96_fp16_sm80.cu",
191
+ "csrc/flash_attn/src/flash_fwd_split_hdim96_bf16_sm80.cu",
192
+ "csrc/flash_attn/src/flash_fwd_split_hdim128_fp16_sm80.cu",
193
+ "csrc/flash_attn/src/flash_fwd_split_hdim128_bf16_sm80.cu",
194
+ "csrc/flash_attn/src/flash_fwd_split_hdim160_fp16_sm80.cu",
195
+ "csrc/flash_attn/src/flash_fwd_split_hdim160_bf16_sm80.cu",
196
+ "csrc/flash_attn/src/flash_fwd_split_hdim192_fp16_sm80.cu",
197
+ "csrc/flash_attn/src/flash_fwd_split_hdim192_bf16_sm80.cu",
198
+ "csrc/flash_attn/src/flash_fwd_split_hdim224_fp16_sm80.cu",
199
+ "csrc/flash_attn/src/flash_fwd_split_hdim224_bf16_sm80.cu",
200
+ "csrc/flash_attn/src/flash_fwd_split_hdim256_fp16_sm80.cu",
201
+ "csrc/flash_attn/src/flash_fwd_split_hdim256_bf16_sm80.cu",
202
+ "csrc/flash_attn/src/flash_fwd_split_hdim32_fp16_causal_sm80.cu",
203
+ "csrc/flash_attn/src/flash_fwd_split_hdim32_bf16_causal_sm80.cu",
204
+ "csrc/flash_attn/src/flash_fwd_split_hdim64_fp16_causal_sm80.cu",
205
+ "csrc/flash_attn/src/flash_fwd_split_hdim64_bf16_causal_sm80.cu",
206
+ "csrc/flash_attn/src/flash_fwd_split_hdim96_fp16_causal_sm80.cu",
207
+ "csrc/flash_attn/src/flash_fwd_split_hdim96_bf16_causal_sm80.cu",
208
+ "csrc/flash_attn/src/flash_fwd_split_hdim128_fp16_causal_sm80.cu",
209
+ "csrc/flash_attn/src/flash_fwd_split_hdim128_bf16_causal_sm80.cu",
210
+ "csrc/flash_attn/src/flash_fwd_split_hdim160_fp16_causal_sm80.cu",
211
+ "csrc/flash_attn/src/flash_fwd_split_hdim160_bf16_causal_sm80.cu",
212
+ "csrc/flash_attn/src/flash_fwd_split_hdim192_fp16_causal_sm80.cu",
213
+ "csrc/flash_attn/src/flash_fwd_split_hdim192_bf16_causal_sm80.cu",
214
+ "csrc/flash_attn/src/flash_fwd_split_hdim224_fp16_causal_sm80.cu",
215
+ "csrc/flash_attn/src/flash_fwd_split_hdim224_bf16_causal_sm80.cu",
216
+ "csrc/flash_attn/src/flash_fwd_split_hdim256_fp16_causal_sm80.cu",
217
+ "csrc/flash_attn/src/flash_fwd_split_hdim256_bf16_causal_sm80.cu",
218
+ ],
219
+ extra_compile_args={
220
+ "cxx": ["-O3", "-std=c++17"] + generator_flag,
221
+ "nvcc": append_nvcc_threads(
222
+ [
223
+ "-O3",
224
+ "-std=c++17",
225
+ "-U__CUDA_NO_HALF_OPERATORS__",
226
+ "-U__CUDA_NO_HALF_CONVERSIONS__",
227
+ "-U__CUDA_NO_HALF2_OPERATORS__",
228
+ "-U__CUDA_NO_BFLOAT16_CONVERSIONS__",
229
+ "--expt-relaxed-constexpr",
230
+ "--expt-extended-lambda",
231
+ "--use_fast_math",
232
+ # "--ptxas-options=-v",
233
+ # "--ptxas-options=-O2",
234
+ # "-lineinfo",
235
+ # "-DFLASHATTENTION_DISABLE_BACKWARD",
236
+ # "-DFLASHATTENTION_DISABLE_DROPOUT",
237
+ # "-DFLASHATTENTION_DISABLE_ALIBI",
238
+ # "-DFLASHATTENTION_DISABLE_SOFTCAP",
239
+ # "-DFLASHATTENTION_DISABLE_UNEVEN_K",
240
+ # "-DFLASHATTENTION_DISABLE_LOCAL",
241
+ ]
242
+ + generator_flag
243
+ + cc_flag
244
+ ),
245
+ },
246
+ include_dirs=[
247
+ Path(this_dir) / "csrc" / "flash_attn",
248
+ Path(this_dir) / "csrc" / "flash_attn" / "src",
249
+ Path(this_dir) / "csrc" / "cutlass" / "include",
250
+ ],
251
+ )
252
+ )
253
+
254
+
255
+ def get_package_version():
256
+ with open(Path(this_dir) / "flash_attn" / "__init__.py", "r") as f:
257
+ version_match = re.search(r"^__version__\s*=\s*(.*)$", f.read(), re.MULTILINE)
258
+ public_version = ast.literal_eval(version_match.group(1))
259
+ local_version = os.environ.get("FLASH_ATTN_LOCAL_VERSION")
260
+ if local_version:
261
+ return f"{public_version}+{local_version}"
262
+ else:
263
+ return str(public_version)
264
+
265
+
266
+ def get_wheel_url():
267
+ # Determine the version numbers that will be used to determine the correct wheel
268
+ # We're using the CUDA version used to build torch, not the one currently installed
269
+ # _, cuda_version_raw = get_cuda_bare_metal_version(CUDA_HOME)
270
+ torch_cuda_version = parse(torch.version.cuda)
271
+ torch_version_raw = parse(torch.__version__)
272
+ # For CUDA 11, we only compile for CUDA 11.8, and for CUDA 12 we only compile for CUDA 12.2
273
+ # to save CI time. Minor versions should be compatible.
274
+ torch_cuda_version = parse("11.8") if torch_cuda_version.major == 11 else parse("12.2")
275
+ python_version = f"cp{sys.version_info.major}{sys.version_info.minor}"
276
+ platform_name = get_platform()
277
+ flash_version = get_package_version()
278
+ # cuda_version = f"{cuda_version_raw.major}{cuda_version_raw.minor}"
279
+ cuda_version = f"{torch_cuda_version.major}{torch_cuda_version.minor}"
280
+ torch_version = f"{torch_version_raw.major}.{torch_version_raw.minor}"
281
+ cxx11_abi = str(torch._C._GLIBCXX_USE_CXX11_ABI).upper()
282
+
283
+ # Determine wheel URL based on CUDA version, torch version, python version and OS
284
+ wheel_filename = f"{PACKAGE_NAME}-{flash_version}+cu{cuda_version}torch{torch_version}cxx11abi{cxx11_abi}-{python_version}-{python_version}-{platform_name}.whl"
285
+ wheel_url = BASE_WHEEL_URL.format(tag_name=f"v{flash_version}", wheel_name=wheel_filename)
286
+ return wheel_url, wheel_filename
287
+
288
+
289
+ class CachedWheelsCommand(_bdist_wheel):
290
+ """
291
+ The CachedWheelsCommand plugs into the default bdist wheel, which is ran by pip when it cannot
292
+ find an existing wheel (which is currently the case for all flash attention installs). We use
293
+ the environment parameters to detect whether there is already a pre-built version of a compatible
294
+ wheel available and short-circuits the standard full build pipeline.
295
+ """
296
+
297
+ def run(self):
298
+ if FORCE_BUILD:
299
+ return super().run()
300
+
301
+ wheel_url, wheel_filename = get_wheel_url()
302
+ print("Guessing wheel URL: ", wheel_url)
303
+ try:
304
+ urllib.request.urlretrieve(wheel_url, wheel_filename)
305
+
306
+ # Make the archive
307
+ # Lifted from the root wheel processing command
308
+ # https://github.com/pypa/wheel/blob/cf71108ff9f6ffc36978069acb28824b44ae028e/src/wheel/bdist_wheel.py#LL381C9-L381C85
309
+ if not os.path.exists(self.dist_dir):
310
+ os.makedirs(self.dist_dir)
311
+
312
+ impl_tag, abi_tag, plat_tag = self.get_tag()
313
+ archive_basename = f"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}"
314
+
315
+ wheel_path = os.path.join(self.dist_dir, archive_basename + ".whl")
316
+ print("Raw wheel path", wheel_path)
317
+ os.rename(wheel_filename, wheel_path)
318
+ except (urllib.error.HTTPError, urllib.error.URLError):
319
+ print("Precompiled wheel not found. Building from source...")
320
+ # If the wheel could not be downloaded, build from source
321
+ super().run()
322
+
323
+
324
+ class NinjaBuildExtension(BuildExtension):
325
+ def __init__(self, *args, **kwargs) -> None:
326
+ # do not override env MAX_JOBS if already exists
327
+ if not os.environ.get("MAX_JOBS"):
328
+ import psutil
329
+
330
+ # calculate the maximum allowed NUM_JOBS based on cores
331
+ max_num_jobs_cores = max(1, os.cpu_count() // 2)
332
+
333
+ # calculate the maximum allowed NUM_JOBS based on free memory
334
+ free_memory_gb = psutil.virtual_memory().available / (1024 ** 3) # free memory in GB
335
+ max_num_jobs_memory = int(free_memory_gb / 9) # each JOB peak memory cost is ~8-9GB when threads = 4
336
+
337
+ # pick lower value of jobs based on cores vs memory metric to minimize oom and swap usage during compilation
338
+ max_jobs = max(1, min(max_num_jobs_cores, max_num_jobs_memory))
339
+ os.environ["MAX_JOBS"] = str(max_jobs)
340
+
341
+ super().__init__(*args, **kwargs)
342
+
343
+
344
+ setup(
345
+ name=PACKAGE_NAME,
346
+ version=get_package_version(),
347
+ packages=find_packages(
348
+ exclude=(
349
+ "build",
350
+ "csrc",
351
+ "include",
352
+ "tests",
353
+ "dist",
354
+ "docs",
355
+ "benchmarks",
356
+ "flash_attn.egg-info",
357
+ )
358
+ ),
359
+ author="Tri Dao",
360
+ author_email="[email protected]",
361
+ description="Flash Attention: Fast and Memory-Efficient Exact Attention",
362
+ long_description=long_description,
363
+ long_description_content_type="text/markdown",
364
+ url="https://github.com/Dao-AILab/flash-attention",
365
+ classifiers=[
366
+ "Programming Language :: Python :: 3",
367
+ "License :: OSI Approved :: BSD License",
368
+ "Operating System :: Unix",
369
+ ],
370
+ ext_modules=ext_modules,
371
+ cmdclass={"bdist_wheel": CachedWheelsCommand, "build_ext": NinjaBuildExtension}
372
+ if ext_modules
373
+ else {
374
+ "bdist_wheel": CachedWheelsCommand,
375
+ },
376
+ python_requires=">=3.8",
377
+ install_requires=[
378
+ "torch",
379
+ "einops",
380
+ ],
381
+ setup_requires=[
382
+ "packaging",
383
+ "psutil",
384
+ "ninja",
385
+ ],
386
+ )
flash-attention/tests/models/test_vit.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import pytest
4
+ import torch
5
+ from flash_attn.models.vit import vit_base_patch16_224 as flash_vit_base_patch16_224
6
+ from timm.models.vision_transformer import vit_base_patch16_224
7
+
8
+
9
+ @pytest.mark.parametrize("fused_mlp", [False, True])
10
+ # @pytest.mark.parametrize('fused_mlp', [False])
11
+ @pytest.mark.parametrize("optimized", [False, True])
12
+ # @pytest.mark.parametrize('optimized', [True])
13
+ def test_vit(optimized, fused_mlp):
14
+ """Check that our implementation of ViT matches the timm's implementation:
15
+ the output of our forward pass in fp16 should be around the same as
16
+ timm' forward pass in fp16, when compared to timm's forward pass in fp32.
17
+ """
18
+ dtype = torch.float16
19
+ device = "cuda"
20
+
21
+ kwargs = {}
22
+ if optimized:
23
+ kwargs = dict(use_flash_attn=True, fused_bias_fc=True, fused_dropout_add_ln=True)
24
+ kwargs["fused_mlp"] = fused_mlp
25
+ model = flash_vit_base_patch16_224(**kwargs).to(device=device, dtype=dtype)
26
+
27
+ model_ref = vit_base_patch16_224(pretrained=True).to(device=device)
28
+ model_timm = vit_base_patch16_224(pretrained=True).to(device=device, dtype=dtype)
29
+
30
+ model.load_state_dict(model_ref.state_dict())
31
+
32
+ model.eval()
33
+ model_ref.eval()
34
+ model_timm.eval()
35
+
36
+ torch.manual_seed(0)
37
+ batch_size = 2
38
+ x = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)
39
+ out = model(x)
40
+ out_timm = model_timm(x)
41
+ out_ref = model_ref(x.float())
42
+
43
+ print(f"Output max diff: {(out - out_ref).abs().max().item()}")
44
+ print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
45
+ print(f"timm fp16 max diff: {(out_timm - out_ref).abs().max().item()}")
46
+ print(f"timm fp16 mean diff: {(out_timm - out_ref).abs().mean().item()}")
47
+ rtol = 2 if not fused_mlp else 8
48
+ assert (out - out_ref).abs().max().item() < rtol * (out_timm - out_ref).abs().max().item()
flash-attention/tests/modules/test_embedding_parallel.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run test with:
2
+ # torchrun --no_python --nproc_per_node=8 pytest -q -s tests/modules/test_embedding_parallel.py
3
+
4
+ import pytest
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ from apex.transformer import parallel_state
9
+ from einops import rearrange
10
+ from flash_attn.modules.embedding import GPT2Embeddings, ParallelGPT2Embeddings
11
+
12
+ is_sm8x = torch.cuda.get_device_capability("cuda")[0] >= 8
13
+
14
+
15
+ @pytest.mark.parametrize("dtype", [torch.float16] + ([torch.bfloat16] if is_sm8x else []))
16
+ # @pytest.mark.parametrize('dtype', [torch.bfloat16])
17
+ @pytest.mark.parametrize("world_size", [1, 2, 4, 8])
18
+ # @pytest.mark.parametrize('world_size', [2])
19
+ @pytest.mark.parametrize("sequence_parallel", [True, False])
20
+ # @pytest.mark.parametrize('sequence_parallel', [False])
21
+ @pytest.mark.parametrize("has_pos_emb", [True, False])
22
+ # @pytest.mark.parametrize('has_pos_emb', [True])
23
+ @pytest.mark.parametrize("dim", [1024])
24
+ def test_embedding_parallel(dim, has_pos_emb, sequence_parallel, world_size, dtype):
25
+ vocab_size = 50264
26
+ seqlen = 2048
27
+ assert vocab_size % world_size == 0
28
+ assert dim % world_size == 0
29
+ rtol, atol = (3e-3, 5e-2) if dtype == torch.bfloat16 else (3e-3, 3e-3)
30
+ if not torch.distributed.is_initialized():
31
+ torch.distributed.init_process_group(backend="nccl", init_method="env://")
32
+ device = f"cuda:{torch.distributed.get_rank()}"
33
+ assert world_size <= torch.distributed.get_world_size()
34
+ parallel_state.initialize_model_parallel(tensor_model_parallel_size_=world_size)
35
+ rank = parallel_state.get_tensor_model_parallel_rank()
36
+ # set seed
37
+ torch.random.manual_seed(0)
38
+ batch_size = 8
39
+ seqlen = 1024
40
+ assert (batch_size * seqlen) % world_size == 0
41
+ input_ids_pt = torch.randint(0, vocab_size, (batch_size, seqlen), device=device)
42
+ input_ids = input_ids_pt.detach().clone()
43
+
44
+ model_pt = GPT2Embeddings(
45
+ dim, vocab_size, seqlen if has_pos_emb else 0, device=device, dtype=dtype
46
+ )
47
+ model = ParallelGPT2Embeddings(
48
+ dim,
49
+ vocab_size,
50
+ seqlen if has_pos_emb else 0,
51
+ parallel_state.get_tensor_model_parallel_group(),
52
+ sequence_parallel=sequence_parallel,
53
+ device=device,
54
+ dtype=dtype,
55
+ )
56
+ partition_vocab_size = vocab_size // world_size
57
+ partition_dim = dim // world_size
58
+ with torch.no_grad():
59
+ model.word_embeddings.weight.copy_(
60
+ model_pt.word_embeddings.weight[
61
+ rank * partition_vocab_size : (rank + 1) * partition_vocab_size
62
+ ]
63
+ )
64
+ if has_pos_emb:
65
+ model.position_embeddings.weight.copy_(
66
+ model_pt.position_embeddings.weight[
67
+ :, rank * partition_dim : (rank + 1) * partition_dim
68
+ ]
69
+ )
70
+
71
+ out = model(input_ids, combine_batch_seqlen_dim=True)
72
+ out_pt = rearrange(model_pt(input_ids), "b s d -> (b s) d")
73
+ partition_batch_dim = batch_size * seqlen // world_size
74
+ assert torch.allclose(
75
+ out,
76
+ out_pt[rank * partition_batch_dim : (rank + 1) * partition_batch_dim]
77
+ if sequence_parallel
78
+ else out_pt,
79
+ rtol=rtol,
80
+ atol=atol,
81
+ )
82
+
83
+ g = torch.randn_like(out_pt)
84
+ out_pt.backward(g)
85
+ out.backward(
86
+ g[rank * partition_batch_dim : (rank + 1) * partition_batch_dim] if sequence_parallel else g
87
+ )
88
+ parallel_state.destroy_model_parallel()
89
+
90
+ assert torch.allclose(
91
+ model.word_embeddings.weight.grad,
92
+ model_pt.word_embeddings.weight.grad[
93
+ rank * partition_vocab_size : (rank + 1) * partition_vocab_size
94
+ ],
95
+ rtol=rtol,
96
+ atol=atol,
97
+ )
98
+ if has_pos_emb:
99
+ assert torch.allclose(
100
+ model.position_embeddings.weight.grad,
101
+ model_pt.position_embeddings.weight.grad[
102
+ :, rank * partition_dim : (rank + 1) * partition_dim
103
+ ],
104
+ rtol=rtol,
105
+ atol=atol,
106
+ )
flash-attention/tests/modules/test_mha_parallel.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run test with:
2
+ # torchrun --no_python --nproc_per_node=8 pytest -q -s tests/modules/test_mha_parallel.py
3
+
4
+ import math
5
+
6
+ import pytest
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from apex.transformer import parallel_state, tensor_parallel
10
+ from einops import rearrange
11
+ from flash_attn.modules.mha import MHA, ParallelMHA
12
+
13
+ is_sm8x = torch.cuda.get_device_capability("cuda")[0] >= 8
14
+
15
+
16
+ @pytest.mark.parametrize("dtype", [torch.float16] + ([torch.bfloat16] if is_sm8x else []))
17
+ # @pytest.mark.parametrize('dtype', [torch.float16])
18
+ @pytest.mark.parametrize("world_size", [1, 2, 4, 8])
19
+ # @pytest.mark.parametrize('world_size', [2])
20
+ @pytest.mark.parametrize("sequence_parallel", [True, False])
21
+ # @pytest.mark.parametrize('sequence_parallel', [False])
22
+ @pytest.mark.parametrize("head_dim", [64, 128])
23
+ # @pytest.mark.parametrize('head_dim', [64])
24
+ @pytest.mark.parametrize("embed_dim", [1024, 4096])
25
+ # @pytest.mark.parametrize('embed_dim', [1024])
26
+ def test_mha_parallel(embed_dim, head_dim, sequence_parallel, world_size, dtype):
27
+ assert embed_dim % head_dim == 0
28
+ num_heads = embed_dim // head_dim
29
+ assert num_heads % world_size == 0
30
+ rtol, atol = (3e-3, 1e-2) if dtype == torch.bfloat16 else (3e-3, 1e-3)
31
+ if not torch.distributed.is_initialized():
32
+ torch.distributed.init_process_group(backend="nccl", init_method="env://")
33
+ device = f"cuda:{torch.distributed.get_rank()}"
34
+ assert world_size <= torch.distributed.get_world_size()
35
+ parallel_state.initialize_model_parallel(tensor_model_parallel_size_=world_size)
36
+ rank = parallel_state.get_tensor_model_parallel_rank()
37
+ # set seed
38
+ torch.random.manual_seed(0)
39
+ batch_size = 2
40
+ seqlen = 1024
41
+ assert (batch_size * seqlen) % world_size == 0
42
+ x_pt = torch.randn(
43
+ batch_size * seqlen, embed_dim, device=device, dtype=dtype, requires_grad=True
44
+ )
45
+ # We need to generate g here so that all processes get the same gradient,
46
+ # as rank 0 will have an extra bias that changes the RNG.
47
+ # If we don't divide by batch_size, the gradient gets a bit too large.
48
+ g = torch.randn_like(x_pt) / 32
49
+ if sequence_parallel:
50
+ x = (
51
+ tensor_parallel.scatter_to_sequence_parallel_region(x_pt)
52
+ .detach()
53
+ .clone()
54
+ .requires_grad_()
55
+ )
56
+ else:
57
+ x = x_pt.detach().clone().requires_grad_()
58
+
59
+ model_pt = MHA(
60
+ embed_dim,
61
+ num_heads,
62
+ rotary_emb_dim=int(head_dim // 2),
63
+ use_flash_attn=True,
64
+ device=device,
65
+ dtype=dtype,
66
+ )
67
+ partition_dim = embed_dim // world_size
68
+ model = ParallelMHA(
69
+ embed_dim,
70
+ num_heads,
71
+ parallel_state.get_tensor_model_parallel_group(),
72
+ rotary_emb_dim=int(head_dim // 2),
73
+ use_flash_attn=True,
74
+ sequence_parallel=sequence_parallel,
75
+ device=device,
76
+ dtype=dtype,
77
+ )
78
+
79
+ with torch.no_grad():
80
+ model.Wqkv.weight.copy_(
81
+ rearrange(
82
+ rearrange(model_pt.Wqkv.weight, "(three o) i -> three o i", three=3)[
83
+ :, rank * partition_dim : (rank + 1) * partition_dim
84
+ ],
85
+ "three o i -> (three o) i",
86
+ )
87
+ )
88
+ model.Wqkv.bias.copy_(
89
+ rearrange(
90
+ rearrange(model_pt.Wqkv.bias, "(three o) -> three o", three=3)[
91
+ :, rank * partition_dim : (rank + 1) * partition_dim
92
+ ],
93
+ "three o -> (three o)",
94
+ )
95
+ )
96
+ model.out_proj.weight.copy_(
97
+ model_pt.out_proj.weight[:, rank * partition_dim : (rank + 1) * partition_dim]
98
+ )
99
+ if rank == 0:
100
+ model.out_proj.bias.copy_(model_pt.out_proj.bias)
101
+
102
+ out = model(x, seqlen=seqlen)
103
+ out_pt = rearrange(model_pt(rearrange(x_pt, "(b s) d -> b s d", s=seqlen)), "b s d -> (b s) d")
104
+ partition_batch_dim = batch_size * seqlen // world_size
105
+ assert torch.allclose(
106
+ out,
107
+ out_pt[rank * partition_batch_dim : (rank + 1) * partition_batch_dim]
108
+ if sequence_parallel
109
+ else out_pt,
110
+ rtol=rtol,
111
+ atol=atol,
112
+ )
113
+
114
+ out_pt.backward(g)
115
+ out.backward(
116
+ g[rank * partition_batch_dim : (rank + 1) * partition_batch_dim] if sequence_parallel else g
117
+ )
118
+ parallel_state.destroy_model_parallel()
119
+
120
+ assert torch.allclose(
121
+ x.grad,
122
+ x_pt.grad[rank * partition_batch_dim : (rank + 1) * partition_batch_dim]
123
+ if sequence_parallel
124
+ else x_pt.grad,
125
+ rtol=rtol,
126
+ atol=atol / 100, # magnitude of x.grad is quite small
127
+ )
128
+ # The error for d_weight and d_bias is quite a bit higher
129
+ assert torch.allclose(
130
+ model.Wqkv.weight.grad,
131
+ rearrange(
132
+ rearrange(model_pt.Wqkv.weight.grad, "(three o) i -> three o i", three=3)[
133
+ :, rank * partition_dim : (rank + 1) * partition_dim
134
+ ],
135
+ "three o i -> (three o) i",
136
+ ),
137
+ rtol=rtol,
138
+ atol=atol * 10,
139
+ )
140
+ assert torch.allclose(
141
+ model.Wqkv.bias.grad,
142
+ rearrange(
143
+ rearrange(model_pt.Wqkv.bias.grad, "(three o) -> three o", three=3)[
144
+ :, rank * partition_dim : (rank + 1) * partition_dim
145
+ ],
146
+ "three o -> (three o)",
147
+ ),
148
+ rtol=rtol,
149
+ atol=atol * 5,
150
+ )
151
+ assert torch.allclose(
152
+ model.out_proj.weight.grad,
153
+ model_pt.out_proj.weight.grad[:, rank * partition_dim : (rank + 1) * partition_dim],
154
+ rtol=rtol,
155
+ atol=atol * 10,
156
+ )
157
+ if rank == 0:
158
+ assert torch.allclose(
159
+ model.out_proj.bias.grad, model_pt.out_proj.bias.grad, rtol=rtol, atol=atol * 5
160
+ )
flash-attention/tests/modules/test_mlp_parallel.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run test with:
2
+ # torchrun --no_python --nproc_per_node=8 pytest -q -s tests/modules/test_mlp_parallel.py
3
+
4
+ import pytest
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from apex.transformer import parallel_state, tensor_parallel
8
+ from einops import rearrange
9
+ from flash_attn.modules.mlp import GatedMlp, ParallelGatedMlp
10
+
11
+ is_sm8x = torch.cuda.get_device_capability("cuda")[0] >= 8
12
+
13
+
14
+ @pytest.mark.parametrize("dtype", [torch.float16] + ([torch.bfloat16] if is_sm8x else []))
15
+ # @pytest.mark.parametrize('dtype', [torch.float16])
16
+ @pytest.mark.parametrize("world_size", [1, 2, 4, 8])
17
+ # @pytest.mark.parametrize('world_size', [2])
18
+ @pytest.mark.parametrize("sequence_parallel", [True, False])
19
+ # @pytest.mark.parametrize('sequence_parallel', [False])
20
+ @pytest.mark.parametrize("activation", [F.silu, F.sigmoid])
21
+ # @pytest.mark.parametrize('activation', [F.silu])
22
+ @pytest.mark.parametrize("dim", [1024, 4096])
23
+ # @pytest.mark.parametrize('dim', [1024])
24
+ def test_mlp_parallel(dim, activation, sequence_parallel, world_size, dtype):
25
+ rtol, atol = (3e-3, 3e-2) if dtype == torch.bfloat16 else (3e-3, 3e-3)
26
+
27
+ if not torch.distributed.is_initialized():
28
+ torch.distributed.init_process_group(backend="nccl", init_method="env://")
29
+ device = f"cuda:{torch.distributed.get_rank()}"
30
+ assert world_size <= torch.distributed.get_world_size()
31
+ parallel_state.initialize_model_parallel(tensor_model_parallel_size_=world_size)
32
+ rank = parallel_state.get_tensor_model_parallel_rank()
33
+ # set seed
34
+ torch.random.manual_seed(0)
35
+ batch_size = 2
36
+ seqlen = 1024
37
+ assert (batch_size * seqlen) % world_size == 0
38
+ x_pt = torch.randn(batch_size * seqlen, dim, device=device, dtype=dtype, requires_grad=True)
39
+ # We need to generate g here so that all processes get the same gradient,
40
+ # as rank 0 will have an extra bias that changes the RNG.
41
+ # If we don't divide by batch_size, the gradient gets a bit too large.
42
+ g = torch.randn_like(x_pt) / 32
43
+ if sequence_parallel:
44
+ x = (
45
+ tensor_parallel.scatter_to_sequence_parallel_region(x_pt)
46
+ .detach()
47
+ .clone()
48
+ .requires_grad_()
49
+ )
50
+ else:
51
+ x = x_pt.detach().clone().requires_grad_()
52
+
53
+ model_pt = GatedMlp(dim, activation=activation, device=device, dtype=dtype)
54
+ partition_dim = model_pt.fc1.weight.shape[0] // 2 // world_size
55
+ model = ParallelGatedMlp(
56
+ dim,
57
+ parallel_state.get_tensor_model_parallel_group(),
58
+ activation=activation,
59
+ sequence_parallel=sequence_parallel,
60
+ device=device,
61
+ dtype=dtype,
62
+ )
63
+
64
+ with torch.no_grad():
65
+ model.fc1.weight.copy_(
66
+ rearrange(
67
+ rearrange(model_pt.fc1.weight, "(two o) i -> two o i", two=2)[
68
+ :, rank * partition_dim : (rank + 1) * partition_dim
69
+ ],
70
+ "two o i -> (two o) i",
71
+ )
72
+ )
73
+ model.fc1.bias.copy_(
74
+ rearrange(
75
+ rearrange(model_pt.fc1.bias, "(two o) -> two o", two=2)[
76
+ :, rank * partition_dim : (rank + 1) * partition_dim
77
+ ],
78
+ "two o -> (two o)",
79
+ )
80
+ )
81
+ model.fc2.weight.copy_(
82
+ model_pt.fc2.weight[:, rank * partition_dim : (rank + 1) * partition_dim]
83
+ )
84
+ if rank == 0:
85
+ model.fc2.bias.copy_(model_pt.fc2.bias)
86
+
87
+ out = model(x)
88
+ out_pt = model_pt(x_pt)
89
+ partition_batch_dim = batch_size * seqlen // world_size
90
+ assert torch.allclose(
91
+ out,
92
+ out_pt[rank * partition_batch_dim : (rank + 1) * partition_batch_dim]
93
+ if sequence_parallel
94
+ else out_pt,
95
+ rtol=rtol,
96
+ atol=atol,
97
+ )
98
+
99
+ out_pt.backward(g)
100
+ out.backward(
101
+ g[rank * partition_batch_dim : (rank + 1) * partition_batch_dim] if sequence_parallel else g
102
+ )
103
+ parallel_state.destroy_model_parallel()
104
+
105
+ assert torch.allclose(
106
+ x.grad,
107
+ x_pt.grad[rank * partition_batch_dim : (rank + 1) * partition_batch_dim]
108
+ if sequence_parallel
109
+ else x_pt.grad,
110
+ rtol=rtol,
111
+ atol=atol,
112
+ )
113
+
114
+ assert torch.allclose(
115
+ model.fc1.weight.grad,
116
+ rearrange(
117
+ rearrange(model_pt.fc1.weight.grad, "(two o) i -> two o i", two=2)[
118
+ :, rank * partition_dim : (rank + 1) * partition_dim
119
+ ],
120
+ "two o i -> (two o) i",
121
+ ),
122
+ rtol=rtol,
123
+ atol=atol,
124
+ )
125
+ assert torch.allclose(
126
+ model.fc1.bias.grad,
127
+ rearrange(
128
+ rearrange(model_pt.fc1.bias.grad, "(two o) -> two o", two=2)[
129
+ :, rank * partition_dim : (rank + 1) * partition_dim
130
+ ],
131
+ "two o -> (two o)",
132
+ ),
133
+ rtol=rtol,
134
+ atol=atol,
135
+ )
136
+ assert torch.allclose(
137
+ model.fc2.weight.grad,
138
+ model_pt.fc2.weight.grad[:, rank * partition_dim : (rank + 1) * partition_dim],
139
+ rtol=rtol,
140
+ atol=atol,
141
+ )
142
+ if rank == 0:
143
+ assert torch.allclose(model.fc2.bias.grad, model_pt.fc2.bias.grad, rtol=rtol, atol=atol)
flash-attention/tests/ops/test_dropout_layer_norm.py ADDED
@@ -0,0 +1,1189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import pytest
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from einops import rearrange, repeat
7
+ from flash_attn.ops.layer_norm import (
8
+ DropoutAddLayerNorm,
9
+ dropout_add_layer_norm,
10
+ dropout_add_layer_norm_parallel_residual,
11
+ dropout_add_layer_norm_subset,
12
+ )
13
+ from flash_attn.ops.rms_norm import (
14
+ DropoutAddRMSNorm,
15
+ dropout_add_rms_norm,
16
+ dropout_add_rms_norm_parallel_residual,
17
+ dropout_add_rms_norm_subset,
18
+ )
19
+
20
+ try:
21
+ from apex.normalization import FusedRMSNorm
22
+ from apex.normalization.fused_layer_norm import fused_rms_norm_affine
23
+ except:
24
+ FusedRMSNorm, fused_rms_norm_affine = None, None
25
+
26
+
27
+ is_sm8x = torch.cuda.get_device_capability("cuda")[0] >= 8
28
+
29
+
30
+ @pytest.mark.parametrize("is_rms_norm", [False, True])
31
+ @pytest.mark.parametrize("has_colscale", [True, False])
32
+ # @pytest.mark.parametrize('has_colscale', [False])
33
+ @pytest.mark.parametrize("has_rowscale", [True, False])
34
+ # @pytest.mark.parametrize('has_rowscale', [True])
35
+ @pytest.mark.parametrize("has_residual", [True, False])
36
+ # @pytest.mark.parametrize('has_residual', [False])
37
+ @pytest.mark.parametrize("dropout_p", [0.37, 0.0])
38
+ # @pytest.mark.parametrize('dropout_p', [0.0])
39
+ @pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
40
+ # @pytest.mark.parametrize('weight_dtype', [torch.float32])
41
+ @pytest.mark.parametrize(
42
+ "input_dtype,residual_dtype",
43
+ [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
44
+ + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
45
+ )
46
+ # @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float16, torch.float32)])
47
+ @pytest.mark.parametrize(
48
+ "hidden_size",
49
+ [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
50
+ )
51
+ # @pytest.mark.parametrize('hidden_size', [256])
52
+ def test_dropout_layer_norm_training(
53
+ hidden_size,
54
+ input_dtype,
55
+ residual_dtype,
56
+ weight_dtype,
57
+ dropout_p,
58
+ has_residual,
59
+ has_rowscale,
60
+ has_colscale,
61
+ is_rms_norm,
62
+ ):
63
+ if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
64
+ pytest.skip() # Not supported
65
+ if is_rms_norm and FusedRMSNorm is None:
66
+ pytest.skip() # We need Apex's FusedRMSNorm to test
67
+ layer_norm_cls = torch.nn.LayerNorm if not is_rms_norm else FusedRMSNorm
68
+ our_layer_norm_cls = DropoutAddLayerNorm if not is_rms_norm else DropoutAddRMSNorm
69
+ our_layer_norm_func = dropout_add_layer_norm if not is_rms_norm else dropout_add_rms_norm
70
+ device = "cuda"
71
+ # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
72
+ rtol, atol = (1e-3, 1e-4)
73
+ # set seed
74
+ torch.random.manual_seed(0)
75
+ batch_size = 8
76
+ seqlen = 512
77
+ x0_pt = torch.randn(
78
+ batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
79
+ )
80
+ x0 = x0_pt.detach().clone().requires_grad_()
81
+ x0_ref = x0_pt.detach().clone().float().requires_grad_()
82
+ if has_colscale:
83
+ colscale = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
84
+ colscale_pt = colscale.detach().clone().requires_grad_()
85
+ colscale_ref = colscale.detach().clone().float().requires_grad_()
86
+ else:
87
+ colscale = None
88
+ if has_residual:
89
+ res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
90
+ res = res_pt.detach().clone().requires_grad_()
91
+ res_ref = res_pt.detach().clone().float().requires_grad_()
92
+ else:
93
+ res = None
94
+ if has_rowscale:
95
+ rowscale = torch.empty(batch_size, seqlen, device=device, dtype=input_dtype)
96
+ survival_rate = 0.87
97
+ rowscale = rowscale.bernoulli_(survival_rate) / survival_rate
98
+ x0_scaled_pt = x0_pt * rearrange(rowscale, "... -> ... 1")
99
+ x0_scaled_ref = x0_ref * rearrange(rowscale, "... -> ... 1")
100
+ else:
101
+ rowscale = None
102
+ x0_scaled_pt = x0_pt
103
+ x0_scaled_ref = x0_ref
104
+ if has_colscale:
105
+ x0_scaled_pt = x0_scaled_pt * colscale_pt
106
+ x0_scaled_ref = x0_scaled_ref * colscale_ref
107
+ model_pt = layer_norm_cls(hidden_size).to(device=device, dtype=weight_dtype)
108
+ torch.nn.init.normal_(model_pt.weight)
109
+ if not is_rms_norm:
110
+ torch.nn.init.normal_(model_pt.bias)
111
+ model_ref = layer_norm_cls(hidden_size).to(device=device, dtype=torch.float32)
112
+ model = our_layer_norm_cls(hidden_size, p=dropout_p, device=device, dtype=weight_dtype)
113
+ with torch.no_grad():
114
+ model.weight.copy_(model_pt.weight)
115
+ model_ref.weight.copy_(model_pt.weight)
116
+ if not is_rms_norm:
117
+ model.bias.copy_(model_pt.bias)
118
+ model_ref.bias.copy_(model_pt.bias)
119
+ residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32
120
+ out, dmask = our_layer_norm_func(
121
+ x0,
122
+ res,
123
+ model.weight,
124
+ model.bias,
125
+ model.p,
126
+ model.eps,
127
+ rowscale=rowscale,
128
+ layerscale=colscale,
129
+ residual_in_fp32=residual_in_fp32,
130
+ return_dropout_mask=True,
131
+ )
132
+ assert out.dtype == input_dtype
133
+ print(f"Actual dropout fraction: {1 - dmask.float().mean().item()}")
134
+ if has_residual:
135
+ residual_pt = (
136
+ (x0_scaled_pt.float() * dmask.float()) / (1 - dropout_p) + res_pt.float()
137
+ ).to(dtype=residual_dtype)
138
+ residual_ref = (x0_scaled_ref * dmask.float()) / (1 - dropout_p) + res_ref
139
+ else:
140
+ residual_pt = ((x0_scaled_pt.float() * dmask.float()) / (1 - dropout_p)).to(
141
+ dtype=residual_dtype
142
+ )
143
+ residual_ref = (x0_scaled_ref * dmask.float()) / (1 - dropout_p)
144
+ out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(dtype=input_dtype)
145
+ out_ref = model_ref(residual_ref)
146
+ assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4
147
+
148
+ g = torch.randn_like(out) / batch_size
149
+ out_pt.backward(g)
150
+ out.backward(g)
151
+ out_ref.backward(g)
152
+ assert (x0.grad - x0_ref.grad).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad).abs().max() + 1e-4
153
+ if has_residual:
154
+ assert (res.grad - res_ref.grad).abs().max() <= 4 * (
155
+ res_pt.grad - res_ref.grad
156
+ ).abs().max() + 1e-4
157
+ assert (model.weight.grad - model_ref.weight.grad).abs().max() <= 3 * (
158
+ model_pt.weight.grad - model_ref.weight.grad
159
+ ).abs().max() + 3e-5
160
+ if not is_rms_norm:
161
+ assert (model.bias.grad - model_ref.bias.grad).abs().max() <= 2 * (
162
+ model_pt.bias.grad - model_ref.bias.grad
163
+ ).abs().max() + 3e-5
164
+ if has_colscale:
165
+ assert (colscale.grad - colscale_ref.grad).abs().max() <= 2 * (
166
+ colscale_pt.grad - colscale_ref.grad
167
+ ).abs().max() + 2e-4
168
+
169
+
170
+ @pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
171
+ @pytest.mark.parametrize(
172
+ "input_dtype,residual_dtype",
173
+ [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
174
+ + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
175
+ )
176
+ @pytest.mark.parametrize("hidden_size", [768, 1024, 1280, 1536, 1600, 2048, 2560, 3072, 4096, 5120])
177
+ def test_dropout_layer_norm_eval(hidden_size, input_dtype, residual_dtype, weight_dtype):
178
+ if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
179
+ pytest.skip() # Not supported
180
+ device = "cuda"
181
+ # rtol, atol = (1e-5, 1e-6) if dtype == torch.float32 else (1e-3, 1e-4)
182
+ rtol, atol = (1e-3, 1e-4)
183
+ dropout_p = 0.37
184
+ # set seed
185
+ torch.random.manual_seed(0)
186
+ batch_size = 32
187
+ seqlen = 512
188
+ x0_pt = torch.randn(
189
+ batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
190
+ )
191
+ x0 = x0_pt.detach().clone().requires_grad_()
192
+ x0_ref = x0_pt.detach().clone().float().requires_grad_()
193
+ res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
194
+ res = res_pt.detach().clone().requires_grad_()
195
+ res_ref = res_pt.detach().clone().float().requires_grad_()
196
+ model_pt = torch.nn.LayerNorm(hidden_size, device=device, dtype=weight_dtype)
197
+ torch.nn.init.normal_(model_pt.weight)
198
+ torch.nn.init.normal_(model_pt.bias)
199
+ model = DropoutAddLayerNorm(hidden_size, p=dropout_p, device=device, dtype=weight_dtype)
200
+ model_ref = torch.nn.LayerNorm(hidden_size, device=device, dtype=torch.float32)
201
+ with torch.no_grad():
202
+ model.weight.copy_(model_pt.weight)
203
+ model.bias.copy_(model_pt.bias)
204
+ model_ref.weight.copy_(model_pt.weight)
205
+ model_ref.bias.copy_(model_pt.bias)
206
+ model_pt.eval()
207
+ model.eval()
208
+ model_ref.eval()
209
+ out = model(x0, res)
210
+ residual_pt = (x0_pt.float() + res_pt.float()).to(dtype=residual_dtype)
211
+ residual_ref = x0_ref + res_ref
212
+ out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(input_dtype)
213
+ out_ref = model_ref(residual_ref)
214
+ assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4
215
+
216
+
217
+ @pytest.mark.parametrize("is_rms_norm", [False, True])
218
+ @pytest.mark.parametrize("has_colscale", [True, False])
219
+ @pytest.mark.parametrize("has_rowscale", [True, False])
220
+ @pytest.mark.parametrize("has_residual", [True, False])
221
+ @pytest.mark.parametrize("dropout_p", [0.37, 0.0])
222
+ @pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
223
+ @pytest.mark.parametrize(
224
+ "input_dtype,residual_dtype",
225
+ [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
226
+ + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
227
+ )
228
+ # @pytest.mark.parametrize('has_colscale', [True])
229
+ # @pytest.mark.parametrize('has_rowscale', [False])
230
+ # @pytest.mark.parametrize('has_residual', [True])
231
+ # @pytest.mark.parametrize('dropout_p', [0.0])
232
+ # @pytest.mark.parametrize('weight_dtype', [torch.float32])
233
+ # @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float32, torch.float32)])
234
+ @pytest.mark.parametrize(
235
+ "hidden_size",
236
+ [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
237
+ )
238
+ # @pytest.mark.parametrize('hidden_size', [256])
239
+ def test_dropout_layer_norm_prenorm_training(
240
+ hidden_size,
241
+ input_dtype,
242
+ residual_dtype,
243
+ weight_dtype,
244
+ dropout_p,
245
+ has_residual,
246
+ has_rowscale,
247
+ has_colscale,
248
+ is_rms_norm,
249
+ ):
250
+ if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
251
+ pytest.skip() # Not supported
252
+ if is_rms_norm and FusedRMSNorm is None:
253
+ pytest.skip() # We need Apex's FusedRMSNorm to test
254
+ layer_norm_cls = torch.nn.LayerNorm if not is_rms_norm else FusedRMSNorm
255
+ our_layer_norm_cls = DropoutAddLayerNorm if not is_rms_norm else DropoutAddRMSNorm
256
+ our_layer_norm_func = dropout_add_layer_norm if not is_rms_norm else dropout_add_rms_norm
257
+ device = "cuda"
258
+ # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
259
+ rtol, atol = (1e-3, 2e-4)
260
+ # set seed
261
+ torch.random.manual_seed(0)
262
+ batch_size = 8
263
+ seqlen = 512
264
+ x0_pt = torch.randn(
265
+ batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
266
+ )
267
+ x0 = x0_pt.detach().clone().requires_grad_()
268
+ x0_ref = x0_pt.detach().clone().float().requires_grad_()
269
+ if has_colscale:
270
+ colscale = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
271
+ colscale_pt = colscale.detach().clone().requires_grad_()
272
+ colscale_ref = colscale.detach().clone().float().requires_grad_()
273
+ else:
274
+ colscale = None
275
+ if has_residual:
276
+ res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
277
+ res = res_pt.detach().clone().requires_grad_()
278
+ res_ref = res_pt.detach().clone().float().requires_grad_()
279
+ else:
280
+ res = None
281
+ if has_rowscale:
282
+ rowscale = torch.empty(batch_size, seqlen, device=device, dtype=input_dtype)
283
+ survival_rate = 0.87
284
+ rowscale = rowscale.bernoulli_(survival_rate) / survival_rate
285
+ x0_scaled_pt = x0_pt * rearrange(rowscale, "... -> ... 1")
286
+ x0_scaled_ref = x0_ref * rearrange(rowscale, "... -> ... 1")
287
+ else:
288
+ rowscale = None
289
+ x0_scaled_pt = x0_pt
290
+ x0_scaled_ref = x0_ref
291
+ if has_colscale:
292
+ x0_scaled_pt = x0_scaled_pt * colscale_pt
293
+ x0_scaled_ref = x0_scaled_ref * colscale_ref
294
+ model_pt = layer_norm_cls(hidden_size).to(device=device, dtype=weight_dtype)
295
+ torch.nn.init.normal_(model_pt.weight)
296
+ if not is_rms_norm:
297
+ torch.nn.init.normal_(model_pt.bias)
298
+ model_ref = layer_norm_cls(hidden_size).to(device=device, dtype=torch.float32)
299
+ model = our_layer_norm_cls(
300
+ hidden_size, prenorm=True, p=dropout_p, device=device, dtype=weight_dtype
301
+ )
302
+ with torch.no_grad():
303
+ model.weight.copy_(model_pt.weight)
304
+ model_ref.weight.copy_(model_pt.weight)
305
+ if not is_rms_norm:
306
+ model.bias.copy_(model_pt.bias)
307
+ model_ref.bias.copy_(model_pt.bias)
308
+ residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32
309
+ out, residual, dmask = our_layer_norm_func(
310
+ x0,
311
+ res,
312
+ model.weight,
313
+ model.bias,
314
+ model.p,
315
+ model.eps,
316
+ rowscale=rowscale,
317
+ layerscale=colscale,
318
+ prenorm=True,
319
+ residual_in_fp32=residual_in_fp32,
320
+ return_dropout_mask=True,
321
+ )
322
+ print(f"Actual dropout fraction: {1 - dmask.float().mean().item()}")
323
+ if has_residual:
324
+ residual_pt = (
325
+ (x0_scaled_pt.float() * dmask.float()) / (1 - dropout_p) + res_pt.float()
326
+ ).to(dtype=residual_dtype)
327
+ residual_ref = (x0_scaled_ref * dmask.float()) / (1 - dropout_p) + res_ref
328
+ else:
329
+ residual_pt = ((x0_scaled_pt.float() * dmask.float()) / (1 - dropout_p)).to(
330
+ dtype=residual_dtype
331
+ )
332
+ residual_ref = (x0_scaled_ref * dmask.float()) / (1 - dropout_p)
333
+ out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(dtype=input_dtype)
334
+ out_ref = model_ref(residual_ref)
335
+ assert out.dtype == input_dtype
336
+ assert residual.dtype == residual_dtype
337
+ assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4
338
+ assert (residual - residual_ref).abs().max() <= 4 * (
339
+ residual_pt - residual_ref
340
+ ).abs().max() + 1e-4
341
+
342
+ g = torch.randn_like(out) / batch_size
343
+ (out_pt * F.sigmoid(residual_pt)).backward(g)
344
+ (out * F.sigmoid(residual)).backward(g)
345
+ (out_ref * F.sigmoid(residual_ref.to(dtype=residual_dtype))).backward(g)
346
+ assert (x0.grad - x0_ref.grad).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad).abs().max() + 1e-4
347
+ if has_residual:
348
+ assert (res.grad - res_ref.grad).abs().max() <= 4 * (
349
+ res_pt.grad - res_ref.grad
350
+ ).abs().max() + 1e-4
351
+ assert (model.weight.grad - model_ref.weight.grad).abs().max() <= 2 * (
352
+ model_pt.weight.grad - model_ref.weight.grad
353
+ ).abs().max() + 2e-4
354
+ if not is_rms_norm:
355
+ assert (model.bias.grad - model_ref.bias.grad).abs().max() <= 2 * (
356
+ model_pt.bias.grad - model_ref.bias.grad
357
+ ).abs().max() + 2e-4
358
+ if has_colscale:
359
+ assert (colscale.grad - colscale_ref.grad).abs().max() <= 2 * (
360
+ colscale_pt.grad - colscale_ref.grad
361
+ ).abs().max() + 2e-4
362
+
363
+
364
+ @pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
365
+ @pytest.mark.parametrize(
366
+ "input_dtype,residual_dtype",
367
+ [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
368
+ + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
369
+ )
370
+ @pytest.mark.parametrize("hidden_size", [768, 1024, 1280, 1536, 1600, 2048, 2560, 3072, 4096, 5120])
371
+ def test_dropout_layer_norm_prenorm_eval(hidden_size, input_dtype, residual_dtype, weight_dtype):
372
+ if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
373
+ pytest.skip() # Not supported
374
+ device = "cuda"
375
+ # rtol, atol = (1e-5, 1e-6) if dtype == torch.float32 else (1e-3, 1e-4)
376
+ rtol, atol = (1e-3, 1e-4)
377
+ dropout_p = 0.37
378
+ # set seed
379
+ torch.random.manual_seed(0)
380
+ batch_size = 32
381
+ seqlen = 512
382
+ x0_pt = torch.randn(
383
+ batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
384
+ )
385
+ x0 = x0_pt.detach().clone().requires_grad_()
386
+ x0_ref = x0_pt.detach().clone().float().requires_grad_()
387
+ res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
388
+ res = res_pt.detach().clone().requires_grad_()
389
+ res_ref = res_pt.detach().clone().float().requires_grad_()
390
+ model_pt = torch.nn.LayerNorm(hidden_size, device=device, dtype=weight_dtype)
391
+ torch.nn.init.normal_(model_pt.weight)
392
+ torch.nn.init.normal_(model_pt.bias)
393
+ model = DropoutAddLayerNorm(
394
+ hidden_size, prenorm=True, p=dropout_p, device=device, dtype=weight_dtype
395
+ )
396
+ model_ref = torch.nn.LayerNorm(hidden_size, device=device, dtype=torch.float32)
397
+ with torch.no_grad():
398
+ model.weight.copy_(model_pt.weight)
399
+ model.bias.copy_(model_pt.bias)
400
+ model_ref.weight.copy_(model_pt.weight)
401
+ model_ref.bias.copy_(model_pt.bias)
402
+ model_pt.eval()
403
+ model.eval()
404
+ model_ref.eval()
405
+ out, residual = model(x0, res)
406
+ residual_pt = (x0_pt.float() + res_pt.float()).to(dtype=residual_dtype)
407
+ residual_ref = x0_ref + res_ref
408
+ out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(input_dtype)
409
+ out_ref = model_ref(residual_ref)
410
+ assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4
411
+ assert (residual - residual_ref).abs().max() <= 4 * (
412
+ residual_pt - residual_ref
413
+ ).abs().max() + 1e-4
414
+
415
+
416
+ @pytest.mark.parametrize("has_colscale", [True, False])
417
+ @pytest.mark.parametrize("has_residual", [True, False])
418
+ @pytest.mark.parametrize("dropout_p", [0.37, 0.0])
419
+ @pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
420
+ @pytest.mark.parametrize(
421
+ "input_dtype,residual_dtype",
422
+ [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
423
+ + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
424
+ )
425
+ # @pytest.mark.parametrize('has_colscale', [True])
426
+ # @pytest.mark.parametrize('has_residual', [True])
427
+ # @pytest.mark.parametrize('dropout_p', [0.0])
428
+ # @pytest.mark.parametrize('weight_dtype', [torch.float32])
429
+ # @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float32, torch.float32)])
430
+ @pytest.mark.parametrize(
431
+ "hidden_size",
432
+ [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
433
+ )
434
+ # @pytest.mark.parametrize('hidden_size', [256])
435
+ def test_dropout_layer_norm_subset_training(
436
+ hidden_size, input_dtype, residual_dtype, weight_dtype, dropout_p, has_residual, has_colscale
437
+ ):
438
+ if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
439
+ pytest.skip() # Not supported
440
+ device = "cuda"
441
+ # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
442
+ rtol, atol = (1e-3, 2e-4)
443
+ # set seed
444
+ torch.random.manual_seed(0)
445
+ batch_size = 8
446
+ seqlen = 512
447
+ drop_path_rate = 0.4
448
+ drop_path_scale = 1 / (1 - drop_path_rate)
449
+
450
+ def generate_droppath_masks(batch_size, seqlen, drop_path_rate, device):
451
+ # Do it on CPU so we can get the numrows (with .item()) without GPU-CPU sync
452
+ mask_batch = torch.rand(batch_size) < 1 - drop_path_rate
453
+ numrows = (mask_batch).sum().item() * seqlen
454
+ mask_batch = mask_batch.to(device=device, non_blocking=True)
455
+ mask_batch_seqlen = repeat(mask_batch, "b -> (b s)", s=seqlen)
456
+ subset = torch.cumsum(mask_batch_seqlen, dim=0, dtype=torch.int32).masked_fill_(
457
+ ~mask_batch_seqlen, 0
458
+ )
459
+ return mask_batch, numrows, rearrange(subset, "(b s) -> b s", b=batch_size)
460
+
461
+ x0_mask_batch, x0_numrows, x0_subset = generate_droppath_masks(
462
+ batch_size, seqlen, drop_path_rate, device
463
+ )
464
+ out_mask_batch, out_numrows, out_subset = generate_droppath_masks(
465
+ batch_size, seqlen, drop_path_rate, device
466
+ )
467
+
468
+ x0_pt = torch.randn(
469
+ batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
470
+ )
471
+ x0 = x0_pt.detach().clone()[x0_mask_batch].requires_grad_()
472
+ x0_ref = x0_pt.detach().clone().float().requires_grad_()
473
+ if has_colscale:
474
+ colscale = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
475
+ colscale_pt = colscale.detach().clone().requires_grad_()
476
+ colscale_ref = colscale.detach().clone().float().requires_grad_()
477
+ else:
478
+ colscale = None
479
+ if has_residual:
480
+ res_pt = torch.randn_like(x0_pt, dtype=residual_dtype, requires_grad=True)
481
+ res = res_pt.detach().clone().requires_grad_()
482
+ res_ref = res_pt.detach().clone().float().requires_grad_()
483
+ else:
484
+ res = None
485
+
486
+ if has_colscale:
487
+ x0_scaled_pt = x0_pt * colscale_pt
488
+ x0_scaled_ref = x0_ref * colscale_ref
489
+ else:
490
+ x0_scaled_pt = x0_pt
491
+ x0_scaled_ref = x0_ref
492
+
493
+ model_pt = torch.nn.LayerNorm(hidden_size, device=device, dtype=weight_dtype)
494
+ torch.nn.init.normal_(model_pt.weight)
495
+ torch.nn.init.normal_(model_pt.bias)
496
+ model_ref = torch.nn.LayerNorm(hidden_size, device=device, dtype=torch.float32)
497
+ model = DropoutAddLayerNorm(
498
+ hidden_size, prenorm=False, p=dropout_p, device=device, dtype=weight_dtype
499
+ )
500
+ with torch.no_grad():
501
+ model.weight.copy_(model_pt.weight)
502
+ model.bias.copy_(model_pt.bias)
503
+ model_ref.weight.copy_(model_pt.weight)
504
+ model_ref.bias.copy_(model_pt.bias)
505
+
506
+ residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32
507
+ out, dmask = dropout_add_layer_norm_subset(
508
+ x0,
509
+ res,
510
+ model.weight,
511
+ model.bias,
512
+ model.p,
513
+ model.eps,
514
+ layerscale=colscale,
515
+ x0_subset=x0_subset,
516
+ out_subset=out_subset,
517
+ rowscale_const=drop_path_scale,
518
+ out_numrows=out_numrows,
519
+ prenorm=False,
520
+ residual_in_fp32=residual_in_fp32,
521
+ return_dropout_mask=True,
522
+ )
523
+ print(f"Actual dropout fraction: {1 - dmask.float().mean().item()}")
524
+
525
+ x0_scaled_pt = (
526
+ x0_scaled_pt.masked_fill(repeat(~x0_mask_batch, "b -> b s d", s=seqlen, d=hidden_size), 0)
527
+ * drop_path_scale
528
+ )
529
+ x0_scaled_ref = (
530
+ x0_scaled_ref.masked_fill(repeat(~x0_mask_batch, "b -> b s d", s=seqlen, d=hidden_size), 0)
531
+ * drop_path_scale
532
+ )
533
+ dmask_expanded = torch.zeros_like(x0_pt, dtype=torch.uint8)
534
+ dmask_expanded[x0_mask_batch] = dmask
535
+ if has_residual:
536
+ residual_pt = (
537
+ (x0_scaled_pt.float() * dmask_expanded.float()) / (1 - dropout_p) + res_pt.float()
538
+ ).to(dtype=residual_dtype)
539
+ residual_ref = (x0_scaled_ref * dmask_expanded.float()) / (1 - dropout_p) + res_ref
540
+ else:
541
+ residual_pt = ((x0_scaled_pt.float() * dmask_expanded.float()) / (1 - dropout_p)).to(
542
+ dtype=residual_dtype
543
+ )
544
+ residual_ref = (x0_scaled_ref * dmask_expanded.float()) / (1 - dropout_p)
545
+ out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(dtype=input_dtype)[out_mask_batch]
546
+ out_ref = model_ref(residual_ref)[out_mask_batch]
547
+ assert out.dtype == input_dtype
548
+ assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4
549
+
550
+ g = torch.randn_like(out) / batch_size
551
+ out_pt.backward(g)
552
+ out.backward(g)
553
+ out_ref.backward(g)
554
+ assert (x0.grad - x0_ref.grad[x0_mask_batch]).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad)[
555
+ x0_mask_batch
556
+ ].abs().max() + 1e-4
557
+ if has_residual:
558
+ assert (res.grad - res_ref.grad).abs().max() <= 4 * (
559
+ res_pt.grad - res_ref.grad
560
+ ).abs().max() + 1e-4
561
+ assert (model.weight.grad - model_ref.weight.grad).abs().max() <= 2 * (
562
+ model_pt.weight.grad - model_ref.weight.grad
563
+ ).abs().max() + 2e-4
564
+ assert (model.bias.grad - model_ref.bias.grad).abs().max() <= 2 * (
565
+ model_pt.bias.grad - model_ref.bias.grad
566
+ ).abs().max() + 2e-4
567
+ if has_colscale:
568
+ assert (colscale.grad - colscale_ref.grad).abs().max() <= 2 * (
569
+ colscale_pt.grad - colscale_ref.grad
570
+ ).abs().max() + 2e-4
571
+
572
+
573
+ @pytest.mark.parametrize("has_colscale", [True, False])
574
+ @pytest.mark.parametrize("has_residual", [True, False])
575
+ @pytest.mark.parametrize("dropout_p", [0.37, 0.0])
576
+ @pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
577
+ @pytest.mark.parametrize(
578
+ "input_dtype,residual_dtype",
579
+ [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
580
+ + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
581
+ )
582
+ # @pytest.mark.parametrize('has_colscale', [True])
583
+ # @pytest.mark.parametrize('has_residual', [True])
584
+ # @pytest.mark.parametrize('dropout_p', [0.0])
585
+ # @pytest.mark.parametrize('weight_dtype', [torch.float32])
586
+ # @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float32, torch.float32)])
587
+ @pytest.mark.parametrize(
588
+ "hidden_size",
589
+ [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
590
+ )
591
+ # @pytest.mark.parametrize('hidden_size', [256])
592
+ def test_dropout_layer_norm_subset_prenorm_training(
593
+ hidden_size, input_dtype, residual_dtype, weight_dtype, dropout_p, has_residual, has_colscale
594
+ ):
595
+ if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
596
+ pytest.skip() # Not supported
597
+ device = "cuda"
598
+ # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
599
+ rtol, atol = (1e-3, 2e-4)
600
+ # set seed
601
+ torch.random.manual_seed(0)
602
+ batch_size = 8
603
+ seqlen = 512
604
+ drop_path_rate = 0.4
605
+ drop_path_scale = 1 / (1 - drop_path_rate)
606
+
607
+ def generate_droppath_masks(batch_size, seqlen, drop_path_rate, device):
608
+ # Do it on CPU so we can get the numrows (with .item()) without GPU-CPU sync
609
+ mask_batch = torch.rand(batch_size) < 1 - drop_path_rate
610
+ numrows = (mask_batch).sum().item() * seqlen
611
+ mask_batch = mask_batch.to(device=device, non_blocking=True)
612
+ mask_batch_seqlen = repeat(mask_batch, "b -> (b s)", s=seqlen)
613
+ subset = torch.cumsum(mask_batch_seqlen, dim=0, dtype=torch.int32).masked_fill_(
614
+ ~mask_batch_seqlen, 0
615
+ )
616
+ return mask_batch, numrows, rearrange(subset, "(b s) -> b s", b=batch_size)
617
+
618
+ x0_mask_batch, x0_numrows, x0_subset = generate_droppath_masks(
619
+ batch_size, seqlen, drop_path_rate, device
620
+ )
621
+ out_mask_batch, out_numrows, out_subset = generate_droppath_masks(
622
+ batch_size, seqlen, drop_path_rate, device
623
+ )
624
+
625
+ x0_pt = torch.randn(
626
+ batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
627
+ )
628
+ x0 = x0_pt.detach().clone()[x0_mask_batch].requires_grad_()
629
+ x0_ref = x0_pt.detach().clone().float().requires_grad_()
630
+ if has_colscale:
631
+ colscale = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
632
+ colscale_pt = colscale.detach().clone().requires_grad_()
633
+ colscale_ref = colscale.detach().clone().float().requires_grad_()
634
+ else:
635
+ colscale = None
636
+ if has_residual:
637
+ res_pt = torch.randn_like(x0_pt, dtype=residual_dtype, requires_grad=True)
638
+ res = res_pt.detach().clone().requires_grad_()
639
+ res_ref = res_pt.detach().clone().float().requires_grad_()
640
+ else:
641
+ res = None
642
+
643
+ if has_colscale:
644
+ x0_scaled_pt = x0_pt * colscale_pt
645
+ x0_scaled_ref = x0_ref * colscale_ref
646
+ else:
647
+ x0_scaled_pt = x0_pt
648
+ x0_scaled_ref = x0_ref
649
+
650
+ model_pt = torch.nn.LayerNorm(hidden_size, device=device, dtype=weight_dtype)
651
+ torch.nn.init.normal_(model_pt.weight)
652
+ torch.nn.init.normal_(model_pt.bias)
653
+ model_ref = torch.nn.LayerNorm(hidden_size, device=device, dtype=torch.float32)
654
+ model = DropoutAddLayerNorm(
655
+ hidden_size, prenorm=True, p=dropout_p, device=device, dtype=weight_dtype
656
+ )
657
+ with torch.no_grad():
658
+ model.weight.copy_(model_pt.weight)
659
+ model.bias.copy_(model_pt.bias)
660
+ model_ref.weight.copy_(model_pt.weight)
661
+ model_ref.bias.copy_(model_pt.bias)
662
+
663
+ residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32
664
+ out, residual, dmask = dropout_add_layer_norm_subset(
665
+ x0,
666
+ res,
667
+ model.weight,
668
+ model.bias,
669
+ model.p,
670
+ model.eps,
671
+ layerscale=colscale,
672
+ x0_subset=x0_subset,
673
+ out_subset=out_subset,
674
+ rowscale_const=drop_path_scale,
675
+ out_numrows=out_numrows,
676
+ prenorm=True,
677
+ residual_in_fp32=residual_in_fp32,
678
+ return_dropout_mask=True,
679
+ )
680
+ print(f"Actual dropout fraction: {1 - dmask.float().mean().item()}")
681
+
682
+ x0_scaled_pt = (
683
+ x0_scaled_pt.masked_fill(repeat(~x0_mask_batch, "b -> b s d", s=seqlen, d=hidden_size), 0)
684
+ * drop_path_scale
685
+ )
686
+ x0_scaled_ref = (
687
+ x0_scaled_ref.masked_fill(repeat(~x0_mask_batch, "b -> b s d", s=seqlen, d=hidden_size), 0)
688
+ * drop_path_scale
689
+ )
690
+ dmask_expanded = torch.zeros_like(x0_pt, dtype=torch.uint8)
691
+ dmask_expanded[x0_mask_batch] = dmask
692
+ if has_residual:
693
+ residual_pt = (
694
+ (x0_scaled_pt.float() * dmask_expanded.float()) / (1 - dropout_p) + res_pt.float()
695
+ ).to(dtype=residual_dtype)
696
+ residual_ref = (x0_scaled_ref * dmask_expanded.float()) / (1 - dropout_p) + res_ref
697
+ else:
698
+ residual_pt = ((x0_scaled_pt.float() * dmask_expanded.float()) / (1 - dropout_p)).to(
699
+ dtype=residual_dtype
700
+ )
701
+ residual_ref = (x0_scaled_ref * dmask_expanded.float()) / (1 - dropout_p)
702
+ out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(dtype=input_dtype)[out_mask_batch]
703
+ out_ref = model_ref(residual_ref)[out_mask_batch]
704
+ assert out.dtype == input_dtype
705
+ assert residual.dtype == residual_dtype
706
+ assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4
707
+ assert (residual - residual_ref).abs().max() <= 4 * (
708
+ residual_pt - residual_ref
709
+ ).abs().max() + 1e-4
710
+
711
+ g = torch.randn_like(out) / batch_size
712
+ (out_pt * F.sigmoid(residual_pt[out_mask_batch]) + residual_pt.mean(0, keepdim=True)).backward(
713
+ g
714
+ )
715
+ (out * F.sigmoid(residual[out_mask_batch]) + residual.mean(0, keepdim=True)).backward(g)
716
+ (
717
+ out_ref * F.sigmoid(residual_ref[out_mask_batch].to(dtype=residual_dtype))
718
+ + residual_ref.mean(0, keepdim=True)
719
+ ).backward(g)
720
+ assert (x0.grad - x0_ref.grad[x0_mask_batch]).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad)[
721
+ x0_mask_batch
722
+ ].abs().max() + 1e-4
723
+ if has_residual:
724
+ assert (res.grad - res_ref.grad).abs().max() <= 4 * (
725
+ res_pt.grad - res_ref.grad
726
+ ).abs().max() + 1e-4
727
+ assert (model.weight.grad - model_ref.weight.grad).abs().max() <= 2 * (
728
+ model_pt.weight.grad - model_ref.weight.grad
729
+ ).abs().max() + 2e-4
730
+ assert (model.bias.grad - model_ref.bias.grad).abs().max() <= 2 * (
731
+ model_pt.bias.grad - model_ref.bias.grad
732
+ ).abs().max() + 2e-4
733
+ if has_colscale:
734
+ assert (colscale.grad - colscale_ref.grad).abs().max() <= 2 * (
735
+ colscale_pt.grad - colscale_ref.grad
736
+ ).abs().max() + 2e-4
737
+
738
+
739
+ @pytest.mark.parametrize("is_rms_norm", [False, True])
740
+ # @pytest.mark.parametrize('is_rms_norm', [False])
741
+ @pytest.mark.parametrize("tied_norm", [False, True])
742
+ # @pytest.mark.parametrize('tied_norm', [False])
743
+ @pytest.mark.parametrize("has_residual", [True, False])
744
+ # @pytest.mark.parametrize('has_residual', [False])
745
+ @pytest.mark.parametrize("has_x1", [True, False])
746
+ # @pytest.mark.parametrize('has_x1', [True])
747
+ @pytest.mark.parametrize("dropout_p", [0.37, 0.0])
748
+ # @pytest.mark.parametrize('dropout_p', [0.0])
749
+ @pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
750
+ # @pytest.mark.parametrize('weight_dtype', [torch.float16])
751
+ @pytest.mark.parametrize(
752
+ "input_dtype,residual_dtype",
753
+ [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
754
+ + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
755
+ )
756
+ # @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float16, torch.float32)])
757
+ @pytest.mark.parametrize(
758
+ "hidden_size",
759
+ [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
760
+ )
761
+ # @pytest.mark.parametrize('hidden_size', [256])
762
+ def test_dropout_layer_norm_parallel_residual_training(
763
+ hidden_size,
764
+ input_dtype,
765
+ residual_dtype,
766
+ weight_dtype,
767
+ dropout_p,
768
+ has_x1,
769
+ has_residual,
770
+ tied_norm,
771
+ is_rms_norm,
772
+ ):
773
+ if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
774
+ pytest.skip() # Not supported
775
+ if is_rms_norm and fused_rms_norm_affine is None:
776
+ pytest.skip() # We need Apex's FusedRMSNorm to test
777
+ our_layer_norm_func = (
778
+ dropout_add_layer_norm_parallel_residual
779
+ if not is_rms_norm
780
+ else dropout_add_rms_norm_parallel_residual
781
+ )
782
+ device = "cuda"
783
+ # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
784
+ rtol, atol = (1e-3, 1e-4)
785
+ # set seed
786
+ torch.random.manual_seed(0)
787
+ batch_size = 8
788
+ seqlen = 512
789
+ x0_pt = torch.randn(
790
+ batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
791
+ )
792
+ x0 = x0_pt.detach().clone().requires_grad_()
793
+ x0_ref = x0_pt.detach().clone().float().requires_grad_()
794
+ if has_x1:
795
+ x1_pt = torch.randn(
796
+ batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
797
+ )
798
+ x1 = x1_pt.detach().clone().requires_grad_()
799
+ x1_ref = x1_pt.detach().clone().float().requires_grad_()
800
+ else:
801
+ x1 = None
802
+ if has_residual:
803
+ res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
804
+ res = res_pt.detach().clone().requires_grad_()
805
+ res_ref = res_pt.detach().clone().float().requires_grad_()
806
+ else:
807
+ res = None
808
+ weight0 = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
809
+ bias0 = (
810
+ torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
811
+ if not is_rms_norm
812
+ else None
813
+ )
814
+ weight0_pt = weight0.detach().clone().requires_grad_()
815
+ weight0_ref = weight0.detach().clone().float().requires_grad_()
816
+ bias0_pt = bias0.detach().clone().requires_grad_() if bias0 is not None else None
817
+ bias0_ref = bias0.detach().clone().float().requires_grad_() if bias0 is not None else None
818
+ if not tied_norm:
819
+ weight1 = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
820
+ bias1 = (
821
+ torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
822
+ if not is_rms_norm
823
+ else None
824
+ )
825
+ weight1_pt = weight1.detach().clone().requires_grad_()
826
+ weight1_ref = weight1.detach().clone().float().requires_grad_()
827
+ bias1_pt = bias1.detach().clone().requires_grad_() if bias1 is not None else None
828
+ bias1_ref = bias1.detach().clone().float().requires_grad_() if bias1 is not None else None
829
+ else:
830
+ weight1, bias1 = None, None
831
+ epsilon = 1e-5
832
+ residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32
833
+
834
+ out0, out1, dmask0, dmask1 = our_layer_norm_func(
835
+ x0,
836
+ x1,
837
+ res,
838
+ weight0,
839
+ bias0,
840
+ weight1,
841
+ bias1,
842
+ dropout_p,
843
+ epsilon,
844
+ residual_in_fp32=residual_in_fp32,
845
+ return_dropout_mask=True,
846
+ )
847
+ assert out0.dtype == input_dtype
848
+ if not tied_norm:
849
+ assert out1.dtype == input_dtype
850
+ print(f"Actual dropout fraction: {1 - dmask0.float().mean().item()}")
851
+ if has_residual:
852
+ if has_x1:
853
+ residual_pt = (
854
+ (x0_pt.float() * dmask0.float()) / (1 - dropout_p)
855
+ + (x1_pt.float() * dmask1.float()) / (1 - dropout_p)
856
+ + res_pt.float()
857
+ ).to(dtype=residual_dtype)
858
+ residual_ref = (
859
+ (x0_ref * dmask0.float()) / (1 - dropout_p)
860
+ + (x1_ref * dmask1.float()) / (1 - dropout_p)
861
+ ) + res_ref
862
+ else:
863
+ residual_pt = ((x0_pt.float() * dmask0.float()) / (1 - dropout_p) + res_pt.float()).to(
864
+ dtype=residual_dtype
865
+ )
866
+ residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p) + res_ref
867
+ else:
868
+ if has_x1:
869
+ residual_pt = (
870
+ (x0_pt.float() * dmask0.float()) / (1 - dropout_p)
871
+ + (x1_pt.float() * dmask1.float()) / (1 - dropout_p)
872
+ ).to(dtype=residual_dtype)
873
+ residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p) + (
874
+ x1_ref * dmask1.float()
875
+ ) / (1 - dropout_p)
876
+ else:
877
+ residual_pt = ((x0_pt.float() * dmask0.float()) / (1 - dropout_p)).to(
878
+ dtype=residual_dtype
879
+ )
880
+ residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p)
881
+ if not is_rms_norm:
882
+ out0_pt = F.layer_norm(
883
+ residual_pt.to(dtype=weight_dtype), (hidden_size,), weight0_pt, bias0_pt, eps=epsilon
884
+ ).to(dtype=input_dtype)
885
+ out0_ref = F.layer_norm(residual_ref, (hidden_size,), weight0_ref, bias0_ref, eps=epsilon)
886
+ if not tied_norm:
887
+ out1_pt = F.layer_norm(
888
+ residual_pt.to(dtype=weight_dtype),
889
+ (hidden_size,),
890
+ weight1_pt,
891
+ bias1_pt,
892
+ eps=epsilon,
893
+ ).to(dtype=input_dtype)
894
+ out1_ref = F.layer_norm(
895
+ residual_ref, (hidden_size,), weight1_ref, bias1_ref, eps=epsilon
896
+ )
897
+ else:
898
+ out0_pt = fused_rms_norm_affine(
899
+ residual_pt.to(dtype=weight_dtype), weight0_pt, (hidden_size,), eps=epsilon
900
+ ).to(dtype=input_dtype)
901
+ out0_ref = fused_rms_norm_affine(residual_ref, weight0_ref, (hidden_size,), eps=epsilon)
902
+ if not tied_norm:
903
+ out1_pt = fused_rms_norm_affine(
904
+ residual_pt.to(dtype=weight_dtype), weight1_pt, (hidden_size,), eps=epsilon
905
+ ).to(dtype=input_dtype)
906
+ out1_ref = fused_rms_norm_affine(residual_ref, weight1_ref, (hidden_size,), eps=epsilon)
907
+
908
+ assert (out0 - out0_ref).abs().max() <= 4 * (out0_pt - out0_ref).abs().max() + 1e-4
909
+ if not tied_norm:
910
+ assert (out1 - out1_ref).abs().max() <= 4 * (out1_pt - out1_ref).abs().max() + 1e-4
911
+
912
+ g0 = torch.randn_like(out0) / batch_size
913
+ if tied_norm:
914
+ out0.backward(g0)
915
+ out0_pt.backward(g0)
916
+ out0_ref.backward(g0)
917
+ else:
918
+ g1 = torch.randn_like(out1) / batch_size
919
+ (out0 * g0 + out1 * g1).sum().backward()
920
+ (out0_pt * g0 + out1_pt * g1).sum().backward()
921
+ (out0_ref * g0 + out1_ref * g1).sum().backward()
922
+ assert (x0.grad - x0_ref.grad).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad).abs().max() + 1e-4
923
+ if has_x1:
924
+ assert (x1.grad - x1_ref.grad).abs().max() <= 4 * (
925
+ x1_pt.grad - x1_ref.grad
926
+ ).abs().max() + 1e-4
927
+ if has_residual:
928
+ assert (res.grad - res_ref.grad).abs().max() <= 4 * (
929
+ res_pt.grad - res_ref.grad
930
+ ).abs().max() + 1e-4
931
+ assert (weight0.grad - weight0_ref.grad).abs().max() <= 3 * (
932
+ weight0_pt.grad - weight0_ref.grad
933
+ ).abs().max() + 3e-5
934
+ if not is_rms_norm:
935
+ assert (bias0.grad - bias0_ref.grad).abs().max() <= 2 * (
936
+ bias0_pt.grad - bias0_ref.grad
937
+ ).abs().max() + 3e-5
938
+ if not tied_norm:
939
+ assert (weight1.grad - weight1_ref.grad).abs().max() <= 3 * (
940
+ weight1_pt.grad - weight1_ref.grad
941
+ ).abs().max() + 3e-5
942
+ if not is_rms_norm:
943
+ assert (bias1.grad - bias1_ref.grad).abs().max() <= 2 * (
944
+ bias1_pt.grad - bias1_ref.grad
945
+ ).abs().max() + 3e-5
946
+
947
+
948
+ @pytest.mark.parametrize("is_rms_norm", [False, True])
949
+ # @pytest.mark.parametrize('is_rms_norm', [False])
950
+ @pytest.mark.parametrize("tied_norm", [False, True])
951
+ # @pytest.mark.parametrize('tied_norm', [False])
952
+ @pytest.mark.parametrize("has_residual", [True, False])
953
+ # @pytest.mark.parametrize('has_residual', [False])
954
+ @pytest.mark.parametrize("has_x1", [True, False])
955
+ # @pytest.mark.parametrize('has_x1', [True])
956
+ @pytest.mark.parametrize("dropout_p", [0.37, 0.0])
957
+ # @pytest.mark.parametrize('dropout_p', [0.0])
958
+ @pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
959
+ # @pytest.mark.parametrize('weight_dtype', [torch.float16])
960
+ @pytest.mark.parametrize(
961
+ "input_dtype,residual_dtype",
962
+ [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
963
+ + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
964
+ )
965
+ # @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float16, torch.float32)])
966
+ @pytest.mark.parametrize(
967
+ "hidden_size",
968
+ [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
969
+ )
970
+ # @pytest.mark.parametrize('hidden_size', [256])
971
+ def test_dropout_layer_norm_parallel_residual_prenorm_training(
972
+ hidden_size,
973
+ input_dtype,
974
+ residual_dtype,
975
+ weight_dtype,
976
+ dropout_p,
977
+ has_x1,
978
+ has_residual,
979
+ tied_norm,
980
+ is_rms_norm,
981
+ ):
982
+ if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
983
+ pytest.skip() # Not supported
984
+ if is_rms_norm and fused_rms_norm_affine is None:
985
+ pytest.skip() # We need Apex's FusedRMSNorm to test
986
+ our_layer_norm_func = (
987
+ dropout_add_layer_norm_parallel_residual
988
+ if not is_rms_norm
989
+ else dropout_add_rms_norm_parallel_residual
990
+ )
991
+ device = "cuda"
992
+ # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
993
+ rtol, atol = (1e-3, 1e-4)
994
+ # set seed
995
+ torch.random.manual_seed(0)
996
+ batch_size = 8
997
+ seqlen = 512
998
+ x0_pt = torch.randn(
999
+ batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
1000
+ )
1001
+ x0 = x0_pt.detach().clone().requires_grad_()
1002
+ x0_ref = x0_pt.detach().clone().float().requires_grad_()
1003
+ if has_x1:
1004
+ x1_pt = torch.randn(
1005
+ batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
1006
+ )
1007
+ x1 = x1_pt.detach().clone().requires_grad_()
1008
+ x1_ref = x1_pt.detach().clone().float().requires_grad_()
1009
+ else:
1010
+ x1 = None
1011
+ if has_residual:
1012
+ res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
1013
+ res = res_pt.detach().clone().requires_grad_()
1014
+ res_ref = res_pt.detach().clone().float().requires_grad_()
1015
+ else:
1016
+ res = None
1017
+ weight0 = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
1018
+ bias0 = (
1019
+ torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
1020
+ if not is_rms_norm
1021
+ else None
1022
+ )
1023
+ weight0_pt = weight0.detach().clone().requires_grad_()
1024
+ weight0_ref = weight0.detach().clone().float().requires_grad_()
1025
+ bias0_pt = bias0.detach().clone().requires_grad_() if bias0 is not None else None
1026
+ bias0_ref = bias0.detach().clone().float().requires_grad_() if bias0 is not None else None
1027
+ if not tied_norm:
1028
+ weight1 = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
1029
+ bias1 = (
1030
+ torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
1031
+ if not is_rms_norm
1032
+ else None
1033
+ )
1034
+ weight1_pt = weight1.detach().clone().requires_grad_()
1035
+ weight1_ref = weight1.detach().clone().float().requires_grad_()
1036
+ bias1_pt = bias1.detach().clone().requires_grad_() if bias1 is not None else None
1037
+ bias1_ref = bias1.detach().clone().float().requires_grad_() if bias1 is not None else None
1038
+ else:
1039
+ weight1, bias1 = None, None
1040
+ epsilon = 1e-5
1041
+ residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32
1042
+
1043
+ out0, out1, residual, dmask0, dmask1 = our_layer_norm_func(
1044
+ x0,
1045
+ x1,
1046
+ res,
1047
+ weight0,
1048
+ bias0,
1049
+ weight1,
1050
+ bias1,
1051
+ dropout_p,
1052
+ epsilon,
1053
+ prenorm=True,
1054
+ residual_in_fp32=residual_in_fp32,
1055
+ return_dropout_mask=True,
1056
+ )
1057
+ assert out0.dtype == input_dtype
1058
+ if not tied_norm:
1059
+ assert out1.dtype == input_dtype
1060
+ print(f"Actual dropout fraction: {1 - dmask0.float().mean().item()}")
1061
+ if has_residual:
1062
+ if has_x1:
1063
+ residual_pt = (
1064
+ (x0_pt.float() * dmask0.float()) / (1 - dropout_p)
1065
+ + (x1_pt.float() * dmask1.float()) / (1 - dropout_p)
1066
+ + res_pt.float()
1067
+ ).to(dtype=residual_dtype)
1068
+ residual_ref = (
1069
+ (x0_ref * dmask0.float()) / (1 - dropout_p)
1070
+ + (x1_ref * dmask1.float()) / (1 - dropout_p)
1071
+ ) + res_ref
1072
+ else:
1073
+ residual_pt = ((x0_pt.float() * dmask0.float()) / (1 - dropout_p) + res_pt.float()).to(
1074
+ dtype=residual_dtype
1075
+ )
1076
+ residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p) + res_ref
1077
+ else:
1078
+ if has_x1:
1079
+ residual_pt = (
1080
+ (x0_pt.float() * dmask0.float()) / (1 - dropout_p)
1081
+ + (x1_pt.float() * dmask1.float()) / (1 - dropout_p)
1082
+ ).to(dtype=residual_dtype)
1083
+ residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p) + (
1084
+ x1_ref * dmask1.float()
1085
+ ) / (1 - dropout_p)
1086
+ else:
1087
+ residual_pt = ((x0_pt.float() * dmask0.float()) / (1 - dropout_p)).to(
1088
+ dtype=residual_dtype
1089
+ )
1090
+ residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p)
1091
+ if not is_rms_norm:
1092
+ out0_pt = F.layer_norm(
1093
+ residual_pt.to(dtype=weight_dtype), (hidden_size,), weight0_pt, bias0_pt, eps=epsilon
1094
+ ).to(dtype=input_dtype)
1095
+ out0_ref = F.layer_norm(residual_ref, (hidden_size,), weight0_ref, bias0_ref, eps=epsilon)
1096
+ if not tied_norm:
1097
+ out1_pt = F.layer_norm(
1098
+ residual_pt.to(dtype=weight_dtype),
1099
+ (hidden_size,),
1100
+ weight1_pt,
1101
+ bias1_pt,
1102
+ eps=epsilon,
1103
+ ).to(dtype=input_dtype)
1104
+ out1_ref = F.layer_norm(
1105
+ residual_ref, (hidden_size,), weight1_ref, bias1_ref, eps=epsilon
1106
+ )
1107
+ else:
1108
+ out0_pt = fused_rms_norm_affine(
1109
+ residual_pt.to(dtype=weight_dtype), weight0_pt, (hidden_size,), eps=epsilon
1110
+ ).to(dtype=input_dtype)
1111
+ out0_ref = fused_rms_norm_affine(residual_ref, weight0_ref, (hidden_size,), eps=epsilon)
1112
+ if not tied_norm:
1113
+ out1_pt = fused_rms_norm_affine(
1114
+ residual_pt.to(dtype=weight_dtype), weight1_pt, (hidden_size,), eps=epsilon
1115
+ ).to(dtype=input_dtype)
1116
+ out1_ref = fused_rms_norm_affine(residual_ref, weight1_ref, (hidden_size,), eps=epsilon)
1117
+
1118
+ assert (out0 - out0_ref).abs().max() <= 4 * (out0_pt - out0_ref).abs().max() + 1e-4
1119
+ if not tied_norm:
1120
+ assert (out1 - out1_ref).abs().max() <= 4 * (out1_pt - out1_ref).abs().max() + 1e-4
1121
+ assert (residual - residual_ref).abs().max() <= 4 * (
1122
+ residual_pt - residual_ref
1123
+ ).abs().max() + 1e-4
1124
+
1125
+ g0 = torch.randn_like(out0) / batch_size
1126
+ if tied_norm:
1127
+ (out0 * F.sigmoid(residual)).backward(g0)
1128
+ (out0_pt * F.sigmoid(residual_pt)).backward(g0)
1129
+ (out0_ref * F.sigmoid(residual_ref)).backward(g0)
1130
+ else:
1131
+ g1 = torch.randn_like(out1) / batch_size
1132
+ (out0 * F.sigmoid(residual) * g0 + out1 * g1).sum().backward()
1133
+ (out0_pt * F.sigmoid(residual_pt) * g0 + out1_pt * g1).sum().backward()
1134
+ (out0_ref * F.sigmoid(residual_ref) * g0 + out1_ref * g1).sum().backward()
1135
+ assert (x0.grad - x0_ref.grad).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad).abs().max() + 1e-4
1136
+ if has_x1:
1137
+ assert (x1.grad - x1_ref.grad).abs().max() <= 4 * (
1138
+ x1_pt.grad - x1_ref.grad
1139
+ ).abs().max() + 1e-4
1140
+ if has_residual:
1141
+ assert (res.grad - res_ref.grad).abs().max() <= 4 * (
1142
+ res_pt.grad - res_ref.grad
1143
+ ).abs().max() + 1e-4
1144
+ assert (weight0.grad - weight0_ref.grad).abs().max() <= 3 * (
1145
+ weight0_pt.grad - weight0_ref.grad
1146
+ ).abs().max() + 3e-5
1147
+ if not is_rms_norm:
1148
+ assert (bias0.grad - bias0_ref.grad).abs().max() <= 2 * (
1149
+ bias0_pt.grad - bias0_ref.grad
1150
+ ).abs().max() + 3e-5
1151
+ if not tied_norm:
1152
+ assert (weight1.grad - weight1_ref.grad).abs().max() <= 3 * (
1153
+ weight1_pt.grad - weight1_ref.grad
1154
+ ).abs().max() + 3e-5
1155
+ if not is_rms_norm:
1156
+ assert (bias1.grad - bias1_ref.grad).abs().max() <= 2 * (
1157
+ bias1_pt.grad - bias1_ref.grad
1158
+ ).abs().max() + 3e-5
1159
+
1160
+
1161
+ def test_dropout_layer_norm_randomness():
1162
+ hidden_size = 256
1163
+ dtype = torch.float32
1164
+ dropout_p = 0.1
1165
+ device = "cuda"
1166
+ # set seed
1167
+ torch.random.manual_seed(0)
1168
+ batch_size = 8
1169
+ seqlen = 512
1170
+ x0 = torch.randn(
1171
+ batch_size, seqlen, hidden_size, device=device, dtype=dtype, requires_grad=True
1172
+ )
1173
+ res = torch.randn_like(x0, dtype=dtype, requires_grad=True)
1174
+ model = DropoutAddLayerNorm(hidden_size, p=dropout_p, device=device, dtype=dtype)
1175
+ torch.random.manual_seed(42)
1176
+ _, dmask0 = dropout_add_layer_norm(
1177
+ x0, res, model.weight, model.bias, model.p, model.eps, return_dropout_mask=True
1178
+ )
1179
+ # Subsequent call should have a different dropout mask
1180
+ _, dmask1 = dropout_add_layer_norm(
1181
+ x0, res, model.weight, model.bias, model.p, model.eps, return_dropout_mask=True
1182
+ )
1183
+ torch.random.manual_seed(42)
1184
+ # Resetting the seed, should get the same dropout mask
1185
+ _, dmask2 = dropout_add_layer_norm(
1186
+ x0, res, model.weight, model.bias, model.p, model.eps, return_dropout_mask=True
1187
+ )
1188
+ assert not torch.equal(dmask0, dmask1)
1189
+ assert torch.equal(dmask0, dmask2)
flash-attention/tests/ops/test_fused_dense.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from functools import partial
3
+
4
+ import pytest
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from einops import rearrange
8
+ from flash_attn.ops.fused_dense import FusedDense, FusedMLP
9
+
10
+
11
+ @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
12
+ @pytest.mark.parametrize("return_residual", [False, True])
13
+ @pytest.mark.parametrize("has_bias", [True, False])
14
+ @pytest.mark.parametrize("out_features", [1024, 4096])
15
+ @pytest.mark.parametrize("in_features", [1024, 4096])
16
+ def test_fused_linear_bias(in_features, out_features, has_bias, return_residual, dtype):
17
+ device = "cuda"
18
+ rtol, atol = (3e-3, 1e-2) if dtype == torch.bfloat16 else (3e-3, 1e-3)
19
+ # set seed
20
+ torch.random.manual_seed(0)
21
+ batch_size = 8
22
+ seqlen = 512
23
+ x_pt = torch.randn(
24
+ batch_size, seqlen, in_features, device=device, dtype=dtype, requires_grad=True
25
+ )
26
+ x = x_pt.detach().clone().requires_grad_()
27
+ model_pt = torch.nn.Linear(in_features, out_features, bias=has_bias, device=device, dtype=dtype)
28
+ model = FusedDense(
29
+ in_features,
30
+ out_features,
31
+ bias=has_bias,
32
+ return_residual=return_residual,
33
+ device=device,
34
+ dtype=dtype,
35
+ )
36
+ with torch.no_grad():
37
+ model.weight.copy_(model_pt.weight)
38
+ if has_bias:
39
+ model.bias.copy_(model_pt.bias)
40
+ out_pt = model_pt(x_pt)
41
+ if not return_residual:
42
+ out = model(x)
43
+ else:
44
+ out, x_copy = model(x)
45
+ x_copy = (
46
+ x_copy[..., :out_features]
47
+ if out_features < in_features
48
+ else F.pad(x_copy, (0, out_features - in_features))
49
+ )
50
+ x_pt_copy = (
51
+ x_pt[..., :out_features]
52
+ if out_features < in_features
53
+ else F.pad(x_pt, (0, out_features - in_features))
54
+ )
55
+ # Just add some random function of the residual
56
+ out_pt = out_pt + F.gelu(x_pt_copy)
57
+ out = out + F.gelu(x_copy)
58
+
59
+ # with torch.no_grad():
60
+ # out_fl = F.linear(x_pt.float(), model.weight.float(), model.bias.float()).half()
61
+ assert torch.allclose(out, out_pt, rtol=rtol, atol=atol)
62
+
63
+ # If we don't divide by batch_size, the gradient gets a bit too large.
64
+ g = torch.randn_like(out) / 32
65
+ out_pt.backward(g)
66
+ out.backward(g)
67
+ assert torch.allclose(x.grad, x_pt.grad, rtol=rtol, atol=atol)
68
+ # The error for d_weight and d_bias is quite a bit higher
69
+ assert torch.allclose(model.weight.grad, model_pt.weight.grad, rtol=rtol, atol=atol * 10)
70
+ if has_bias:
71
+ assert torch.allclose(model.bias.grad, model_pt.bias.grad, rtol=rtol, atol=atol * 5)
72
+
73
+
74
+ @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
75
+ # @pytest.mark.parametrize('dtype', [torch.float16])
76
+ @pytest.mark.parametrize("heuristic", ["auto", -1])
77
+ # @pytest.mark.parametrize('heuristic', ['auto'])
78
+ @pytest.mark.parametrize("checkpoint_lvl", [0, 1, 2])
79
+ # @pytest.mark.parametrize('checkpoint_lvl', [1])
80
+ @pytest.mark.parametrize("return_residual", [False, True])
81
+ # @pytest.mark.parametrize('return_residual', [False])
82
+ @pytest.mark.parametrize("has_bias2", [True, False])
83
+ @pytest.mark.parametrize("has_bias1", [True, False])
84
+ # @pytest.mark.parametrize('has_bias2', [True])
85
+ # @pytest.mark.parametrize('has_bias1', [True])
86
+ @pytest.mark.parametrize("activation", ["gelu_approx", "relu"])
87
+ # @pytest.mark.parametrize('activation', ['relu'])
88
+ @pytest.mark.parametrize("out_features", [1024, 4096])
89
+ @pytest.mark.parametrize("in_features", [1024, 4096])
90
+ # @pytest.mark.parametrize('out_features', [4096])
91
+ # @pytest.mark.parametrize('in_features', [1024])
92
+ def test_fused_mlp(
93
+ in_features,
94
+ out_features,
95
+ activation,
96
+ has_bias1,
97
+ has_bias2,
98
+ return_residual,
99
+ checkpoint_lvl,
100
+ heuristic,
101
+ dtype,
102
+ ):
103
+ device = "cuda"
104
+ rtol, atol = (3e-3, 3e-2) if dtype == torch.bfloat16 else (3e-3, 1e-3)
105
+ # set seed
106
+ torch.random.manual_seed(0)
107
+ batch_size = 8
108
+ seqlen = 512
109
+ x_pt = torch.randn(
110
+ batch_size, seqlen, in_features, device=device, dtype=dtype, requires_grad=True
111
+ )
112
+ x = x_pt.detach().clone().requires_grad_()
113
+ model_pt_fc1 = torch.nn.Linear(
114
+ in_features, out_features, bias=has_bias1, device=device, dtype=dtype
115
+ )
116
+ model_pt_fc2 = torch.nn.Linear(
117
+ out_features, in_features, bias=has_bias2, device=device, dtype=dtype
118
+ )
119
+ model = FusedMLP(
120
+ in_features,
121
+ out_features,
122
+ in_features,
123
+ activation=activation,
124
+ bias1=has_bias1,
125
+ bias2=has_bias2,
126
+ return_residual=return_residual,
127
+ checkpoint_lvl=checkpoint_lvl,
128
+ heuristic=heuristic,
129
+ device=device,
130
+ dtype=dtype,
131
+ )
132
+ with torch.no_grad():
133
+ model.fc1.weight.copy_(model_pt_fc1.weight)
134
+ if has_bias1:
135
+ model.fc1.bias.copy_(model_pt_fc1.bias)
136
+ model.fc2.weight.copy_(model_pt_fc2.weight)
137
+ if has_bias2:
138
+ model.fc2.bias.copy_(model_pt_fc2.bias)
139
+ activation_fn = (
140
+ partial(F.gelu, approximate="tanh")
141
+ if activation == "gelu_approx"
142
+ else partial(F.relu, inplace=True)
143
+ )
144
+ out_pt = model_pt_fc2(activation_fn(model_pt_fc1(x_pt)))
145
+ if not return_residual:
146
+ out = model(x)
147
+ else:
148
+ out, x_copy = model(x)
149
+ # Just add some random function of the residual
150
+ out_pt = out_pt + F.gelu(x_pt)
151
+ out = out + F.gelu(x_copy)
152
+ assert torch.allclose(out, out_pt, rtol=rtol, atol=atol)
153
+
154
+ # If we don't divide by batch_size, the gradient gets a bit too large.
155
+ g = torch.randn_like(out) / 32
156
+ out_pt.backward(g)
157
+ out.backward(g)
158
+ # The error for relu is higher still
159
+ if activation == "relu":
160
+ atol = 1e-1 if dtype == torch.bfloat16 else 5e-2
161
+ assert torch.allclose(x.grad, x_pt.grad, rtol=rtol, atol=atol)
162
+ # The error for d_weight and d_bias is quite a bit higher
163
+ assert torch.allclose(
164
+ model.fc1.weight.grad, model_pt_fc1.weight.grad, rtol=rtol, atol=atol * 10
165
+ )
166
+ if has_bias1:
167
+ assert torch.allclose(model.fc1.bias.grad, model_pt_fc1.bias.grad, rtol=rtol, atol=atol * 5)
168
+ assert torch.allclose(
169
+ model.fc2.weight.grad, model_pt_fc2.weight.grad, rtol=rtol, atol=atol * 10
170
+ )
171
+ if has_bias2:
172
+ assert torch.allclose(model.fc2.bias.grad, model_pt_fc2.bias.grad, rtol=rtol, atol=atol * 5)
flash-attention/tests/ops/test_fused_dense_parallel.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run test with:
2
+ # torchrun --no_python --nproc_per_node=8 pytest -q -s tests/ops/test_fused_dense_parallel.py
3
+
4
+ import math
5
+
6
+ import pytest
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from apex.transformer import parallel_state, tensor_parallel
10
+ from flash_attn.ops.fused_dense import ColumnParallelLinear, FusedDense, FusedMLP, ParallelFusedMLP
11
+
12
+ is_sm8x = torch.cuda.get_device_capability("cuda")[0] >= 8
13
+
14
+
15
+ @pytest.mark.parametrize("dtype", [torch.float16] + ([torch.bfloat16] if is_sm8x else []))
16
+ # @pytest.mark.parametrize('dtype', [torch.bfloat16])
17
+ @pytest.mark.parametrize("world_size", [1, 2, 4, 8])
18
+ # @pytest.mark.parametrize('world_size', [2])
19
+ @pytest.mark.parametrize("sequence_parallel", [True, False])
20
+ # @pytest.mark.parametrize('sequence_parallel', [False])
21
+ @pytest.mark.parametrize("has_bias", [True, False])
22
+ # @pytest.mark.parametrize('has_bias', [False])
23
+ @pytest.mark.parametrize("out_features", [1024])
24
+ @pytest.mark.parametrize("in_features", [4096])
25
+ def test_fused_linear_bias(
26
+ in_features, out_features, has_bias, sequence_parallel, world_size, dtype
27
+ ):
28
+ assert out_features % world_size == 0
29
+ rtol, atol = (3e-3, 3e-2) if dtype == torch.bfloat16 else (3e-3, 3e-3)
30
+ if not torch.distributed.is_initialized():
31
+ torch.distributed.init_process_group(backend="nccl", init_method="env://")
32
+ device = f"cuda:{torch.distributed.get_rank()}"
33
+ assert world_size <= torch.distributed.get_world_size()
34
+ parallel_state.initialize_model_parallel(tensor_model_parallel_size_=world_size)
35
+ rank = parallel_state.get_tensor_model_parallel_rank()
36
+ # set seed
37
+ torch.random.manual_seed(0)
38
+ batch_size = 2
39
+ seqlen = 512
40
+ assert batch_size * seqlen % world_size == 0
41
+ x_pt = torch.randn(
42
+ batch_size * seqlen, in_features, device=device, dtype=dtype, requires_grad=True
43
+ )
44
+ if sequence_parallel:
45
+ x = (
46
+ tensor_parallel.scatter_to_sequence_parallel_region(x_pt)
47
+ .detach()
48
+ .clone()
49
+ .requires_grad_()
50
+ )
51
+ else:
52
+ x = x_pt.detach().clone().requires_grad_()
53
+
54
+ model_pt = torch.nn.Linear(in_features, out_features, bias=has_bias, device=device, dtype=dtype)
55
+ partition_out_features = out_features // world_size
56
+ model = ColumnParallelLinear(
57
+ in_features,
58
+ out_features,
59
+ parallel_state.get_tensor_model_parallel_group(),
60
+ bias=has_bias,
61
+ sequence_parallel=sequence_parallel,
62
+ device=device,
63
+ dtype=dtype,
64
+ )
65
+ with torch.no_grad():
66
+ model.weight.copy_(
67
+ model_pt.weight[rank * partition_out_features : (rank + 1) * partition_out_features]
68
+ )
69
+ if has_bias:
70
+ model.bias.copy_(
71
+ model_pt.bias[rank * partition_out_features : (rank + 1) * partition_out_features]
72
+ )
73
+
74
+ out = model(x)
75
+ out_pt = model_pt(x_pt)
76
+ assert torch.allclose(
77
+ out,
78
+ out_pt[:, rank * partition_out_features : (rank + 1) * partition_out_features],
79
+ rtol=rtol,
80
+ atol=atol,
81
+ )
82
+
83
+ # If we don't divide by batch_size, the gradient gets a bit too large.
84
+ g = torch.randn_like(out_pt) / 32
85
+ out_pt.backward(g)
86
+ out.backward(g[:, rank * partition_out_features : (rank + 1) * partition_out_features])
87
+ parallel_state.destroy_model_parallel()
88
+
89
+ partition_batch_dim = batch_size * seqlen // world_size
90
+ assert torch.allclose(
91
+ x.grad,
92
+ x_pt.grad[rank * partition_batch_dim : (rank + 1) * partition_batch_dim]
93
+ if sequence_parallel
94
+ else x_pt.grad,
95
+ rtol=rtol,
96
+ atol=atol,
97
+ )
98
+ # The error for d_weight and d_bias is quite a bit higher
99
+ assert torch.allclose(
100
+ model.weight.grad,
101
+ model_pt.weight.grad[rank * partition_out_features : (rank + 1) * partition_out_features],
102
+ rtol=rtol,
103
+ atol=atol * 10,
104
+ )
105
+ if has_bias:
106
+ assert torch.allclose(
107
+ model.bias.grad,
108
+ model_pt.bias.grad[rank * partition_out_features : (rank + 1) * partition_out_features],
109
+ rtol=rtol,
110
+ atol=atol * 5,
111
+ )
112
+
113
+
114
+ @pytest.mark.parametrize("dtype", [torch.float16] + ([torch.bfloat16] if is_sm8x else []))
115
+ # @pytest.mark.parametrize('dtype', [torch.bfloat16])
116
+ @pytest.mark.parametrize("world_size", [1, 2, 4, 8])
117
+ # @pytest.mark.parametrize('world_size', [2])
118
+ @pytest.mark.parametrize("sequence_parallel", [True, False])
119
+ # @pytest.mark.parametrize('sequence_parallel', [False])
120
+ @pytest.mark.parametrize("has_bias2", [True, False])
121
+ # @pytest.mark.parametrize('has_bias2', [True])
122
+ @pytest.mark.parametrize("out_features", [4096])
123
+ @pytest.mark.parametrize("in_features", [1024])
124
+ def test_fused_mlp(in_features, out_features, has_bias2, sequence_parallel, world_size, dtype):
125
+ assert out_features % world_size == 0
126
+ rtol, atol = (3e-3, 3e-2) if dtype == torch.bfloat16 else (3e-3, 3e-3)
127
+ if not torch.distributed.is_initialized():
128
+ torch.distributed.init_process_group(backend="nccl", init_method="env://")
129
+ device = f"cuda:{torch.distributed.get_rank()}"
130
+ assert world_size <= torch.distributed.get_world_size()
131
+ parallel_state.initialize_model_parallel(tensor_model_parallel_size_=world_size)
132
+ rank = parallel_state.get_tensor_model_parallel_rank()
133
+ # set seed
134
+ torch.random.manual_seed(0)
135
+ batch_size = 2
136
+ seqlen = 512
137
+ assert batch_size * seqlen % world_size == 0
138
+ x_pt = torch.randn(
139
+ batch_size * seqlen, in_features, device=device, dtype=dtype, requires_grad=True
140
+ )
141
+ # We need to generate g here so that all processes get the same gradient,
142
+ # as rank 0 will have an extra bias that changes the RNG.
143
+ # If we don't divide by batch_size, the gradient gets a bit too large.
144
+ g = torch.randn_like(x_pt) / 32
145
+ if sequence_parallel:
146
+ x = (
147
+ tensor_parallel.scatter_to_sequence_parallel_region(x_pt)
148
+ .detach()
149
+ .clone()
150
+ .requires_grad_()
151
+ )
152
+ else:
153
+ x = x_pt.detach().clone().requires_grad_()
154
+
155
+ model_pt_fc1 = torch.nn.Linear(in_features, out_features, device=device, dtype=dtype)
156
+ model_pt_fc2 = torch.nn.Linear(
157
+ out_features, in_features, bias=has_bias2, device=device, dtype=dtype
158
+ )
159
+ partition_out_features = out_features // world_size
160
+ partition_in_features = in_features // world_size
161
+ model = ParallelFusedMLP(
162
+ in_features,
163
+ out_features,
164
+ in_features,
165
+ process_group=parallel_state.get_tensor_model_parallel_group(),
166
+ bias2=has_bias2 and rank == 0,
167
+ sequence_parallel=sequence_parallel,
168
+ device=device,
169
+ dtype=dtype,
170
+ )
171
+
172
+ with torch.no_grad():
173
+ model.fc1.weight.copy_(
174
+ model_pt_fc1.weight[rank * partition_out_features : (rank + 1) * partition_out_features]
175
+ )
176
+ model.fc1.bias.copy_(
177
+ model_pt_fc1.bias[rank * partition_out_features : (rank + 1) * partition_out_features]
178
+ )
179
+ model.fc2.weight.copy_(
180
+ model_pt_fc2.weight[
181
+ :, rank * partition_out_features : (rank + 1) * partition_out_features
182
+ ]
183
+ )
184
+ if has_bias2 and rank == 0:
185
+ model.fc2.bias.copy_(model_pt_fc2.bias)
186
+
187
+ out = model(x)
188
+ out_pt = model_pt_fc2(F.gelu(model_pt_fc1(x_pt), approximate="tanh"))
189
+ partition_batch_dim = batch_size * seqlen // world_size
190
+ assert torch.allclose(
191
+ out,
192
+ out_pt[rank * partition_batch_dim : (rank + 1) * partition_batch_dim]
193
+ if sequence_parallel
194
+ else out_pt,
195
+ rtol=rtol,
196
+ atol=atol,
197
+ )
198
+
199
+ out_pt.backward(g)
200
+ out.backward(
201
+ g[rank * partition_batch_dim : (rank + 1) * partition_batch_dim] if sequence_parallel else g
202
+ )
203
+ parallel_state.destroy_model_parallel()
204
+
205
+ assert torch.allclose(
206
+ x.grad,
207
+ x_pt.grad[rank * partition_batch_dim : (rank + 1) * partition_batch_dim]
208
+ if sequence_parallel
209
+ else x_pt.grad,
210
+ rtol=rtol,
211
+ atol=atol,
212
+ )
213
+ # The error for d_weight and d_bias is quite a bit higher
214
+ assert torch.allclose(
215
+ model.fc1.weight.grad,
216
+ model_pt_fc1.weight.grad[
217
+ rank * partition_out_features : (rank + 1) * partition_out_features
218
+ ],
219
+ rtol=rtol,
220
+ atol=atol * 10,
221
+ )
222
+ assert torch.allclose(
223
+ model.fc1.bias.grad,
224
+ model_pt_fc1.bias.grad[rank * partition_out_features : (rank + 1) * partition_out_features],
225
+ rtol=rtol,
226
+ atol=atol * 5,
227
+ )
228
+ assert torch.allclose(
229
+ model.fc2.weight.grad,
230
+ model_pt_fc2.weight.grad[
231
+ :, rank * partition_out_features : (rank + 1) * partition_out_features
232
+ ],
233
+ rtol=rtol,
234
+ atol=atol * 10,
235
+ )
236
+ if has_bias2 and rank == 0:
237
+ assert torch.allclose(model.fc2.bias.grad, model_pt_fc2.bias.grad, rtol=rtol, atol=atol * 5)