diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
deleted file mode 100644
index 92211ea..0000000
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ /dev/null
@@ -1,23 +0,0 @@
----
-name: Bug report
-about: Create a report to help us improve
-title: "[BUG]"
-labels: ''
-assignees: ''
-
----
-
-**Describe the bug**
-A clear and concise description of what the bug is.
-
-**To Reproduce**
-Steps to reproduce the behavior.
-
-**Expected behavior**
-A clear and concise description of what you expected to happen.
-
-**Screenshots**
-If applicable, add screenshots to help explain your problem.
-
-**Additional context**
-Add any other context about the problem here.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
deleted file mode 100644
index bbcbbe7..0000000
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ /dev/null
@@ -1,20 +0,0 @@
----
-name: Feature request
-about: Suggest an idea for this project
-title: ''
-labels: ''
-assignees: ''
-
----
-
-**Is your feature request related to a problem? Please describe.**
-A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
-
-**Describe the solution you'd like**
-A clear and concise description of what you want to happen.
-
-**Describe alternatives you've considered**
-A clear and concise description of any alternative solutions or features you've considered.
-
-**Additional context**
-Add any other context or screenshots about the feature request here.
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
deleted file mode 100644
index 22706e8..0000000
--- a/.github/workflows/stale.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-name: "Mark and close stale issues"
-on:
- workflow_dispatch:
- schedule:
- - cron: "0 0 * * *"
-
-jobs:
- stale:
- if: ${{ github.repository == 'deepseek-ai/DeepSeek-V3' }}
- runs-on: ubuntu-latest
- steps:
- - name: "Mark and close stale issues"
- uses: actions/stale@v9
- with:
- days-before-issue-stale: 30
- days-before-issue-close: 14
- stale-issue-label: "stale"
- close-issue-label: "closed-as-stale"
- exempt-issue-labels: |
- pinned
- security
- stale-issue-message: >
- This issue has been automatically marked as stale because it has not had
- recent activity. It will be closed if no further activity occurs. If you
- believe this issue is still relevant, please leave a comment to keep it open.
- Thank you for your contributions!
- close-issue-message: false
- days-before-pr-stale: -1
- days-before-pr-close: -1
- repo-token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index 68f1d27..0000000
--- a/.gitignore
+++ /dev/null
@@ -1,172 +0,0 @@
-# Byte-compiled / optimized / DLL files
-__pycache__/
-*.py[cod]
-*$py.class
-
-# C extensions
-*.so
-
-# Distribution / packaging
-.Python
-build/
-develop-eggs/
-dist/
-downloads/
-eggs/
-.eggs/
-lib/
-lib64/
-parts/
-sdist/
-var/
-wheels/
-share/python-wheels/
-*.egg-info/
-.installed.cfg
-*.egg
-MANIFEST
-
-# PyInstaller
-# Usually these files are written by a python script from a template
-# before PyInstaller builds the exe, so as to inject date/other infos into it.
-*.manifest
-*.spec
-
-# Installer logs
-pip-log.txt
-pip-delete-this-directory.txt
-
-# Unit test / coverage reports
-htmlcov/
-.tox/
-.nox/
-.coverage
-.coverage.*
-.cache
-nosetests.xml
-coverage.xml
-*.cover
-*.py,cover
-.hypothesis/
-.pytest_cache/
-cover/
-
-# Translations
-*.mo
-*.pot
-
-# Django stuff:
-*.log
-local_settings.py
-db.sqlite3
-db.sqlite3-journal
-
-# Flask stuff:
-instance/
-.webassets-cache
-
-# Scrapy stuff:
-.scrapy
-
-# Sphinx documentation
-docs/_build/
-
-# PyBuilder
-.pybuilder/
-target/
-
-# Jupyter Notebook
-.ipynb_checkpoints
-
-# IPython
-profile_default/
-ipython_config.py
-
-# pyenv
-# For a library or package, you might want to ignore these files since the code is
-# intended to run in multiple environments; otherwise, check them in:
-# .python-version
-
-# pipenv
-# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
-# However, in case of collaboration, if having platform-specific dependencies or dependencies
-# having no cross-platform support, pipenv may install dependencies that don't work, or not
-# install all needed dependencies.
-#Pipfile.lock
-
-# UV
-# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
-# This is especially recommended for binary packages to ensure reproducibility, and is more
-# commonly ignored for libraries.
-#uv.lock
-
-# poetry
-# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
-# This is especially recommended for binary packages to ensure reproducibility, and is more
-# commonly ignored for libraries.
-# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
-#poetry.lock
-
-# pdm
-# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
-#pdm.lock
-# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
-# in version control.
-# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
-.pdm.toml
-.pdm-python
-.pdm-build/
-
-# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
-__pypackages__/
-
-# Celery stuff
-celerybeat-schedule
-celerybeat.pid
-
-# SageMath parsed files
-*.sage.py
-
-# Environments
-.env
-.venv
-env/
-venv/
-ENV/
-env.bak/
-venv.bak/
-
-# Spyder project settings
-.spyderproject
-.spyproject
-
-# Rope project settings
-.ropeproject
-
-# mkdocs documentation
-/site
-
-# mypy
-.mypy_cache/
-.dmypy.json
-dmypy.json
-
-# Pyre type checker
-.pyre/
-
-# pytype static type analyzer
-.pytype/
-
-# Cython debug symbols
-cython_debug/
-
-# PyCharm
-# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
-# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
-# and can be added to the global gitignore or merged into this file. For a more nuclear
-# option (not recommended) you can uncomment the following to ignore the entire idea folder.
-#.idea/
-
-.vscode/*
-
-.DS_Store
\ No newline at end of file
diff --git a/LICENSE-CODE b/LICENSE-CODE
deleted file mode 100644
index d42fae9..0000000
--- a/LICENSE-CODE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2023 DeepSeek
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
\ No newline at end of file
diff --git a/LICENSE-MODEL b/LICENSE-MODEL
deleted file mode 100644
index ac09290..0000000
--- a/LICENSE-MODEL
+++ /dev/null
@@ -1,91 +0,0 @@
-DEEPSEEK LICENSE AGREEMENT
-
-Version 1.0, 23 October 2023
-
-Copyright (c) 2023 DeepSeek
-
-Section I: PREAMBLE
-
-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.
-
-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.
-
-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.
-
-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.
-
-This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
-
-NOW THEREFORE, You and DeepSeek agree as follows:
-
-1. Definitions
-"License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
-"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.
-"Output" means the results of operating a Model as embodied in informational content resulting therefrom.
-"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.
-"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.
-"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.
-"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.
-"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.
-"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.
-"Third Parties" means individuals or legal entities that are not under common control with DeepSeek or You.
-
-Section II: INTELLECTUAL PROPERTY RIGHTS
-
-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.
-
-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.
-
-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.
-
-
-Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
-
-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:
-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.
-b. You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
-c. You must cause any modified files to carry prominent notices stating that You changed the files;
-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.
-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.
-
-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).
-
-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.
-
-Section IV: OTHER PROVISIONS
-
-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.
-
-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.
-
-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.
-
-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.
-
-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.
-
-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.
-
-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.
-
-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.
-
-END OF TERMS AND CONDITIONS
-
-Attachment A
-
-Use Restrictions
-
-You agree not to use the Model or Derivatives of the Model:
-
-- 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;
-- For military use in any way;
-- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
-- To generate or disseminate verifiably false information and/or content with the purpose of harming others;
-- To generate or disseminate inappropriate content subject to applicable regulatory requirements;
-- To generate or disseminate personal identifiable information without due authorization or for unreasonable use;
-- To defame, disparage or otherwise harass others;
-- For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
-- 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;
-- 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;
-- For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories.
\ No newline at end of file
diff --git a/README.md b/README.md
deleted file mode 100644
index a67a28d..0000000
--- a/README.md
+++ /dev/null
@@ -1,356 +0,0 @@
-
-
-
-
-
-

-
-
-
-
-## Table of Contents
-
-1. [Introduction](#1-introduction)
-2. [Model Summary](#2-model-summary)
-3. [Model Downloads](#3-model-downloads)
-4. [Evaluation Results](#4-evaluation-results)
-5. [Chat Website & API Platform](#5-chat-website--api-platform)
-6. [How to Run Locally](#6-how-to-run-locally)
-7. [License](#7-license)
-8. [Citation](#8-citation)
-9. [Contact](#9-contact)
-
-
-## 1. Introduction
-
-We present DeepSeek-V3, a strong Mixture-of-Experts (MoE) language model with 671B total parameters with 37B activated for each token.
-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.
-Furthermore, DeepSeek-V3 pioneers an auxiliary-loss-free strategy for load balancing and sets a multi-token prediction training objective for stronger performance.
-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.
-Comprehensive evaluations reveal that DeepSeek-V3 outperforms other open-source models and achieves performance comparable to leading closed-source models.
-Despite its excellent performance, DeepSeek-V3 requires only 2.788M H800 GPU hours for its full training.
-In addition, its training process is remarkably stable.
-Throughout the entire training process, we did not experience any irrecoverable loss spikes or perform any rollbacks.
-
-
-
-
-## 2. Model Summary
-
----
-
-**Architecture: Innovative Load Balancing Strategy and Training Objective**
-
-- 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.
-- We investigate a Multi-Token Prediction (MTP) objective and prove it beneficial to model performance.
- It can also be used for speculative decoding for inference acceleration.
-
----
-
-**Pre-Training: Towards Ultimate Training Efficiency**
-
-- 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.
-- Through co-design of algorithms, frameworks, and hardware, we overcome the communication bottleneck in cross-node MoE training, nearly achieving full computation-communication overlap.
- This significantly enhances our training efficiency and reduces the training costs, enabling us to further scale up the model size without additional overhead.
-- 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.
-
----
-
-**Post-Training: Knowledge Distillation from DeepSeek-R1**
-
-- 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.
-
----
-
-
-## 3. Model Downloads
-
-
-
-| **Model** | **#Total Params** | **#Activated Params** | **Context Length** | **Download** |
-| :------------: | :------------: | :------------: | :------------: | :------------: |
-| DeepSeek-V3-Base | 671B | 37B | 128K | [🤗 Hugging Face](https://huggingface.co/deepseek-ai/DeepSeek-V3-Base) |
-| DeepSeek-V3 | 671B | 37B | 128K | [🤗 Hugging Face](https://huggingface.co/deepseek-ai/DeepSeek-V3) |
-
-
-
-> [!NOTE]
-> The total size of DeepSeek-V3 models on Hugging Face is 685B, which includes 671B of the Main Model weights and 14B of the Multi-Token Prediction (MTP) Module weights.
-
-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).
-
-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.
-
-## 4. Evaluation Results
-### Base Model
-#### Standard Benchmarks
-
-
-
-
-| | Benchmark (Metric) | # Shots | DeepSeek-V2 | Qwen2.5 72B | LLaMA3.1 405B | DeepSeek-V3 |
-|---|-------------------|----------|--------|-------------|---------------|---------|
-| | Architecture | - | MoE | Dense | Dense | MoE |
-| | # Activated Params | - | 21B | 72B | 405B | 37B |
-| | # Total Params | - | 236B | 72B | 405B | 671B |
-| English | Pile-test (BPB) | - | 0.606 | 0.638 | **0.542** | 0.548 |
-| | BBH (EM) | 3-shot | 78.8 | 79.8 | 82.9 | **87.5** |
-| | MMLU (Acc.) | 5-shot | 78.4 | 85.0 | 84.4 | **87.1** |
-| | MMLU-Redux (Acc.) | 5-shot | 75.6 | 83.2 | 81.3 | **86.2** |
-| | MMLU-Pro (Acc.) | 5-shot | 51.4 | 58.3 | 52.8 | **64.4** |
-| | DROP (F1) | 3-shot | 80.4 | 80.6 | 86.0 | **89.0** |
-| | ARC-Easy (Acc.) | 25-shot | 97.6 | 98.4 | 98.4 | **98.9** |
-| | ARC-Challenge (Acc.) | 25-shot | 92.2 | 94.5 | **95.3** | **95.3** |
-| | HellaSwag (Acc.) | 10-shot | 87.1 | 84.8 | **89.2** | 88.9 |
-| | PIQA (Acc.) | 0-shot | 83.9 | 82.6 | **85.9** | 84.7 |
-| | WinoGrande (Acc.) | 5-shot | **86.3** | 82.3 | 85.2 | 84.9 |
-| | RACE-Middle (Acc.) | 5-shot | 73.1 | 68.1 | **74.2** | 67.1 |
-| | RACE-High (Acc.) | 5-shot | 52.6 | 50.3 | **56.8** | 51.3 |
-| | TriviaQA (EM) | 5-shot | 80.0 | 71.9 | 82.7 | **82.9** |
-| | NaturalQuestions (EM) | 5-shot | 38.6 | 33.2 | **41.5** | 40.0 |
-| | AGIEval (Acc.) | 0-shot | 57.5 | 75.8 | 60.6 | **79.6** |
-| Code | HumanEval (Pass@1) | 0-shot | 43.3 | 53.0 | 54.9 | **65.2** |
-| | MBPP (Pass@1) | 3-shot | 65.0 | 72.6 | 68.4 | **75.4** |
-| | LiveCodeBench-Base (Pass@1) | 3-shot | 11.6 | 12.9 | 15.5 | **19.4** |
-| | CRUXEval-I (Acc.) | 2-shot | 52.5 | 59.1 | 58.5 | **67.3** |
-| | CRUXEval-O (Acc.) | 2-shot | 49.8 | 59.9 | 59.9 | **69.8** |
-| Math | GSM8K (EM) | 8-shot | 81.6 | 88.3 | 83.5 | **89.3** |
-| | MATH (EM) | 4-shot | 43.4 | 54.4 | 49.0 | **61.6** |
-| | MGSM (EM) | 8-shot | 63.6 | 76.2 | 69.9 | **79.8** |
-| | CMath (EM) | 3-shot | 78.7 | 84.5 | 77.3 | **90.7** |
-| Chinese | CLUEWSC (EM) | 5-shot | 82.0 | 82.5 | **83.0** | 82.7 |
-| | C-Eval (Acc.) | 5-shot | 81.4 | 89.2 | 72.5 | **90.1** |
-| | CMMLU (Acc.) | 5-shot | 84.0 | **89.5** | 73.7 | 88.8 |
-| | CMRC (EM) | 1-shot | **77.4** | 75.8 | 76.0 | 76.3 |
-| | C3 (Acc.) | 0-shot | 77.4 | 76.7 | **79.7** | 78.6 |
-| | CCPM (Acc.) | 0-shot | **93.0** | 88.5 | 78.6 | 92.0 |
-| Multilingual | MMMLU-non-English (Acc.) | 5-shot | 64.0 | 74.8 | 73.8 | **79.4** |
-
-
-
-> [!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.
-> For more evaluation details, please check our paper.
-
-#### Context Window
-
-
-
-
-Evaluation results on the ``Needle In A Haystack`` (NIAH) tests. DeepSeek-V3 performs well across all context window lengths up to **128K**.
-
-### Chat Model
-#### Standard Benchmarks (Models larger than 67B)
-
-
-| | **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** |
-|---|---------------------|---------------------|----------------------|---------------------|----------------------|---------------------------|----------------|----------------|
-| | Architecture | MoE | MoE | Dense | Dense | - | - | MoE |
-| | # Activated Params | 21B | 21B | 72B | 405B | - | - | 37B |
-| | # Total Params | 236B | 236B | 72B | 405B | - | - | 671B |
-| English | MMLU (EM) | 78.2 | 80.6 | 85.3 | **88.6** | **88.3** | 87.2 | **88.5** |
-| | MMLU-Redux (EM) | 77.9 | 80.3 | 85.6 | 86.2 | **88.9** | 88.0 | **89.1** |
-| | MMLU-Pro (EM) | 58.5 | 66.2 | 71.6 | 73.3 | **78.0** | 72.6 | 75.9 |
-| | DROP (3-shot F1) | 83.0 | 87.8 | 76.7 | 88.7 | 88.3 | 83.7 | **91.6** |
-| | IF-Eval (Prompt Strict) | 57.7 | 80.6 | 84.1 | 86.0 | **86.5** | 84.3 | 86.1 |
-| | GPQA-Diamond (Pass@1) | 35.3 | 41.3 | 49.0 | 51.1 | **65.0** | 49.9 | 59.1 |
-| | SimpleQA (Correct) | 9.0 | 10.2 | 9.1 | 17.1 | 28.4 | **38.2** | 24.9 |
-| | FRAMES (Acc.) | 66.9 | 65.4 | 69.8 | 70.0 | 72.5 | **80.5** | 73.3 |
-| | LongBench v2 (Acc.) | 31.6 | 35.4 | 39.4 | 36.1 | 41.0 | 48.1 | **48.7** |
-| Code | HumanEval-Mul (Pass@1) | 69.3 | 77.4 | 77.3 | 77.2 | 81.7 | 80.5 | **82.6** |
-| | LiveCodeBench (Pass@1-COT) | 18.8 | 29.2 | 31.1 | 28.4 | 36.3 | 33.4 | **40.5** |
-| | LiveCodeBench (Pass@1) | 20.3 | 28.4 | 28.7 | 30.1 | 32.8 | 34.2 | **37.6** |
-| | Codeforces (Percentile) | 17.5 | 35.6 | 24.8 | 25.3 | 20.3 | 23.6 | **51.6** |
-| | SWE Verified (Resolved) | - | 22.6 | 23.8 | 24.5 | **50.8** | 38.8 | 42.0 |
-| | Aider-Edit (Acc.) | 60.3 | 71.6 | 65.4 | 63.9 | **84.2** | 72.9 | 79.7 |
-| | Aider-Polyglot (Acc.) | - | 18.2 | 7.6 | 5.8 | 45.3 | 16.0 | **49.6** |
-| Math | AIME 2024 (Pass@1) | 4.6 | 16.7 | 23.3 | 23.3 | 16.0 | 9.3 | **39.2** |
-| | MATH-500 (EM) | 56.3 | 74.7 | 80.0 | 73.8 | 78.3 | 74.6 | **90.2** |
-| | CNMO 2024 (Pass@1) | 2.8 | 10.8 | 15.9 | 6.8 | 13.1 | 10.8 | **43.2** |
-| Chinese | CLUEWSC (EM) | 89.9 | 90.4 | **91.4** | 84.7 | 85.4 | 87.9 | 90.9 |
-| | C-Eval (EM) | 78.6 | 79.5 | 86.1 | 61.5 | 76.7 | 76.0 | **86.5** |
-| | C-SimpleQA (Correct) | 48.5 | 54.1 | 48.4 | 50.4 | 51.3 | 59.3 | **64.8** |
-
-
-
-> [!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.
-
-
-#### Open Ended Generation Evaluation
-
-
-
-
-
-| Model | Arena-Hard | AlpacaEval 2.0 |
-|-------|------------|----------------|
-| DeepSeek-V2.5-0905 | 76.2 | 50.5 |
-| Qwen2.5-72B-Instruct | 81.2 | 49.1 |
-| LLaMA-3.1 405B | 69.3 | 40.5 |
-| GPT-4o-0513 | 80.4 | 51.1 |
-| Claude-Sonnet-3.5-1022 | 85.2 | 52.0 |
-| DeepSeek-V3 | **85.5** | **70.0** |
-
-
-
-> [!NOTE]
-> English open-ended conversation evaluations. For AlpacaEval 2.0, we use the length-controlled win rate as the metric.
-
-
-## 5. Chat Website & API Platform
-You can chat with DeepSeek-V3 on DeepSeek's official website: [chat.deepseek.com](https://chat.deepseek.com/sign_in)
-
-We also provide OpenAI-Compatible API at DeepSeek Platform: [platform.deepseek.com](https://platform.deepseek.com/)
-
-## 6. How to Run Locally
-
-DeepSeek-V3 can be deployed locally using the following hardware and open-source community software:
-
-1. **DeepSeek-Infer Demo**: We provide a simple and lightweight demo for FP8 and BF16 inference.
-2. **SGLang**: Fully support the DeepSeek-V3 model in both BF16 and FP8 inference modes, with Multi-Token Prediction [coming soon](https://github.com/sgl-project/sglang/issues/2591).
-3. **LMDeploy**: Enables efficient FP8 and BF16 inference for local and cloud deployment.
-4. **TensorRT-LLM**: Currently supports BF16 inference and INT4/8 quantization, with FP8 support coming soon.
-5. **vLLM**: Support DeepSeek-V3 model with FP8 and BF16 modes for tensor parallelism and pipeline parallelism.
-6. **AMD GPU**: Enables running the DeepSeek-V3 model on AMD GPUs via SGLang in both BF16 and FP8 modes.
-7. **Huawei Ascend NPU**: Supports running DeepSeek-V3 on Huawei Ascend devices.
-
-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.
-
-Here is an example of converting FP8 weights to BF16:
-
-```shell
-cd inference
-python fp8_cast_bf16.py --input-fp8-hf-path /path/to/fp8_weights --output-bf16-hf-path /path/to/bf16_weights
-```
-
-> [!NOTE]
-> Hugging Face's Transformers has not been directly supported yet.
-
-### 6.1 Inference with DeepSeek-Infer Demo (example only)
-
-#### System Requirements
-
-> [!NOTE]
-> Linux with Python 3.10 only. Mac and Windows are not supported.
-
-Dependencies:
-```pip-requirements
-torch==2.4.1
-triton==3.0.0
-transformers==4.46.3
-safetensors==0.4.5
-```
-#### Model Weights & Demo Code Preparation
-
-First, clone our DeepSeek-V3 GitHub repository:
-
-```shell
-git clone https://github.com/deepseek-ai/DeepSeek-V3.git
-```
-
-Navigate to the `inference` folder and install dependencies listed in `requirements.txt`. Easiest way is to use a package manager like `conda` or `uv` to create a new virtual environment and install the dependencies.
-
-```shell
-cd DeepSeek-V3/inference
-pip install -r requirements.txt
-```
-
-Download the model weights from Hugging Face, and put them into `/path/to/DeepSeek-V3` folder.
-
-#### Model Weights Conversion
-
-Convert Hugging Face model weights to a specific format:
-
-```shell
-python convert.py --hf-ckpt-path /path/to/DeepSeek-V3 --save-path /path/to/DeepSeek-V3-Demo --n-experts 256 --model-parallel 16
-```
-
-#### Run
-
-Then you can chat with DeepSeek-V3:
-
-```shell
-torchrun --nnodes 2 --nproc-per-node 8 --node-rank $RANK --master-addr $ADDR generate.py --ckpt-path /path/to/DeepSeek-V3-Demo --config configs/config_671B.json --interactive --temperature 0.7 --max-new-tokens 200
-```
-
-Or batch inference on a given file:
-
-```shell
-torchrun --nnodes 2 --nproc-per-node 8 --node-rank $RANK --master-addr $ADDR generate.py --ckpt-path /path/to/DeepSeek-V3-Demo --config configs/config_671B.json --input-file $FILE
-```
-
-### 6.2 Inference with SGLang (recommended)
-
-[SGLang](https://github.com/sgl-project/sglang) currently supports [MLA optimizations](https://lmsys.org/blog/2024-09-04-sglang-v0-3/#deepseek-multi-head-latent-attention-mla-throughput-optimizations), [DP Attention](https://lmsys.org/blog/2024-12-04-sglang-v0-4/#data-parallelism-attention-for-deepseek-models), FP8 (W8A8), FP8 KV Cache, and Torch Compile, delivering state-of-the-art latency and throughput performance among open-source frameworks.
-
-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.
-
-SGLang also supports [multi-node tensor parallelism](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-2-h208), enabling you to run this model on multiple network-connected machines.
-
-Multi-Token Prediction (MTP) is in development, and progress can be tracked in the [optimization plan](https://github.com/sgl-project/sglang/issues/2591).
-
-Here are the launch instructions from the SGLang team: https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3
-
-### 6.3 Inference with LMDeploy (recommended)
-[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.
-
-For comprehensive step-by-step instructions on running DeepSeek-V3 with LMDeploy, please refer to here: https://github.com/InternLM/lmdeploy/issues/2960
-
-
-### 6.4 Inference with TRT-LLM (recommended)
-
-[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.
-
-
-### 6.5 Inference with vLLM (recommended)
-
-[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.
-
-### 6.6 Recommended Inference Functionality with AMD GPUs
-
-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).
-
-### 6.7 Recommended Inference Functionality with Huawei Ascend NPUs
-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).
-
-
-## 7. License
-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.
-
-## 8. Citation
-```
-@misc{deepseekai2024deepseekv3technicalreport,
- title={DeepSeek-V3 Technical Report},
- author={DeepSeek-AI},
- year={2024},
- eprint={2412.19437},
- archivePrefix={arXiv},
- primaryClass={cs.CL},
- url={https://arxiv.org/abs/2412.19437},
-}
-```
-
-## 9. Contact
-If you have any questions, please raise an issue or contact us at [service@deepseek.com](service@deepseek.com).
diff --git a/README_WEIGHTS.md b/README_WEIGHTS.md
deleted file mode 100644
index 5679083..0000000
--- a/README_WEIGHTS.md
+++ /dev/null
@@ -1,94 +0,0 @@
-# DeepSeek-V3 Weight File Documentation
-
-## New Fields in `config.json`
-
-- **model_type**: Specifies the model type, which is updated to `deepseek_v3` in this release.
-- **num_nextn_predict_layers**: Indicates the number of Multi-Token Prediction (MTP) Modules. The open-sourced V3 weights include **1 MTP Module** .
-- **quantization_config**: Describes the configuration for FP8 quantization.
-
----
-
-## Weight Structure Overview
-
-The DeepSeek-V3 weight file consists of two main components: **Main Model Weights** and **MTP Modules**.
-
-### 1. Main Model Weights
-
-- **Composition**:
- - Input/output embedding layers and a complete set of 61 Transformer hidden layers.
-- **Parameter Count**:
- - Total parameters: **671B**
- - Activation parameters: **36.7B** (including 0.9B for Embedding and 0.9B for the output Head).
-
-#### Structural Details
-
-- **Embedding Layer**:
- - `model.embed_tokens.weight`
-- **Transformer Hidden Layers**:
- - `model.layers.0` to `model.layers.60`, totaling `num_hidden_layers` layers.
-- **Output Layer**:
- - `model.norm.weight`
- - `lm_head.weight`
-
-### 2. Multi-Token Prediction (MTP) Modules
-
-- **Composition**:
- - Additional MTP Modules defined by the `num_nextn_predict_layers` field. In this model, the value is set to 1.
-- **Parameter Count**:
- - Parameters: **11.5B unique parameters**, excluding the shared 0.9B Embedding and 0.9B output Head).
- - Activation parameters: **2.4B** (including the shared 0.9B Embedding and 0.9B output Head).
-
-#### Structural Details
-
-- **embed_tokens**: **Shares parameters** with the Embedding layer of the Main Model weights.
-- **enorm & hnorm**: RMSNorm parameters required for speculative decoding.
-- **eh_proj**: Parameters for dimensionality reduction projection on the norm results.
-- **Additional Transformer Hidden Layer**:
- - `model.layers.61.self_attn & mlp` (structure identical to the Main Model hidden layers).
-- **shared_head**: **Shares parameters** with the output Head of the Main Model weights.
-
----
-
-### Loading Rules
-
-- **Main Model Weights**: Loaded via the `num_hidden_layers` parameter in `config.json`.
-- **MTP Modules**: Loaded via the `num_nextn_predict_layers` parameter, with layer IDs appended immediately after the Main Model hidden layers. For example:
- - If `num_hidden_layers = 61` and `num_nextn_predict_layers = 1`, the MTP Module's layer ID is `61`.
-
----
-
-## FP8 Weight Documentation
-
-DeepSeek-V3 natively supports FP8 weight format with 128x128 block scaling.
-
-### FP8 Configuration
-
-The FP8 weight file introduces a `quantization_config` field to describe the quantization method. Below is an example configuration:
-
-```json
-"quantization_config": {
- "activation_scheme": "dynamic",
- "fmt": "e4m3",
- "quant_method": "fp8",
- "weight_block_size": [128, 128]
-}
-```
-
-- **Quantization Format**:
- - Format type: `fp8` and `e4m3` (corresponding to `torch.float8_e4m3fn`).
- - Weight block size: `128x128`.
-- **Activation Quantization Scheme**:
- - Utilizes dynamic activation quantization (`dynamic`).
-
-### Dequantization Method
-
-The FP8 weight file includes a `weight_scale_inv` field, which stores the dequantization scale for each weight block.
-
-- **Storage Format**: `float32 Tensor`, stored alongside the weight data.
-- **Dequantization Formula**:
- - 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.
- - The dequantization process is performed as: `(128x128 weight block) * weight_scale_inv`.
-
-Through dequantization of the FP8 weights, runtime operations enable online quantization at a granularity of `per-token-per-128-channel`.
-
----
diff --git a/figures/benchmark.png b/figures/benchmark.png
deleted file mode 100644
index d7ee0c0..0000000
Binary files a/figures/benchmark.png and /dev/null differ
diff --git a/figures/niah.png b/figures/niah.png
deleted file mode 100644
index 2a2e920..0000000
Binary files a/figures/niah.png and /dev/null differ
diff --git a/inference/configs/config_16B.json b/inference/configs/config_16B.json
deleted file mode 100644
index 2aa6477..0000000
--- a/inference/configs/config_16B.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "vocab_size": 102400,
- "dim": 2048,
- "inter_dim": 10944,
- "moe_inter_dim": 1408,
- "n_layers": 27,
- "n_dense_layers": 1,
- "n_heads": 16,
- "n_routed_experts": 64,
- "n_shared_experts": 2,
- "n_activated_experts": 6,
- "route_scale": 1.0,
- "q_lora_rank": 0,
- "kv_lora_rank": 512,
- "qk_nope_head_dim": 128,
- "qk_rope_head_dim": 64,
- "v_head_dim": 128,
- "mscale": 0.707
-}
\ No newline at end of file
diff --git a/inference/configs/config_236B.json b/inference/configs/config_236B.json
deleted file mode 100644
index 389b312..0000000
--- a/inference/configs/config_236B.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "vocab_size": 102400,
- "dim": 5120,
- "inter_dim": 12288,
- "moe_inter_dim": 1536,
- "n_layers": 60,
- "n_dense_layers": 1,
- "n_heads": 128,
- "n_routed_experts": 160,
- "n_shared_experts": 2,
- "n_activated_experts": 6,
- "n_expert_groups": 8,
- "n_limited_groups": 3,
- "route_scale": 16.0,
- "q_lora_rank": 1536,
- "kv_lora_rank": 512,
- "qk_nope_head_dim": 128,
- "qk_rope_head_dim": 64,
- "v_head_dim": 128
-}
\ No newline at end of file
diff --git a/inference/configs/config_671B.json b/inference/configs/config_671B.json
deleted file mode 100644
index 48b5c71..0000000
--- a/inference/configs/config_671B.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "vocab_size": 129280,
- "dim": 7168,
- "inter_dim": 18432,
- "moe_inter_dim": 2048,
- "n_layers": 61,
- "n_dense_layers": 3,
- "n_heads": 128,
- "n_routed_experts": 256,
- "n_shared_experts": 1,
- "n_activated_experts": 8,
- "n_expert_groups": 8,
- "n_limited_groups": 4,
- "route_scale": 2.5,
- "score_func": "sigmoid",
- "q_lora_rank": 1536,
- "kv_lora_rank": 512,
- "qk_nope_head_dim": 128,
- "qk_rope_head_dim": 64,
- "v_head_dim": 128,
- "dtype": "fp8"
-}
\ No newline at end of file
diff --git a/inference/convert.py b/inference/convert.py
deleted file mode 100644
index 6d85ccc..0000000
--- a/inference/convert.py
+++ /dev/null
@@ -1,96 +0,0 @@
-import os
-import shutil
-from argparse import ArgumentParser
-from glob import glob
-from tqdm import tqdm, trange
-
-import torch
-from safetensors.torch import safe_open, save_file
-
-
-mapping = {
- "embed_tokens": ("embed", 0),
- "input_layernorm": ("attn_norm", None),
- "post_attention_layernorm": ("ffn_norm", None),
- "q_proj": ("wq", 0),
- "q_a_proj": ("wq_a", None),
- "q_a_layernorm": ("q_norm", None),
- "q_b_proj": ("wq_b", 0),
- "kv_a_proj_with_mqa": ("wkv_a", None),
- "kv_a_layernorm": ("kv_norm", None),
- "kv_b_proj": ("wkv_b", 0),
- "o_proj": ("wo", 1),
- "gate": ("gate", None),
- "gate_proj": ("w1", 0),
- "down_proj": ("w2", 1),
- "up_proj": ("w3", 0),
- "norm": ("norm", None),
- "lm_head": ("head", 0),
- "scale": ("scale", None),
-}
-
-
-def main(hf_ckpt_path, save_path, n_experts, mp):
- """
- Converts and saves model checkpoint files into a specified format.
-
- Args:
- hf_ckpt_path (str): Path to the directory containing the input checkpoint files.
- save_path (str): Path to the directory where the converted checkpoint files will be saved.
- n_experts (int): Total number of experts in the model.
- mp (int): Model parallelism factor.
-
- Returns:
- None
- """
- torch.set_num_threads(8)
- n_local_experts = n_experts // mp
- state_dicts = [{} for _ in range(mp)]
-
- for file_path in tqdm(glob(os.path.join(hf_ckpt_path, "*.safetensors"))):
- with safe_open(file_path, framework="pt", device="cpu") as f:
- for name in f.keys():
- if "model.layers.61" in name:
- continue
- param: torch.Tensor = f.get_tensor(name)
- if name.startswith("model."):
- name = name[len("model."):]
- name = name.replace("self_attn", "attn")
- name = name.replace("mlp", "ffn")
- name = name.replace("weight_scale_inv", "scale")
- name = name.replace("e_score_correction_bias", "bias")
- key = name.split(".")[-2]
- assert key in mapping, f"Key {key} not found in mapping"
- new_key, dim = mapping[key]
- name = name.replace(key, new_key)
- for i in range(mp):
- new_param = param
- if "experts" in name and "shared_experts" not in name:
- idx = int(name.split(".")[-3])
- if idx < i * n_local_experts or idx >= (i + 1) * n_local_experts:
- continue
- elif dim is not None:
- assert param.size(dim) % mp == 0, f"Dimension {dim} must be divisible by {mp}"
- shard_size = param.size(dim) // mp
- new_param = param.narrow(dim, i * shard_size, shard_size).contiguous()
- state_dicts[i][name] = new_param
-
- os.makedirs(save_path, exist_ok=True)
-
- for i in trange(mp):
- save_file(state_dicts[i], os.path.join(save_path, f"model{i}-mp{mp}.safetensors"))
-
- for file_path in glob(os.path.join(hf_ckpt_path, "*token*")):
- new_file_path = os.path.join(save_path, os.path.basename(file_path))
- shutil.copyfile(file_path, new_file_path)
-
-
-if __name__ == "__main__":
- parser = ArgumentParser()
- parser.add_argument("--hf-ckpt-path", type=str, required=True)
- parser.add_argument("--save-path", type=str, required=True)
- parser.add_argument("--n-experts", type=int, required=True)
- parser.add_argument("--model-parallel", type=int, required=True)
- args = parser.parse_args()
- assert args.n_experts % args.model_parallel == 0, "Number of experts must be divisible by model parallelism"
- main(args.hf_ckpt_path, args.save_path, args.n_experts, args.model_parallel)
diff --git a/inference/fp8_cast_bf16.py b/inference/fp8_cast_bf16.py
deleted file mode 100644
index 4037342..0000000
--- a/inference/fp8_cast_bf16.py
+++ /dev/null
@@ -1,112 +0,0 @@
-import os
-import json
-from argparse import ArgumentParser
-from glob import glob
-from tqdm import tqdm
-
-import torch
-from safetensors.torch import load_file, save_file
-
-from kernel import weight_dequant
-
-def main(fp8_path, bf16_path):
- """
- Converts FP8 weights to BF16 and saves the converted weights.
-
- This function reads FP8 weights from the specified directory, converts them to BF16,
- and saves the converted weights to another specified directory. It also updates the
- model index file to reflect the changes.
-
- Args:
- fp8_path (str): The path to the directory containing the FP8 weights and model index file.
- bf16_path (str): The path to the directory where the converted BF16 weights will be saved.
-
- Raises:
- KeyError: If a required scale_inv tensor is missing for a weight.
-
- Notes:
- - The function assumes that the FP8 weights are stored in safetensor files.
- - The function caches loaded safetensor files to optimize memory usage.
- - The function updates the model index file to remove references to scale_inv tensors.
- """
- torch.set_default_dtype(torch.bfloat16)
- os.makedirs(bf16_path, exist_ok=True)
- model_index_file = os.path.join(fp8_path, "model.safetensors.index.json")
- with open(model_index_file, "r") as f:
- model_index = json.load(f)
- weight_map = model_index["weight_map"]
-
- # Cache for loaded safetensor files
- loaded_files = {}
- fp8_weight_names = []
-
- # Helper function to get tensor from the correct file
- def get_tensor(tensor_name):
- """
- Retrieves a tensor from the cached safetensor files or loads it from disk if not cached.
-
- Args:
- tensor_name (str): The name of the tensor to retrieve.
-
- Returns:
- torch.Tensor: The retrieved tensor.
-
- Raises:
- KeyError: If the tensor does not exist in the safetensor file.
- """
- file_name = weight_map[tensor_name]
- if file_name not in loaded_files:
- file_path = os.path.join(fp8_path, file_name)
- loaded_files[file_name] = load_file(file_path, device="cuda")
- return loaded_files[file_name][tensor_name]
-
- safetensor_files = list(glob(os.path.join(fp8_path, "*.safetensors")))
- safetensor_files.sort()
- for safetensor_file in tqdm(safetensor_files):
- file_name = os.path.basename(safetensor_file)
- current_state_dict = load_file(safetensor_file, device="cuda")
- loaded_files[file_name] = current_state_dict
-
- new_state_dict = {}
- for weight_name, weight in current_state_dict.items():
- if weight_name.endswith("_scale_inv"):
- continue
- elif weight.element_size() == 1: # FP8 weight
- scale_inv_name = f"{weight_name}_scale_inv"
- try:
- # Get scale_inv from the correct file
- scale_inv = get_tensor(scale_inv_name)
- fp8_weight_names.append(weight_name)
- new_state_dict[weight_name] = weight_dequant(weight, scale_inv)
- except KeyError:
- print(f"Warning: Missing scale_inv tensor for {weight_name}, skipping conversion")
- new_state_dict[weight_name] = weight
- else:
- new_state_dict[weight_name] = weight
-
- new_safetensor_file = os.path.join(bf16_path, file_name)
- save_file(new_state_dict, new_safetensor_file)
-
- # Memory management: keep only the 2 most recently used files
- if len(loaded_files) > 2:
- oldest_file = next(iter(loaded_files))
- del loaded_files[oldest_file]
- torch.cuda.empty_cache()
-
- # Update model index
- new_model_index_file = os.path.join(bf16_path, "model.safetensors.index.json")
- for weight_name in fp8_weight_names:
- scale_inv_name = f"{weight_name}_scale_inv"
- if scale_inv_name in weight_map:
- weight_map.pop(scale_inv_name)
- with open(new_model_index_file, "w") as f:
- json.dump({"metadata": {}, "weight_map": weight_map}, f, indent=2)
-
-
-if __name__ == "__main__":
- parser = ArgumentParser()
- parser.add_argument("--input-fp8-hf-path", type=str, required=True)
- parser.add_argument("--output-bf16-hf-path", type=str, required=True)
- args = parser.parse_args()
- main(args.input_fp8_hf_path, args.output_bf16_hf_path)
-
diff --git a/inference/generate.py b/inference/generate.py
deleted file mode 100644
index 7e9bffe..0000000
--- a/inference/generate.py
+++ /dev/null
@@ -1,185 +0,0 @@
-import os
-import json
-from argparse import ArgumentParser
-from typing import List
-
-import torch
-import torch.distributed as dist
-from transformers import AutoTokenizer
-from safetensors.torch import load_model
-
-from model import Transformer, ModelArgs
-
-
-def sample(logits, temperature: float = 1.0):
- """
- Samples a token from the logits using temperature scaling.
-
- Args:
- logits (torch.Tensor): The logits tensor for token predictions.
- temperature (float, optional): Temperature for scaling logits. Defaults to 1.0.
-
- Returns:
- torch.Tensor: The sampled token.
- """
- logits = logits / max(temperature, 1e-5)
- probs = torch.softmax(logits, dim=-1)
- return probs.div_(torch.empty_like(probs).exponential_(1)).argmax(dim=-1)
-
-
-@torch.inference_mode()
-def generate(
- model: Transformer,
- prompt_tokens: List[List[int]],
- max_new_tokens: int,
- eos_id: int,
- temperature: float = 1.0
-) -> List[List[int]]:
- """
- Generates new tokens based on the given prompt tokens using the specified model.
-
- Args:
- model (Transformer): The transformer model used for token generation.
- prompt_tokens (List[List[int]]): A list of lists containing the prompt tokens for each sequence.
- max_new_tokens (int): The maximum number of new tokens to generate.
- eos_id (int): The end-of-sequence token ID.
- temperature (float, optional): The temperature value for sampling. Defaults to 1.0.
-
- Returns:
- List[List[int]]: A list of lists containing the generated tokens for each sequence.
- """
- prompt_lens = [len(t) for t in prompt_tokens]
- assert max(prompt_lens) <= model.max_seq_len, f"Prompt length exceeds model maximum sequence length (max_seq_len={model.max_seq_len})"
- total_len = min(model.max_seq_len, max_new_tokens + max(prompt_lens))
- tokens = torch.full((len(prompt_tokens), total_len), -1, dtype=torch.long, device="cuda")
- for i, t in enumerate(prompt_tokens):
- tokens[i, :len(t)] = torch.tensor(t, dtype=torch.long, device="cuda")
- prev_pos = 0
- finished = torch.tensor([False] * len(prompt_tokens), device="cuda")
- prompt_mask = tokens != -1
- for cur_pos in range(min(prompt_lens), total_len):
- logits = model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
- if temperature > 0:
- next_token = sample(logits, temperature)
- else:
- next_token = logits.argmax(dim=-1)
- next_token = torch.where(prompt_mask[:, cur_pos], tokens[:, cur_pos], next_token)
- tokens[:, cur_pos] = next_token
- finished |= torch.logical_and(~prompt_mask[:, cur_pos], next_token == eos_id)
- prev_pos = cur_pos
- if finished.all():
- break
- completion_tokens = []
- for i, toks in enumerate(tokens.tolist()):
- toks = toks[prompt_lens[i]:prompt_lens[i]+max_new_tokens]
- if eos_id in toks:
- toks = toks[:toks.index(eos_id)]
- completion_tokens.append(toks)
- return completion_tokens
-
-
-def main(
- ckpt_path: str,
- config: str,
- input_file: str = "",
- interactive: bool = True,
- max_new_tokens: int = 100,
- temperature: float = 1.0,
-) -> None:
- """
- Main function to load the model and perform interactive or batch text generation.
-
- Args:
- ckpt_path (str): Path to the model checkpoint directory.
- config (str): Path to the model configuration file.
- input_file (str, optional): Path to a file containing input prompts. Defaults to "".
- interactive (bool, optional): Whether to run in interactive mode. Defaults to True.
- max_new_tokens (int, optional): Maximum number of new tokens to generate. Defaults to 100.
- temperature (float, optional): Temperature for sampling. Defaults to 1.0.
- """
- world_size = int(os.getenv("WORLD_SIZE", "1"))
- rank = int(os.getenv("RANK", "0"))
- local_rank = int(os.getenv("LOCAL_RANK", "0"))
- if world_size > 1:
- dist.init_process_group("nccl")
- global print
- if rank != 0:
- print = lambda *_, **__: None
- torch.cuda.set_device(local_rank)
- torch.set_default_dtype(torch.bfloat16)
- torch.set_num_threads(8)
- torch.manual_seed(965)
- with open(config) as f:
- args = ModelArgs(**json.load(f))
- print(args)
- with torch.device("cuda"):
- model = Transformer(args)
- tokenizer = AutoTokenizer.from_pretrained(ckpt_path)
- tokenizer.decode(generate(model, [tokenizer.encode("DeepSeek")], 2, -1, 1.)[0])
- load_model(model, os.path.join(ckpt_path, f"model{rank}-mp{world_size}.safetensors"))
-
- if interactive:
- messages = []
- while True:
- if world_size == 1:
- prompt = input(">>> ")
- elif rank == 0:
- prompt = input(">>> ")
- objects = [prompt]
- dist.broadcast_object_list(objects, 0)
- else:
- objects = [None]
- dist.broadcast_object_list(objects, 0)
- prompt = objects[0]
- if prompt == "/exit":
- break
- elif prompt == "/clear":
- messages.clear()
- continue
- messages.append({"role": "user", "content": prompt})
- prompt_tokens = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
- completion_tokens = generate(model, [prompt_tokens], max_new_tokens, tokenizer.eos_token_id, temperature)
- completion = tokenizer.decode(completion_tokens[0], skip_special_tokens=True)
- print(completion)
- messages.append({"role": "assistant", "content": completion})
- else:
- with open(input_file) as f:
- prompts = [line.strip() for line in f.readlines()]
- assert len(prompts) <= args.max_batch_size, f"Number of prompts exceeds maximum batch size ({args.max_batch_size})"
- prompt_tokens = [tokenizer.apply_chat_template([{"role": "user", "content": prompt}], add_generation_prompt=True) for prompt in prompts]
- completion_tokens = generate(model, prompt_tokens, max_new_tokens, tokenizer.eos_token_id, temperature)
- completions = tokenizer.batch_decode(completion_tokens, skip_special_tokens=True)
- for prompt, completion in zip(prompts, completions):
- print("Prompt:", prompt)
- print("Completion:", completion)
- print()
-
- if world_size > 1:
- dist.destroy_process_group()
-
-
-if __name__ == "__main__":
- """
- Command-line interface for distributed text generation.
-
- Arguments:
- --ckpt-path (str): Path to the model checkpoint directory.
- --config (str): Path to the model configuration file.
- --input-file (str, optional): File containing prompts for batch processing.
- --interactive (bool, optional): Enable interactive mode for generating text.
- --max-new-tokens (int, optional): Maximum number of new tokens to generate. Defaults to 200.
- --temperature (float, optional): Temperature for sampling. Defaults to 0.2.
-
- Raises:
- AssertionError: If neither input-file nor interactive mode is specified.
- """
- parser = ArgumentParser()
- parser.add_argument("--ckpt-path", type=str, required=True)
- parser.add_argument("--config", type=str, required=True)
- parser.add_argument("--input-file", type=str, default="")
- parser.add_argument("--interactive", action="store_true")
- parser.add_argument("--max-new-tokens", type=int, default=200)
- parser.add_argument("--temperature", type=float, default=0.2)
- args = parser.parse_args()
- assert args.input_file or args.interactive, "Either input-file or interactive mode must be specified"
- main(args.ckpt_path, args.config, args.input_file, args.interactive, args.max_new_tokens, args.temperature)
diff --git a/inference/kernel.py b/inference/kernel.py
deleted file mode 100644
index ae907ad..0000000
--- a/inference/kernel.py
+++ /dev/null
@@ -1,191 +0,0 @@
-from typing import Tuple
-
-import torch
-import triton
-import triton.language as tl
-from triton import Config
-
-
-@triton.jit
-def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr):
- """
- Quantizes the input tensor `x_ptr` and stores the result in `y_ptr` and the scaling factor in `s_ptr`.
-
- Args:
- x_ptr (triton.Pointer): Pointer to the input tensor.
- y_ptr (triton.Pointer): Pointer to the output tensor where quantized values will be stored.
- s_ptr (triton.Pointer): Pointer to the output tensor where scaling factors will be stored.
- BLOCK_SIZE (tl.constexpr): The size of the block to be processed by each program instance.
-
- Returns:
- None
- """
- pid = tl.program_id(axis=0)
- offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
- x = tl.load(x_ptr + offs).to(tl.float32)
- s = tl.max(tl.abs(x)) / 448.
- y = x / s
- y = y.to(y_ptr.dtype.element_ty)
- tl.store(y_ptr + offs, y)
- tl.store(s_ptr + pid, s)
-
-
-def act_quant(x: torch.Tensor, block_size: int = 128) -> Tuple[torch.Tensor, torch.Tensor]:
- """
- Quantizes the input tensor `x` using block-wise quantization.
-
- Args:
- x (torch.Tensor): The input tensor to be quantized. Must be contiguous and its last dimension size must be divisible by `block_size`.
- block_size (int, optional): The size of the blocks to be used for quantization. Default is 128.
-
- Returns:
- Tuple[torch.Tensor, torch.Tensor]: A tuple containing:
- - The quantized tensor with dtype `torch.float8_e4m3fn`.
- - A tensor of scaling factors with dtype `torch.float32`.
- """
- assert x.is_contiguous(), 'Input tensor must be contiguous'
- assert x.size(-1) % block_size == 0, f'Last dimension size must be divisible by block_size (block_size={block_size})'
- y = torch.empty_like(x, dtype=torch.float8_e4m3fn)
- s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
- grid = lambda meta: (triton.cdiv(x.numel(), meta['BLOCK_SIZE']), )
- act_quant_kernel[grid](x, y, s, BLOCK_SIZE=block_size)
- return y, s
-
-
-@triton.jit
-def weight_dequant_kernel(x_ptr, s_ptr, y_ptr, M, N, BLOCK_SIZE: tl.constexpr):
- """
- Dequantizes weights using the provided scaling factors and stores the result.
-
- Args:
- x_ptr (tl.pointer): Pointer to the quantized weights.
- s_ptr (tl.pointer): Pointer to the scaling factors.
- y_ptr (tl.pointer): Pointer to the output buffer for dequantized weights.
- M (int): Number of rows in the weight matrix.
- N (int): Number of columns in the weight matrix.
- BLOCK_SIZE (tl.constexpr): Size of the block for tiling.
-
- Returns:
- None
- """
- pid_m = tl.program_id(axis=0)
- pid_n = tl.program_id(axis=1)
- n = tl.cdiv(N, BLOCK_SIZE)
- offs_m = pid_m * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
- offs_n = pid_n * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
- offs = offs_m[:, None] * N + offs_n[None, :]
- mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)
- x = tl.load(x_ptr + offs, mask=mask).to(tl.float32)
- s = tl.load(s_ptr + pid_m * n + pid_n)
- y = x * s
- tl.store(y_ptr + offs, y, mask=mask)
-
-
-def weight_dequant(x: torch.Tensor, s: torch.Tensor, block_size: int = 128) -> torch.Tensor:
- """
- Dequantizes the given weight tensor using the provided scale tensor.
-
- Args:
- x (torch.Tensor): The quantized weight tensor of shape (M, N).
- s (torch.Tensor): The scale tensor of shape (M, N).
- block_size (int, optional): The block size to use for dequantization. Defaults to 128.
-
- Returns:
- torch.Tensor: The dequantized weight tensor of the same shape as `x`.
-
- Raises:
- AssertionError: If `x` or `s` are not contiguous or if their dimensions are not 2.
- """
- assert x.is_contiguous() and s.is_contiguous(), 'Input tensors must be contiguous'
- assert x.dim() == 2 and s.dim() == 2, 'Input tensors must have 2 dimensions'
- M, N = x.size()
- y = torch.empty_like(x, dtype=torch.get_default_dtype())
- grid = lambda meta: (triton.cdiv(M, meta['BLOCK_SIZE']), triton.cdiv(N, meta['BLOCK_SIZE']))
- weight_dequant_kernel[grid](x, s, y, M, N, BLOCK_SIZE=block_size)
- return y
-
-
-fp8_gemm_configs = [
- Config({'BLOCK_SIZE_M': block_m, 'BLOCK_SIZE_N': block_n, 'BLOCK_SIZE_K': 128}, num_stages=num_stages, num_warps=8)
- for block_m in [16, 32, 64] for block_n in [32, 64, 128] for num_stages in [3, 4, 5, 6]
-]
-
-@triton.autotune(configs=fp8_gemm_configs, key=['N', 'K'])
-@triton.jit
-def fp8_gemm_kernel(a_ptr, b_ptr, c_ptr,
- a_s_ptr, b_s_ptr,
- M, N: tl.constexpr, K: tl.constexpr,
- BLOCK_SIZE_M: tl.constexpr,
- BLOCK_SIZE_N: tl.constexpr,
- BLOCK_SIZE_K: tl.constexpr):
- """
- Performs a matrix multiplication operation on FP8 matrices with scaling factors.
-
- Args:
- a_ptr (tl.tensor): Pointer to the first input matrix A.
- b_ptr (tl.tensor): Pointer to the second input matrix B.
- c_ptr (tl.tensor): Pointer to the output matrix C.
- a_s_ptr (tl.tensor): Pointer to the scaling factors for matrix A.
- b_s_ptr (tl.tensor): Pointer to the scaling factors for matrix B.
- M (int): Number of rows in matrix A and C.
- N (tl.constexpr): Number of columns in matrix B and C.
- K (tl.constexpr): Number of columns in matrix A and rows in matrix B.
- BLOCK_SIZE_M (tl.constexpr): Block size for the M dimension.
- BLOCK_SIZE_N (tl.constexpr): Block size for the N dimension.
- BLOCK_SIZE_K (tl.constexpr): Block size for the K dimension.
-
- Returns:
- None
- """
- pid_m = tl.program_id(axis=0)
- pid_n = tl.program_id(axis=1)
- k = tl.cdiv(K, BLOCK_SIZE_K)
- offs_m = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
- offs_n = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
- offs_k = tl.arange(0, BLOCK_SIZE_K)
- a_ptrs = a_ptr + offs_m[:, None] * K + offs_k[None, :]
- b_ptrs = b_ptr + offs_n[None, :] * K + offs_k[:, None]
- a_s_ptrs = a_s_ptr + offs_m * k
- b_s_ptrs = b_s_ptr + (offs_n // BLOCK_SIZE_K) * k
-
- accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
- for i in range(k):
- a = tl.load(a_ptrs, mask=offs_k[None, :] < K - i * BLOCK_SIZE_K, other=0.0)
- b = tl.load(b_ptrs, mask=offs_k[:, None] < K - i * BLOCK_SIZE_K, other=0.0)
- a_s = tl.load(a_s_ptrs)
- b_s = tl.load(b_s_ptrs)
- accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
- a_ptrs += BLOCK_SIZE_K
- b_ptrs += BLOCK_SIZE_K
- a_s_ptrs += 1
- b_s_ptrs += 1
- c = accumulator.to(c_ptr.dtype.element_ty)
- offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
- offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
- c_ptrs = c_ptr + offs_m[:, None] * N + offs_n[None, :]
- mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)
- tl.store(c_ptrs, c, mask=mask)
-
-
-def fp8_gemm(a: torch.Tensor, a_s: torch.Tensor, b: torch.Tensor, b_s: torch.Tensor):
- """
- Perform a matrix multiplication using FP8 precision.
-
- Args:
- a (torch.Tensor): The first input matrix, must be contiguous.
- a_s (torch.Tensor): The scaling factor for the first input matrix, must be contiguous.
- b (torch.Tensor): The second input matrix, must be contiguous.
- b_s (torch.Tensor): The scaling factor for the second input matrix, must be contiguous.
-
- Returns:
- torch.Tensor: The result of the matrix multiplication.
- """
- assert a.is_contiguous() and b.is_contiguous(), 'Input tensors must be contiguous'
- assert a_s.is_contiguous() and b_s.is_contiguous(), 'Scaling factor tensors must be contiguous'
- K = a.size(-1)
- M = a.numel() // K
- N = b.size(0)
- c = a.new_empty(*a.size()[:-1], N, dtype=torch.get_default_dtype())
- grid = lambda META: (triton.cdiv(M, META['BLOCK_SIZE_M']), triton.cdiv(N, META['BLOCK_SIZE_N']))
- fp8_gemm_kernel[grid](a, b, c, a_s, b_s, M, N, K)
- return c
diff --git a/inference/model.py b/inference/model.py
deleted file mode 100644
index 8f1ab81..0000000
--- a/inference/model.py
+++ /dev/null
@@ -1,804 +0,0 @@
-import math
-from dataclasses import dataclass
-from typing import Tuple, Optional, Literal
-
-import torch
-from torch import nn
-import torch.nn.functional as F
-import torch.distributed as dist
-
-from kernel import act_quant, weight_dequant, fp8_gemm
-
-
-world_size = 1
-rank = 0
-block_size = 128
-gemm_impl: Literal["bf16", "fp8"] = "bf16"
-attn_impl: Literal["naive", "absorb"] = "absorb"
-
-@dataclass
-class ModelArgs:
- """
- Data class for defining model arguments and hyperparameters.
-
- Attributes:
- max_batch_size (int): Maximum batch size.
- max_seq_len (int): Maximum sequence length.
- dtype (Literal["bf16", "fp8"]): Data type for computations.
- vocab_size (int): Vocabulary size.
- dim (int): Model dimension.
- inter_dim (int): Intermediate dimension for MLP layers.
- moe_inter_dim (int): Intermediate dimension for MoE layers.
- n_layers (int): Number of transformer layers.
- n_dense_layers (int): Number of dense layers in the model.
- n_heads (int): Number of attention heads.
- n_routed_experts (int): Number of routed experts for MoE layers.
- n_shared_experts (int): Number of shared experts for MoE layers.
- n_activated_experts (int): Number of activated experts in MoE layers.
- n_expert_groups (int): Number of expert groups.
- n_limited_groups (int): Number of limited groups for MoE routing.
- score_func (Literal["softmax", "sigmoid"]): Scoring function for MoE routing.
- route_scale (float): Scaling factor for routing scores.
- q_lora_rank (int): LoRA rank for query projections.
- kv_lora_rank (int): LoRA rank for key-value projections.
- qk_nope_head_dim (int): Dimension for query-key projections without positional embeddings.
- qk_rope_head_dim (int): Dimension for query-key projections with rotary embeddings.
- v_head_dim (int): Dimension for value projections.
- original_seq_len (int): Original sequence length.
- rope_theta (float): Base for rotary positional encoding.
- rope_factor (float): Scaling factor for extended sequence lengths.
- beta_fast (int): Fast beta correction factor.
- beta_slow (int): Slow beta correction factor.
- mscale (float): Scaling factor for extended attention.
- """
- max_batch_size: int = 8
- max_seq_len: int = 4096 * 4
- dtype: Literal["bf16", "fp8"] = "bf16"
- vocab_size: int = 102400
- dim: int = 2048
- inter_dim: int = 10944
- moe_inter_dim: int = 1408
- n_layers: int = 27
- n_dense_layers: int = 1
- n_heads: int = 16
- # moe
- n_routed_experts: int = 64
- n_shared_experts: int = 2
- n_activated_experts: int = 6
- n_expert_groups: int = 1
- n_limited_groups: int = 1
- score_func: Literal["softmax", "sigmoid"] = "softmax"
- route_scale: float = 1.
- # mla
- q_lora_rank: int = 0
- kv_lora_rank: int = 512
- qk_nope_head_dim: int = 128
- qk_rope_head_dim: int = 64
- v_head_dim: int = 128
- # yarn
- original_seq_len: int = 4096
- rope_theta: float = 10000.0
- rope_factor: float = 40
- beta_fast: int = 32
- beta_slow: int = 1
- mscale: float = 1.
-
-
-class ParallelEmbedding(nn.Module):
- """
- Embedding layer with parallelism support across distributed processes.
-
- Args:
- vocab_size (int): Vocabulary size.
- dim (int): Embedding dimension.
- """
- def __init__(self, vocab_size: int, dim: int):
- super().__init__()
- self.vocab_size = vocab_size
- self.dim = dim
- assert vocab_size % world_size == 0, f"Vocabulary size must be divisible by world size (world_size={world_size})"
- self.part_vocab_size = (vocab_size // world_size)
- self.vocab_start_idx = rank * self.part_vocab_size
- self.vocab_end_idx = self.vocab_start_idx + self.part_vocab_size
- self.weight = nn.Parameter(torch.empty(self.part_vocab_size, self.dim))
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass for parallel embedding layer.
-
- Args:
- x (torch.Tensor): Input tensor containing token indices.
-
- Returns:
- torch.Tensor: Embedded representations.
-
- Raises:
- ValueError: If `world_size` is not defined.
- """
- if world_size > 1:
- mask = (x < self.vocab_start_idx) | (x >= self.vocab_end_idx)
- x = x - self.vocab_start_idx
- x[mask] = 0
- y = F.embedding(x, self.weight)
- if world_size > 1:
- y[mask] = 0
- dist.all_reduce(y)
- return y
-
-
-def linear(x: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor] = None) -> torch.Tensor:
- """
- Applies a linear transformation to the incoming data: y = xA^T + b.
- This function supports specialized implementations based on quantization
- and tensor formats.
-
- Args:
- x (torch.Tensor): The input tensor.
- weight (torch.Tensor): The weight tensor. It may be quantized and
- requires dequantization for certain cases.
- bias (Optional[torch.Tensor]): The bias tensor to be added. Default is None.
-
- Returns:
- torch.Tensor: The result of the linear transformation, which may involve
- quantization-aware computations depending on the input parameters.
-
- Notes:
- - If `weight` is quantized (e.g., `element_size() == 1`), a dequantized version
- is used for computation.
- - If `gemm_impl == "bf16"`, dequantization and a `bf16` GEMM operation are applied.
- - For other cases, the function applies quantization to `x` and uses `fp8_gemm` for computation.
- """
- if weight.element_size() > 1:
- return F.linear(x, weight, bias)
- elif gemm_impl == "bf16":
- weight = weight_dequant(weight, weight.scale)
- return F.linear(x, weight, bias)
- else:
- x, scale = act_quant(x, block_size)
- y = fp8_gemm(x, scale, weight, weight.scale)
- if bias is not None:
- y += bias
- return y
-
-
-class Linear(nn.Module):
- """
- Custom linear layer with support for quantized weights and optional bias.
-
- Args:
- in_features (int): Number of input features.
- out_features (int): Number of output features.
- bias (bool): Whether to include a bias term. Defaults to False.
- dtype (optional): Data type for the layer. Defaults to `torch.bfloat16`.
- """
- dtype = torch.bfloat16
-
- def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None):
- super().__init__()
- self.in_features = in_features
- self.out_features = out_features
- self.weight = nn.Parameter(torch.empty(out_features, in_features, dtype=dtype or Linear.dtype))
- if self.weight.element_size() == 1:
- scale_out_features = (out_features + block_size - 1) // block_size
- scale_in_features = (in_features + block_size - 1) // block_size
- self.weight.scale = self.scale = nn.Parameter(torch.empty(scale_out_features, scale_in_features, dtype=torch.float32))
- else:
- self.register_parameter("scale", None)
- if bias:
- self.bias = nn.Parameter(torch.empty(out_features))
- else:
- self.register_parameter("bias", None)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass for the custom linear layer.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- torch.Tensor: Transformed tensor after linear computation.
- """
- return linear(x, self.weight, self.bias)
-
-
-class ColumnParallelLinear(Linear):
- """
- Linear layer with column parallelism, splitting output features across distributed processes.
-
- Args:
- in_features (int): Number of input features.
- out_features (int): Total number of output features.
- bias (bool): Whether to include a bias term. Defaults to False.
- dtype (optional): Data type for the layer. Defaults to `torch.bfloat16`.
- """
- def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None):
- assert out_features % world_size == 0, f"Output features must be divisible by world size (world_size={world_size})"
- self.part_out_features = out_features // world_size
- super().__init__(in_features, self.part_out_features, bias, dtype)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass for column parallel linear layer.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- torch.Tensor: Transformed tensor with column-parallel computation.
- """
- y = linear(x, self.weight, self.bias)
- return y
-
-
-class RowParallelLinear(Linear):
- """
- Linear layer with row parallelism, splitting input features across distributed processes.
-
- Args:
- in_features (int): Total number of input features.
- out_features (int): Number of output features.
- bias (bool): Whether to include a bias term. Defaults to False.
- dtype (optional): Data type for the layer. Defaults to `torch.bfloat16`.
- """
- def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None):
- assert in_features % world_size == 0, f"Input features must be divisible by world size (world_size={world_size})"
- self.part_in_features = in_features // world_size
- super().__init__(self.part_in_features, out_features, bias, dtype)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass for row parallel linear layer.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- torch.Tensor: Transformed tensor with row-parallel computation.
- """
- y = linear(x, self.weight)
- if world_size > 1:
- dist.all_reduce(y)
- if self.bias is not None:
- y += self.bias
- return y
-
-
-class RMSNorm(nn.Module):
- """
- Root Mean Square Layer Normalization (RMSNorm).
-
- Args:
- dim (int): Dimension of the input tensor.
- eps (float): Epsilon value for numerical stability. Defaults to 1e-6.
- """
- def __init__(self, dim: int, eps: float = 1e-6):
- super().__init__()
- self.dim = dim
- self.eps = eps
- self.weight = nn.Parameter(torch.ones(dim))
-
- def forward(self, x: torch.Tensor):
- """
- Forward pass for RMSNorm.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- torch.Tensor: Normalized tensor with the same shape as input.
- """
- return F.rms_norm(x, (self.dim,), self.weight, self.eps)
-
-
-def precompute_freqs_cis(args: ModelArgs) -> torch.Tensor:
- """
- Precomputes frequency-based complex exponential values for rotary positional embeddings.
-
- Args:
- args (ModelArgs): Model arguments containing positional embedding parameters.
-
- Returns:
- torch.Tensor: Precomputed complex exponential values for positional embeddings.
- """
- dim = args.qk_rope_head_dim
- seqlen = args.max_seq_len
- beta_fast = args.beta_fast
- beta_slow = args.beta_slow
- base = args.rope_theta
- factor = args.rope_factor
-
- def find_correction_dim(num_rotations, dim, base, max_seq_len):
- """
- Computes the correction dimension for a given number of rotations in the rotary positional embedding.
-
- Args:
- num_rotations (float): Number of rotations to compute the correction for.
- dim (int): Dimensionality of the embedding space.
- base (float): Base value for the exponential computation.
- max_seq_len (int): Maximum sequence length.
-
- Returns:
- float: The correction dimension based on the input parameters.
- """
- return dim * math.log(max_seq_len / (num_rotations * 2 * math.pi)) / (2 * math.log(base))
-
- def find_correction_range(low_rot, high_rot, dim, base, max_seq_len):
- """
- Computes the range of correction dimensions for rotary positional embeddings.
-
- Args:
- low_rot (float): Lower bound for the number of rotations.
- high_rot (float): Upper bound for the number of rotations.
- dim (int): Dimensionality of the embedding space.
- base (float): Base value for the exponential computation.
- max_seq_len (int): Maximum sequence length.
-
- Returns:
- Tuple[int, int]: The range of correction dimensions (low, high), clamped to valid indices.
- """
- low = math.floor(find_correction_dim(low_rot, dim, base, max_seq_len))
- high = math.ceil(find_correction_dim(high_rot, dim, base, max_seq_len))
- return max(low, 0), min(high, dim-1)
-
- def linear_ramp_factor(min, max, dim):
- """
- Computes a linear ramp function used to smooth values between a minimum and maximum range.
-
- Args:
- min (float): Minimum value for the ramp function.
- max (float): Maximum value for the ramp function.
- dim (int): Dimensionality of the ramp tensor.
-
- Returns:
- torch.Tensor: A tensor of shape (dim,) with values linearly interpolated between 0 and 1,
- clamped to the range [0, 1].
- """
- if min == max:
- max += 0.001
- linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
- ramp_func = torch.clamp(linear_func, 0, 1)
- return ramp_func
-
- freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
- if seqlen > args.original_seq_len:
- low, high = find_correction_range(beta_fast, beta_slow, dim, base, args.original_seq_len)
- smooth = 1 - linear_ramp_factor(low, high, dim // 2)
- freqs = freqs / factor * (1 - smooth) + freqs * smooth
-
- t = torch.arange(seqlen)
- freqs = torch.outer(t, freqs)
- freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
- return freqs_cis
-
-
-def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
- """
- Applies rotary positional embeddings to the input tensor.
-
- Args:
- x (torch.Tensor): Input tensor with positional embeddings to be applied.
- freqs_cis (torch.Tensor): Precomputed complex exponential values for positional embeddings.
-
- Returns:
- torch.Tensor: Tensor with rotary embeddings applied.
- """
- dtype = x.dtype
- x = torch.view_as_complex(x.float().view(*x.shape[:-1], -1, 2))
- freqs_cis = freqs_cis.view(1, x.size(1), 1, x.size(-1))
- y = torch.view_as_real(x * freqs_cis).flatten(3)
- return y.to(dtype)
-
-
-class MLA(nn.Module):
- """
- Multi-Headed Attention Layer (MLA).
-
- Attributes:
- dim (int): Dimensionality of the input features.
- n_heads (int): Number of attention heads.
- n_local_heads (int): Number of local attention heads for distributed systems.
- q_lora_rank (int): Rank for low-rank query projection.
- kv_lora_rank (int): Rank for low-rank key/value projection.
- qk_nope_head_dim (int): Dimensionality of non-positional query/key projections.
- qk_rope_head_dim (int): Dimensionality of rotary-positional query/key projections.
- qk_head_dim (int): Total dimensionality of query/key projections.
- v_head_dim (int): Dimensionality of value projections.
- softmax_scale (float): Scaling factor for softmax in attention computation.
- """
- def __init__(self, args: ModelArgs):
- super().__init__()
- self.dim = args.dim
- self.n_heads = args.n_heads
- self.n_local_heads = args.n_heads // world_size
- self.q_lora_rank = args.q_lora_rank
- self.kv_lora_rank = args.kv_lora_rank
- self.qk_nope_head_dim = args.qk_nope_head_dim
- self.qk_rope_head_dim = args.qk_rope_head_dim
- self.qk_head_dim = args.qk_nope_head_dim + args.qk_rope_head_dim
- self.v_head_dim = args.v_head_dim
-
- if self.q_lora_rank == 0:
- self.wq = ColumnParallelLinear(self.dim, self.n_heads * self.qk_head_dim)
- else:
- self.wq_a = Linear(self.dim, self.q_lora_rank)
- self.q_norm = RMSNorm(self.q_lora_rank)
- self.wq_b = ColumnParallelLinear(self.q_lora_rank, self.n_heads * self.qk_head_dim)
- self.wkv_a = Linear(self.dim, self.kv_lora_rank + self.qk_rope_head_dim)
- self.kv_norm = RMSNorm(self.kv_lora_rank)
- self.wkv_b = ColumnParallelLinear(self.kv_lora_rank, self.n_heads * (self.qk_nope_head_dim + self.v_head_dim))
- self.wo = RowParallelLinear(self.n_heads * self.v_head_dim, self.dim)
- self.softmax_scale = self.qk_head_dim ** -0.5
- if args.max_seq_len > args.original_seq_len:
- mscale = 0.1 * args.mscale * math.log(args.rope_factor) + 1.0
- self.softmax_scale = self.softmax_scale * mscale * mscale
-
- if attn_impl == "naive":
- 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)
- 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)
- else:
- self.register_buffer("kv_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.kv_lora_rank), persistent=False)
- self.register_buffer("pe_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.qk_rope_head_dim), persistent=False)
-
- def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]):
- """
- Forward pass for the Multi-Headed Attention Layer (MLA).
-
- Args:
- x (torch.Tensor): Input tensor of shape (batch_size, seq_len, dim).
- start_pos (int): Starting position in the sequence for caching.
- freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings.
- mask (Optional[torch.Tensor]): Mask tensor to exclude certain positions from attention.
-
- Returns:
- torch.Tensor: Output tensor with the same shape as the input.
- """
- bsz, seqlen, _ = x.size()
- end_pos = start_pos + seqlen
- if self.q_lora_rank == 0:
- q = self.wq(x)
- else:
- q = self.wq_b(self.q_norm(self.wq_a(x)))
- q = q.view(bsz, seqlen, self.n_local_heads, self.qk_head_dim)
- q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
- q_pe = apply_rotary_emb(q_pe, freqs_cis)
- kv = self.wkv_a(x)
- kv, k_pe = torch.split(kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
- k_pe = apply_rotary_emb(k_pe.unsqueeze(2), freqs_cis)
- if attn_impl == "naive":
- q = torch.cat([q_nope, q_pe], dim=-1)
- kv = self.wkv_b(self.kv_norm(kv))
- kv = kv.view(bsz, seqlen, self.n_local_heads, self.qk_nope_head_dim + self.v_head_dim)
- k_nope, v = torch.split(kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
- k = torch.cat([k_nope, k_pe.expand(-1, -1, self.n_local_heads, -1)], dim=-1)
- self.k_cache[:bsz, start_pos:end_pos] = k
- self.v_cache[:bsz, start_pos:end_pos] = v
- scores = torch.einsum("bshd,bthd->bsht", q, self.k_cache[:bsz, :end_pos]) * self.softmax_scale
- else:
- 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)
- wkv_b = wkv_b.view(self.n_local_heads, -1, self.kv_lora_rank)
- q_nope = torch.einsum("bshd,hdc->bshc", q_nope, wkv_b[:, :self.qk_nope_head_dim])
- self.kv_cache[:bsz, start_pos:end_pos] = self.kv_norm(kv)
- self.pe_cache[:bsz, start_pos:end_pos] = k_pe.squeeze(2)
- scores = (torch.einsum("bshc,btc->bsht", q_nope, self.kv_cache[:bsz, :end_pos]) +
- torch.einsum("bshr,btr->bsht", q_pe, self.pe_cache[:bsz, :end_pos])) * self.softmax_scale
- if mask is not None:
- scores += mask.unsqueeze(1)
- scores = scores.softmax(dim=-1, dtype=torch.float32).type_as(x)
- if attn_impl == "naive":
- x = torch.einsum("bsht,bthd->bshd", scores, self.v_cache[:bsz, :end_pos])
- else:
- x = torch.einsum("bsht,btc->bshc", scores, self.kv_cache[:bsz, :end_pos])
- x = torch.einsum("bshc,hdc->bshd", x, wkv_b[:, -self.v_head_dim:])
- x = self.wo(x.flatten(2))
- return x
-
-
-class MLP(nn.Module):
- """
- Multi-Layer Perceptron (MLP) used as a feed-forward layer.
-
- Attributes:
- w1 (nn.Module): Linear layer for input-to-hidden transformation.
- w2 (nn.Module): Linear layer for hidden-to-output transformation.
- w3 (nn.Module): Additional linear layer for feature transformation.
- """
- def __init__(self, dim: int, inter_dim: int):
- """
- Initializes the MLP layer.
-
- Args:
- dim (int): Input and output dimensionality.
- inter_dim (int): Hidden layer dimensionality.
- """
- super().__init__()
- self.w1 = ColumnParallelLinear(dim, inter_dim)
- self.w2 = RowParallelLinear(inter_dim, dim)
- self.w3 = ColumnParallelLinear(dim, inter_dim)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass for the MLP layer.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- torch.Tensor: Output tensor after MLP computation.
- """
- return self.w2(F.silu(self.w1(x)) * self.w3(x))
-
-
-class Gate(nn.Module):
- """
- Gating mechanism for routing inputs in a mixture-of-experts (MoE) model.
-
- Attributes:
- dim (int): Dimensionality of input features.
- topk (int): Number of top experts activated for each input.
- n_groups (int): Number of groups for routing.
- topk_groups (int): Number of groups to route inputs to.
- score_func (str): Scoring function ('softmax' or 'sigmoid').
- route_scale (float): Scaling factor for routing weights.
- weight (torch.nn.Parameter): Learnable weights for the gate.
- bias (Optional[torch.nn.Parameter]): Optional bias term for the gate.
- """
- def __init__(self, args: ModelArgs):
- """
- Initializes the Gate module.
-
- Args:
- args (ModelArgs): Model arguments containing gating parameters.
- """
- super().__init__()
- self.dim = args.dim
- self.topk = args.n_activated_experts
- self.n_groups = args.n_expert_groups
- self.topk_groups = args.n_limited_groups
- self.score_func = args.score_func
- self.route_scale = args.route_scale
- self.weight = nn.Parameter(torch.empty(args.n_routed_experts, args.dim))
- self.bias = nn.Parameter(torch.empty(args.n_routed_experts)) if self.dim == 7168 else None
-
- def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
- """
- Forward pass for the gating mechanism.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- Tuple[torch.Tensor, torch.Tensor]: Routing weights and selected expert indices.
- """
- scores = linear(x, self.weight)
- if self.score_func == "softmax":
- scores = scores.softmax(dim=-1, dtype=torch.float32)
- else:
- scores = scores.sigmoid()
- original_scores = scores
- if self.bias is not None:
- scores = scores + self.bias
- if self.n_groups > 1:
- scores = scores.view(x.size(0), self.n_groups, -1)
- if self.bias is None:
- group_scores = scores.amax(dim=-1)
- else:
- group_scores = scores.topk(2, dim=-1)[0].sum(dim=-1)
- indices = group_scores.topk(self.topk_groups, dim=-1)[1]
- mask = scores.new_ones(x.size(0), self.n_groups, dtype=bool).scatter_(1, indices, False)
- scores = scores.masked_fill_(mask.unsqueeze(-1), float("-inf")).flatten(1)
- indices = torch.topk(scores, self.topk, dim=-1)[1]
- weights = original_scores.gather(1, indices)
- if self.score_func == "sigmoid":
- weights /= weights.sum(dim=-1, keepdim=True)
- weights *= self.route_scale
- return weights.type_as(x), indices
-
-
-class Expert(nn.Module):
- """
- Expert layer for Mixture-of-Experts (MoE) models.
-
- Attributes:
- w1 (nn.Module): Linear layer for input-to-hidden transformation.
- w2 (nn.Module): Linear layer for hidden-to-output transformation.
- w3 (nn.Module): Additional linear layer for feature transformation.
- """
- def __init__(self, dim: int, inter_dim: int):
- """
- Initializes the Expert layer.
-
- Args:
- dim (int): Input and output dimensionality.
- inter_dim (int): Hidden layer dimensionality.
- """
- super().__init__()
- self.w1 = Linear(dim, inter_dim)
- self.w2 = Linear(inter_dim, dim)
- self.w3 = Linear(dim, inter_dim)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass for the Expert layer.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- torch.Tensor: Output tensor after expert computation.
- """
- return self.w2(F.silu(self.w1(x)) * self.w3(x))
-
-
-class MoE(nn.Module):
- """
- Mixture-of-Experts (MoE) module.
-
- Attributes:
- dim (int): Dimensionality of input features.
- n_routed_experts (int): Total number of experts in the model.
- n_local_experts (int): Number of experts handled locally in distributed systems.
- n_activated_experts (int): Number of experts activated for each input.
- gate (nn.Module): Gating mechanism to route inputs to experts.
- experts (nn.ModuleList): List of expert modules.
- shared_experts (nn.Module): Shared experts applied to all inputs.
- """
- def __init__(self, args: ModelArgs):
- """
- Initializes the MoE module.
-
- Args:
- args (ModelArgs): Model arguments containing MoE parameters.
- """
- super().__init__()
- self.dim = args.dim
- assert args.n_routed_experts % world_size == 0, f"Number of experts must be divisible by world size (world_size={world_size})"
- self.n_routed_experts = args.n_routed_experts
- self.n_local_experts = args.n_routed_experts // world_size
- self.n_activated_experts = args.n_activated_experts
- self.experts_start_idx = rank * self.n_local_experts
- self.experts_end_idx = self.experts_start_idx + self.n_local_experts
- self.gate = Gate(args)
- self.experts = nn.ModuleList([Expert(args.dim, args.moe_inter_dim) if self.experts_start_idx <= i < self.experts_end_idx else None
- for i in range(self.n_routed_experts)])
- self.shared_experts = MLP(args.dim, args.n_shared_experts * args.moe_inter_dim)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """
- Forward pass for the MoE module.
-
- Args:
- x (torch.Tensor): Input tensor.
-
- Returns:
- torch.Tensor: Output tensor after expert routing and computation.
- """
- shape = x.size()
- x = x.view(-1, self.dim)
- weights, indices = self.gate(x)
- y = torch.zeros_like(x)
- counts = torch.bincount(indices.flatten(), minlength=self.n_routed_experts).tolist()
- for i in range(self.experts_start_idx, self.experts_end_idx):
- if counts[i] == 0:
- continue
- expert = self.experts[i]
- idx, top = torch.where(indices == i)
- y[idx] += expert(x[idx]) * weights[idx, top, None]
- z = self.shared_experts(x)
- if world_size > 1:
- dist.all_reduce(y)
- return (y + z).view(shape)
-
-
-class Block(nn.Module):
- """
- Transformer block combining attention and feed-forward layers.
-
- Attributes:
- attn (nn.Module): Attention layer (MLA).
- ffn (nn.Module): Feed-forward network (MLP or MoE).
- attn_norm (nn.Module): Layer normalization for attention.
- ffn_norm (nn.Module): Layer normalization for feed-forward network.
- """
- def __init__(self, layer_id: int, args: ModelArgs):
- """
- Initializes the Transformer block.
-
- Args:
- layer_id (int): Layer index in the transformer.
- args (ModelArgs): Model arguments containing block parameters.
- """
- super().__init__()
- self.attn = MLA(args)
- self.ffn = MLP(args.dim, args.inter_dim) if layer_id < args.n_dense_layers else MoE(args)
- self.attn_norm = RMSNorm(args.dim)
- self.ffn_norm = RMSNorm(args.dim)
-
- def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]) -> torch.Tensor:
- """
- Forward pass for the Transformer block.
-
- Args:
- x (torch.Tensor): Input tensor.
- start_pos (int): Starting position in the sequence.
- freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings.
- mask (Optional[torch.Tensor]): Mask tensor to exclude certain positions from attention.
-
- Returns:
- torch.Tensor: Output tensor after block computation.
- """
- x = x + self.attn(self.attn_norm(x), start_pos, freqs_cis, mask)
- x = x + self.ffn(self.ffn_norm(x))
- return x
-
-
-class Transformer(nn.Module):
- """
- Transformer model with positional embeddings, multiple layers, and output projection.
-
- Attributes:
- max_seq_len (int): Maximum sequence length for the transformer.
- embed (nn.Module): Embedding layer for input tokens.
- layers (torch.nn.ModuleList): List of transformer blocks.
- norm (nn.Module): Layer normalization applied after all blocks.
- head (nn.Module): Output projection layer mapping to vocabulary size.
- freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings.
- """
- def __init__(self, args: ModelArgs):
- """
- Initializes the Transformer model.
-
- Args:
- args (ModelArgs): Model arguments containing transformer parameters.
- """
- global world_size, rank
- world_size = dist.get_world_size() if dist.is_initialized() else 1
- rank = dist.get_rank() if dist.is_initialized() else 0
- Linear.dtype = torch.float8_e4m3fn if args.dtype == "fp8" else torch.bfloat16
- super().__init__()
- self.max_seq_len = args.max_seq_len
- self.embed = ParallelEmbedding(args.vocab_size, args.dim)
- self.layers = torch.nn.ModuleList()
- for layer_id in range(args.n_layers):
- self.layers.append(Block(layer_id, args))
- self.norm = RMSNorm(args.dim)
- self.head = ColumnParallelLinear(args.dim, args.vocab_size, dtype=torch.get_default_dtype())
- self.register_buffer("freqs_cis", precompute_freqs_cis(args), persistent=False)
-
- @torch.inference_mode()
- def forward(self, tokens: torch.Tensor, start_pos: int = 0):
- """
- Forward pass for the Transformer model.
-
- Args:
- tokens (torch.Tensor): Input tensor of token IDs with shape (batch_size, seq_len).
- start_pos (int, optional): Starting position in the sequence for rotary embeddings. Defaults to 0.
-
- Returns:
- torch.Tensor: Logits tensor of shape (batch_size, vocab_size).
- """
- seqlen = tokens.size(1)
- h = self.embed(tokens)
- freqs_cis = self.freqs_cis[start_pos:start_pos+seqlen]
- mask = None
- if seqlen > 1:
- mask = torch.full((seqlen, seqlen), float("-inf"), device=tokens.device).triu_(1)
- for layer in self.layers:
- h = layer(h, start_pos, freqs_cis, mask)
- h = self.norm(h)[:, -1]
- logits = self.head(h)
- if world_size > 1:
- all_logits = [torch.empty_like(logits) for _ in range(world_size)]
- dist.all_gather(all_logits, logits)
- logits = torch.cat(all_logits, dim=-1)
- return logits
-
-
-if __name__ == "__main__":
- torch.set_default_dtype(torch.bfloat16)
- torch.set_default_device("cuda")
- torch.manual_seed(0)
- args = ModelArgs()
- x = torch.randint(0, args.vocab_size, (2, 128))
- model = Transformer(args)
- print(model(x).size())
diff --git a/inference/requirements.txt b/inference/requirements.txt
deleted file mode 100644
index 68a60d0..0000000
--- a/inference/requirements.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-torch==2.4.1
-triton==3.0.0
-transformers==4.46.3
-safetensors==0.4.5
\ No newline at end of file