Draft
[WIP]dev_npu_async #2
&NewgateAdd on Oct 27
[WIP]dev_npu_async #2
Draft
Merged fromdev_npu_asyncintofreeze-mr3990
Total: 186 files changed+10413-3133
| @@ -1,5 +1,9 @@ | |||
| 1 | # <p align="center"> <img src="docs/LOGO.png" height="172px" width="598px"> </p> | 1 | # <p align="center"> <img src="docs/LOGO.png" height="172px" width="598px"> </p> |
| 2 | 2 | ||
| 3 | +<p align="center"> | ||
| 4 | + <a href="./README_en.md"> English </a> | 简体中文 | ||
| 5 | +</p> | ||
| 6 | + | ||
| 3 | <p align="center"> | 7 | <p align="center"> |
| 4 | <a> <img src="https://img.shields.io/badge/python-3.12-green"> </a> | 8 | <a> <img src="https://img.shields.io/badge/python-3.12-green"> </a> |
| 5 | <a> <img src="https://img.shields.io/badge/build-passing-green"> </a> | 9 | <a> <img src="https://img.shields.io/badge/build-passing-green"> </a> |
| @@ -78,6 +82,7 @@ MindSpeed/ | |||
| 78 | 82 | ||
| 79 | - [May 21, 2025]: 🚀 MindSpeed Core 支持Mcore 0.12.1版本。 | 83 | - [May 21, 2025]: 🚀 MindSpeed Core 支持Mcore 0.12.1版本。 |
| 80 | - [Aug 7, 2026]: 🚀 MindSpeed Core 完成Megatron-LM 0.18.0基础适配,架构分层解耦为MA + TENPU + MindSpeed,配合MegatronAdaptor 和 TransformerEngineNPU使用。 | 84 | - [Aug 7, 2026]: 🚀 MindSpeed Core 完成Megatron-LM 0.18.0基础适配,架构分层解耦为MA + TENPU + MindSpeed,配合MegatronAdaptor 和 TransformerEngineNPU使用。 |
| 85 | +- [Sep 20, 2026]: 🚀 MindSpeed Core 完成Megatron-LM 0.18.0 NPU加速特性适配,新增特性修复新版本的显存及性能问题,具体新增及变更特性参见[兼容性变更](./docs/zh/version_update.md)。 | ||
| 81 | 86 | ||
| 82 | > 注: 当前版本初步支持两种版本的Transformer实现。如需回溯老版本Transformer实现,需要用户配置参数`--transformer-impl local`。 | 87 | > 注: 当前版本初步支持两种版本的Transformer实现。如需回溯老版本Transformer实现,需要用户配置参数`--transformer-impl local`。 |
| 83 | 88 | ||
| @@ -93,16 +98,16 @@ MindSpeed/ | |||
| 93 | 98 | ||
| 94 | 当前版本推荐配套表如下: | 99 | 当前版本推荐配套表如下: |
| 95 | 100 | ||
| 96 | -| 软件 | 版本 | | 101 | +| 软件 | 版本 | |
| 97 | -|----------------------|--------------| | 102 | +|----------------------|----------------------| |
| 98 | -| MindSpeed Core 分支 | core_r0.18.0 | | 103 | +| MindSpeed Core 分支 | 26.2.0_core_r0.18.0 | |
| 99 | -| MegatronAdaptor | core_r0.18.0 | | 104 | +| MegatronAdaptor | 26.2.0_core_r0.18.0 | |
| 100 | -| TransformerEngineNPU | main | | 105 | +| TransformerEngineNPU | 26.2.0_release_v2.17 | |
| 101 | -| Megatron-LM 版本 | 0.18.0 | | 106 | +| Megatron-LM 版本 | core_v0.18.0 | |
| 102 | -| CANN 版本 | 9.1.0 | | 107 | +| CANN 版本 | 9.2.0 | |
| 103 | -| PyTorch | 2.7.1 | | 108 | +| PyTorch | 2.10.0 | |
| 104 | -| torch_npu 版本 | 26.1.0 | | 109 | +| torch_npu 版本 | 26.2.0 | |
| 105 | -| Python 版本 | Python3.12.x | | 110 | +| Python 版本 | Python3.12.x | |
| 106 | 111 | ||
| 107 | 更多具体说明请参考:[版本配套表](./docs/zh/release_notes_core.md#版本配套说明)。 | 112 | 更多具体说明请参考:[版本配套表](./docs/zh/release_notes_core.md#版本配套说明)。 |
| 108 | 113 | ||
| @@ -110,28 +115,30 @@ MindSpeed/ | |||
| 110 | 115 | ||
| 111 | --- | 116 | --- |
| 112 | 117 | ||
| 113 | -MindSpeed Core 当前版本基于 MA + TENPU + MindSpeed 三层架构,依赖关系如下: | 118 | +MindSpeed Core 当前版本基于 MA + TENPU + MindSpeed 三层架构,并按使用场景引入独立的 MindSpeed-Ops 算子包,依赖关系如下: |
| 114 | 119 | ||
| 115 | ```text | 120 | ```text |
| 116 | MegatronAdaptor (MA) ← NPU 基础适配,使 Megatron-LM 能运行 | 121 | MegatronAdaptor (MA) ← NPU 基础适配,使 Megatron-LM 能运行 |
| 117 | - └→ TransformerEngineNPU ← TE 算子的 NPU 实现,依赖 MA 完成设备初始化 | 122 | + ├→ TransformerEngineNPU ← TE 算子的 NPU 实现,依赖 MA 完成设备初始化 |
| 118 | - └→ MindSpeed Core ← 昇腾独有加速,依赖 MA + TENPU 提供基础能力 | 123 | + │ └→ MindSpeed Core ← 昇腾独有加速,依赖 MA + TENPU 提供基础能力 |
| 124 | + └→ MindSpeed-Ops ← 默认训练的权重梯度融合算子,按使用场景安装 | ||
| 119 | ``` | 125 | ``` |
| 120 | 126 | ||
| 121 | > **关键约束**: | 127 | > **关键约束**: |
| 122 | > | 128 | > |
| 123 | > - **安装顺序必须为 MA → TENPU → MindSpeed**,三者缺一不可。 | 129 | > - **安装顺序必须为 MA → TENPU → MindSpeed**,三者缺一不可。 |
| 130 | +> - Megatron-LM 默认开启权重梯度融合累加;默认参数训练还需单独安装 MindSpeed-Ops。MindSpeed 不会自动安装该独立算子包。 | ||
| 124 | > - TransformerEngineNPU 与原生 [TransformerEngine](https://github.com/NVIDIA/TransformerEngine) 库模块名相同(均为 `transformer_engine`),**严禁在同一环境中同时安装两者**。如果已安装原生 TE,请先执行 `pip uninstall transformer_engine` 卸载。 | 131 | > - TransformerEngineNPU 与原生 [TransformerEngine](https://github.com/NVIDIA/TransformerEngine) 库模块名相同(均为 `transformer_engine`),**严禁在同一环境中同时安装两者**。如果已安装原生 TE,请先执行 `pip uninstall transformer_engine` 卸载。 |
| 125 | > - MA 和 TENPU 各自有版本分支要求,请按下方步骤拉取对应分支,版本不匹配会导致运行时错误。 | 132 | > - MA 和 TENPU 各自有版本分支要求,请按下方步骤拉取对应分支,版本不匹配会导致运行时错误。 |
| 126 | 133 | ||
| 127 | ## 使用源码安装 | 134 | ## 使用源码安装 |
| 128 | 135 | ||
| 129 | -获取并切换Megatron-LM版本至 core_r0.18.0 版本,可参考: | 136 | +获取并切换Megatron-LM版本至 core_v0.18.2 版本,可参考: |
| 130 | 137 | ||
| 131 | ```shell | 138 | ```shell |
| 132 | git clone https://github.com/NVIDIA/Megatron-LM.git | 139 | git clone https://github.com/NVIDIA/Megatron-LM.git |
| 133 | cd Megatron-LM | 140 | cd Megatron-LM |
| 134 | -git checkout core_r0.18.0 | 141 | +git checkout core_v0.18.2 |
| 135 | ``` | 142 | ``` |
| 136 | 143 | ||
| 137 | ### 安装 MegatronAdaptor(NPU 基础适配层) | 144 | ### 安装 MegatronAdaptor(NPU 基础适配层) |
| @@ -139,7 +146,7 @@ git checkout core_r0.18.0 | |||
| 139 | ```shell | 146 | ```shell |
| 140 | git clone https://gitcode.com/Ascend/MegatronAdaptor.git | 147 | git clone https://gitcode.com/Ascend/MegatronAdaptor.git |
| 141 | cd MegatronAdaptor | 148 | cd MegatronAdaptor |
| 142 | -git checkout core_r0.18.0 | 149 | +git checkout 26.2.0_core_r0.18.0 |
| 143 | cd .. | 150 | cd .. |
| 144 | pip install -e MegatronAdaptor | 151 | pip install -e MegatronAdaptor |
| 145 | ``` | 152 | ``` |
| @@ -154,7 +161,10 @@ pip uninstall -y transformer_engine | |||
| 154 | 161 | ||
| 155 | # 安装 TENPU | 162 | # 安装 TENPU |
| 156 | git clone https://gitcode.com/Ascend/TransformerEngineNPU.git | 163 | git clone https://gitcode.com/Ascend/TransformerEngineNPU.git |
| 157 | -pip install -e TransformerEngineNPU | 164 | +cd TransformerEngineNPU |
| 165 | +git checkout 26.2.0_release_v2.17 | ||
| 166 | +cd .. | ||
| 167 | +pip install -e TransformerEngineNPU --no-build-isolaton | ||
| 158 | ``` | 168 | ``` |
| 159 | 169 | ||
| 160 | > **验证**:执行 `pip show transformer_engine`,确认显示的路径为 `TransformerEngineNPU` 目录。 | 170 | > **验证**:执行 `pip show transformer_engine`,确认显示的路径为 `TransformerEngineNPU` 目录。 |
| @@ -166,11 +176,33 @@ pip install -e TransformerEngineNPU | |||
| 166 | ```shell | 176 | ```shell |
| 167 | git clone https://gitcode.com/Ascend/MindSpeed.git | 177 | git clone https://gitcode.com/Ascend/MindSpeed.git |
| 168 | cd MindSpeed | 178 | cd MindSpeed |
| 169 | -git checkout core_r0.18.0 | 179 | +git checkout 26.2.0_core_r0.18.0 |
| 170 | cd .. | 180 | cd .. |
| 171 | pip install -e MindSpeed | 181 | pip install -e MindSpeed |
| 172 | ``` | 182 | ``` |
| 173 | 183 | ||
| 184 | +### 按场景安装 MindSpeed-Ops(默认参数训练需要) | ||
| 185 | + | ||
| 186 | +Megatron-LM 默认开启 `gradient_accumulation_fusion`。该路径在 NPU 上调用 MindSpeed-Ops 提供的 MatmulAdd 接口,因此是否需要安装取决于实际场景: | ||
| 187 | + | ||
| 188 | +| 使用场景 | 是否需要安装 MindSpeed-Ops | | ||
| 189 | +|---------|--------------------------| | ||
| 190 | +| 默认参数训练,且模型包含 Megatron 原生张量并行 Linear(如 output layer) | 需要 | | ||
| 191 | +| 训练参数包含 `--no-gradient-accumulation-fusion` | 不需要 | | ||
| 192 | +| 纯推理或评估,不执行反向传播 | 不需要 | | ||
| 193 | + | ||
| 194 | +默认参数训练请执行: | ||
| 195 | + | ||
| 196 | +```shell | ||
| 197 | +git clone https://gitcode.com/Ascend/MindSpeed-Ops.git | ||
| 198 | +cd MindSpeed-Ops | ||
| 199 | +pip install -e . --extra-index-url=https://triton-ascend.osinfra.cn/pypi/simple --no-build-isolation --no-deps | ||
| 200 | +python -c "from mindspeed_ops.api.atb.npu_matmul_add import npu_matmul_add_fp32, npu_matmul_add_fp16; print('MindSpeed-Ops MatmulAdd API loaded successfully')" | ||
| 201 | +cd .. | ||
| 202 | +``` | ||
| 203 | + | ||
| 204 | +> Atlas A2/A3 训练系列产品的 fp32 主梯度路径使用 ATB JIT 融合算子,需要安装 CANN-NNAL、加载 `nnal/atb/set_env.sh` 并提供 C++/Ninja 编译工具链。详细说明请参见 [MindSpeed-Ops 软件安装](https://gitcode.com/Ascend/MindSpeed-Ops/blob/master/docs/zh/install_guide.md)。 | ||
| 205 | + | ||
| 174 | ### 环境验证 | 206 | ### 环境验证 |
| 175 | 207 | ||
| 176 | 安装完成后,可在Python中验证各组件是否正确安装: | 208 | 安装完成后,可在Python中验证各组件是否正确安装: |
| @@ -184,6 +216,9 @@ import transformer_engine # 无报错即 TENPU 正常(非原生 TE) | |||
| 184 | 216 | ||
| 185 | # 验证 MindSpeed | 217 | # 验证 MindSpeed |
| 186 | import mindspeed.megatron_adaptor # 无报错即 MindSpeed 正常加载 | 218 | import mindspeed.megatron_adaptor # 无报错即 MindSpeed 正常加载 |
| 219 | + | ||
| 220 | +# 默认参数训练还需验证 MindSpeed-Ops MatmulAdd API | ||
| 221 | +from mindspeed_ops.api.atb.npu_matmul_add import npu_matmul_add_fp32, npu_matmul_add_fp16 | ||
| 187 | ``` | 222 | ``` |
| 188 | 223 | ||
| 189 | 具体请参考 [部署文档](./docs/zh/user-guide/install_guide.md) 了解硬件/OS 兼容性、CANN/PyTorch/torch_npu 安装等详细前置步骤。 | 224 | 具体请参考 [部署文档](./docs/zh/user-guide/install_guide.md) 了解硬件/OS 兼容性、CANN/PyTorch/torch_npu 安装等详细前置步骤。 |
| @@ -203,9 +238,8 @@ import mindspeed.megatron_adaptor # 无报错即 MindSpeed 正常加载 | |||
| 203 | ```python | 238 | ```python |
| 204 | import torch | 239 | import torch |
| 205 | import megatron_adaptor # 新增代码行 | 240 | import megatron_adaptor # 新增代码行 |
| 206 | - from functools import partial | 241 | + from gpt_builders import gpt_builder |
| 207 | - from contextlib import nullcontext | 242 | + from megatron.core import mpu |
| 208 | - import inspect | ||
| 209 | ``` | 243 | ``` |
| 210 | 244 | ||
| 211 | 具体操作可以参考[快速上手指导](./docs/zh/user-guide/quickstart.md)。 | 245 | 具体操作可以参考[快速上手指导](./docs/zh/user-guide/quickstart.md)。 |
| @@ -215,7 +249,7 @@ MindSpeed LLM和MindSpeed MM的快速上手指导可参考: | |||
| 215 | - 大语言模型训练 | 249 | - 大语言模型训练 |
| 216 | - [基于PyTorch框架](https://gitcode.com/Ascend/MindSpeed-LLM/blob/master/docs/zh/pytorch/training/quick_start.md) | 250 | - [基于PyTorch框架](https://gitcode.com/Ascend/MindSpeed-LLM/blob/master/docs/zh/pytorch/training/quick_start.md) |
| 217 | - 多模态模型训练 | 251 | - 多模态模型训练 |
| 218 | - - [基于PyTorch框架](https://gitcode.com/Ascend/MindSpeed-MM/blob/master/docs/zh/pytorch/quickstart.md) | 252 | + - [基于PyTorch框架](https://gitcode.com/Ascend/MindSpeed-MM/blob/master/docs/zh/guides/practices/quickstart.md) |
| 219 | 253 | ||
| 220 | # 加速特性分级说明 | 254 | # 加速特性分级说明 |
| 221 | 255 | ||
| @@ -266,7 +300,7 @@ MindSpeed 特性由七大模块组成,分别为:Megatron特性支持、并 | |||
| 266 | 300 | ||
| 267 | - 当前大模型训练主要使用bf16数据类型,以下特性若无特殊声明原则上兼容fp16,如使用其它数据类型遇到问题可提交issue,我们会快速响应。🛰️ | 301 | - 当前大模型训练主要使用bf16数据类型,以下特性若无特殊声明原则上兼容fp16,如使用其它数据类型遇到问题可提交issue,我们会快速响应。🛰️ |
| 268 | 302 | ||
| 269 | -- 注意❗:在Megatron_core_r0.9.0后,alltoall dispatcher进行了调整,原版本alltoall dispatcher重命名为alltoall_seq。MindSpeed MoE特性对各分支的支持情况,见各特性说明。 | 303 | +- 注意❗:在Megatron_core_r0.18.0后,alltoall dispatcher进行了调整,alltoall_seq不再支持。MindSpeed MoE特性对各分支的支持情况,见各特性说明。 |
| 270 | 304 | ||
| 271 | 各特性支持情况请查看[MindSpeed Core 特性支持情况](./docs/zh/features/feature_list.md)。 | 305 | 各特性支持情况请查看[MindSpeed Core 特性支持情况](./docs/zh/features/feature_list.md)。 |
| 272 | 306 | ||
| @@ -361,16 +395,7 @@ MindSpeed docs目录下的文档适用CC-BY 4.0许可证,具体请参见[LICEN | |||
| 361 | 395 | ||
| 362 | --- | 396 | --- |
| 363 | 397 | ||
| 364 | -🔎 MindSpeed-Core 由华为公司的下列部门联合贡献 : | 398 | +🔎 MindSpeed-Core 由华为技术有限公司与开发者联合贡献, |
| 365 | - | ||
| 366 | -华为公司: | ||
| 367 | - | ||
| 368 | -- 昇腾计算产品部 | ||
| 369 | -- 计算算法部 | ||
| 370 | -- 计算软件平台部 | ||
| 371 | -- 计算技术开发部 | ||
| 372 | -- 公共开发部:NAIE | ||
| 373 | -- 网络技术实验室 | ||
| 374 | 399 | ||
| 375 | 此外,MindSpeed-Core 感谢以下团队对项目的贡献: | 400 | 此外,MindSpeed-Core 感谢以下团队对项目的贡献: |
| 376 | 401 | ||
| @@ -106,7 +106,7 @@ run_st() { | |||
| 106 | fi | 106 | fi |
| 107 | 107 | ||
| 108 | # --- Resolve Megatron-LM branch from README.md --- | 108 | # --- Resolve Megatron-LM branch from README.md --- |
| 109 | - checkout_lines=$(grep "git checkout" "${code_dir}/README.md" | awk '{print substr($0, index($0,$3))}' | tail -n 1 || true) | 109 | + checkout_lines="core_r0.18.0" |
| 110 | echo "Resolved Megatron-LM ref: ${checkout_lines}" | 110 | echo "Resolved Megatron-LM ref: ${checkout_lines}" |
| 111 | if [ -z "$checkout_lines" ]; then | 111 | if [ -z "$checkout_lines" ]; then |
| 112 | echo "ERROR: No valid git checkout line found in README.md" | 112 | echo "ERROR: No valid git checkout line found in README.md" |
| @@ -102,7 +102,7 @@ run_ut() { | |||
| 102 | fi | 102 | fi |
| 103 | 103 | ||
| 104 | # --- Resolve Megatron-LM branch from README.md --- | 104 | # --- Resolve Megatron-LM branch from README.md --- |
| 105 | - checkout_lines=$(grep "git checkout" "${code_dir}/README.md" | awk '{print substr($0, index($0,$3))}' | tail -n 1 || true) | 105 | + checkout_lines="core_r0.18.0" |
| 106 | echo "Resolved Megatron-LM ref: ${checkout_lines}" | 106 | echo "Resolved Megatron-LM ref: ${checkout_lines}" |
| 107 | if [ -z "$checkout_lines" ]; then | 107 | if [ -z "$checkout_lines" ]; then |
| 108 | echo "ERROR: No valid git checkout line found in README.md" | 108 | echo "ERROR: No valid git checkout line found in README.md" |
| @@ -73,7 +73,7 @@ Table 1 Recommended maximum values for file (folder) permission control in vario | |||
| 73 | | Introduced by open-source | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/sharded_moe.py> | mindspeed/moe/utils.py | <https://arxiv.org/pdf/2006.16668.pdf> | einsum paper address | | 73 | | Introduced by open-source | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/sharded_moe.py> | mindspeed/moe/utils.py | <https://arxiv.org/pdf/2006.16668.pdf> | einsum paper address | |
| 74 | | Introduced by open-source | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/experts.py> | mindspeed/moe/experts.py | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/experts.py> | DeepSpeed MoE source code address | | 74 | | Introduced by open-source | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/experts.py> | mindspeed/moe/experts.py | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/experts.py> | DeepSpeed MoE source code address | |
| 75 | | Introduced by open-source | <https://github.com/HazyResearch/flash-attention> | docs/en/features/flash-attention.md | <https://arxiv.org/pdf/2205.14135> | Flash-attention documentation | | 75 | | Introduced by open-source | <https://github.com/HazyResearch/flash-attention> | docs/en/features/flash-attention.md | <https://arxiv.org/pdf/2205.14135> | Flash-attention documentation | |
| 76 | -| Introduced by open-source | <https://github.com/nvidia/megatron-lm> | docs/en/features/virtual-pipeline-parallel.md | <https://people.eecs.berkeley.edu/~matei/papers/2021/sc_megatron_lm.pdf> | Virtual-pipeline-parallel documentation | | 76 | +| Introduced by open-source | <https://github.com/nvidia/megatron-lm> | docs/en/features/virtual-pipeline-parallel.md | <https://dl.acm.org/doi/10.1145/3458817.3476209> | Virtual-pipeline-parallel documentation | |
| 77 | | Introduced by open-source | <https://github.com/feifeibear/long-context-attention> | docs/en/features/hybrid-context-parallel.md | <https://arxiv.org/abs/2405.07719> | Hybrid-context-parallel documentation | | 77 | | Introduced by open-source | <https://github.com/feifeibear/long-context-attention> | docs/en/features/hybrid-context-parallel.md | <https://arxiv.org/abs/2405.07719> | Hybrid-context-parallel documentation | |
| 78 | | Introduced by open-source | <https://github.com/feifeibear/long-context-attention> | docs/en/features/ring-attention-context-parallel.md | <https://arxiv.org/pdf/2310.01889> | Ring-attention-context-parallel documentation | | 78 | | Introduced by open-source | <https://github.com/feifeibear/long-context-attention> | docs/en/features/ring-attention-context-parallel.md | <https://arxiv.org/pdf/2310.01889> | Ring-attention-context-parallel documentation | |
| 79 | | Introduced by open-source | <https://github.com/ofirpress/attention_with_linear_biases> | docs/en/features/alibi.md | <https://arxiv.org/pdf/2108.12409> | Alibi documentation | | 79 | | Introduced by open-source | <https://github.com/ofirpress/attention_with_linear_biases> | docs/en/features/alibi.md | <https://arxiv.org/pdf/2108.12409> | Alibi documentation | |
| @@ -16,23 +16,49 @@ When DP > 1, the model weights occupy a large amount of memory, and you want to | |||
| 16 | 16 | ||
| 17 | To enable fully sharded data parallelism, add the following configuration: | 17 | To enable fully sharded data parallelism, add the following configuration: |
| 18 | 18 | ||
| 19 | - ```bash | 19 | +```bash |
| 20 | - --use-custom-fsdp | 20 | +--use-megatron-fsdp |
| 21 | - --data-parallel-sharding-strategy optim_grads_params | 21 | +--data-parallel-sharding-strategy optim_grads_params |
| 22 | - --no-gradient-accumulation-fusion | 22 | +--no-gradient-accumulation-fusion |
| 23 | - --use-distributed-optimizer | 23 | +--use-distributed-optimizer |
| 24 | - ``` | 24 | +--ckpt-format fsdp_dtensor |
| 25 | +``` | ||
| 26 | + | ||
| 27 | +`core_r0.18.0` uses the Megatron FSDP interface. The legacy `--use-custom-fsdp` flag remains supported and is mapped to `--use-megatron-fsdp` before Megatron argument validation. The checkpoint format must be `fsdp_dtensor`. | ||
| 25 | 28 | ||
| 26 | You need to disable `CUDA_DEVICE_MAX_CONNECTIONS`. | 29 | You need to disable `CUDA_DEVICE_MAX_CONNECTIONS`. |
| 27 | 30 | ||
| 28 | - ```bash | 31 | +```bash |
| 29 | - unset CUDA_DEVICE_MAX_CONNECTIONS | 32 | +unset CUDA_DEVICE_MAX_CONNECTIONS |
| 30 | - ``` | 33 | +``` |
| 31 | 34 | ||
| 32 | ## Effects | 35 | ## Effects |
| 33 | 36 | ||
| 34 | -The model and weights are further sharded, reducing memory usage. However, because additional communication is introduced in each forward and backward pass, performance will decrease. | 37 | +Sharding parameters, gradients, and optimizer states can reduce persistent training-state memory. Parameter all-gathers add communication, while separate reduce-scatter outputs and communication dtype conversion require temporary buffers. Measure peak memory and iteration time with the target model and parallel configuration. |
| 35 | 38 | ||
| 36 | > [!NOTE] | 39 | > [!NOTE] |
| 37 | > | 40 | > |
| 38 | > MindSpeed adapts the basic functionality of this feature. It is not recommended to combine it with other features in the repository. For usage, [refer to this script](../../../tests_extend/system_tests/feature_tests/custom_fsdp.sh). | 41 | > MindSpeed adapts the basic functionality of this feature. It is not recommended to combine it with other features in the repository. For usage, [refer to this script](../../../tests_extend/system_tests/feature_tests/custom_fsdp.sh). |
| 42 | + | ||
| 43 | +The 0.18 adaptation uses the new gradient bucket reduction pipeline and preserves communication dtype conversion, double buffering, and asynchronous release. The HCCL path uses separate reduce-scatter output storage. In the SUM path, gradients are scaled once before communication without relying on NCCL premultiplied SUM. The MoE router follows the 0.18 implementation, preserving its bias and router dtype support. | ||
| 44 | + | ||
| 45 | +The existing `custom_fsdp.sh` MoE test from master is reused. In 0.18, `--moe-grouped-gemm` requires `--transformer-impl transformer_engine`. Training accuracy and `fsdp_dtensor` checkpoint save/restore still need validation on multiple Ascend devices. | ||
| 46 | + | ||
| 47 | +## Dependencies and Support Boundaries | ||
| 48 | + | ||
| 49 | +Use a TransformerEngineNPU version containing the DTensor FusedAdam fix, such as commit [5c85c0d](https://gitcode.com/GuoHaifeng1999/TransformerEngineNPU/commit/5c85c0df3e9c1887a4aa5a000f96b2f01d9fb031), and verify that the training process imports that installation. Older TENPU versions reject DTensor parameters; selecting `fsdp_dtensor` alone does not resolve this optimizer error. | ||
| 50 | + | ||
| 51 | +| Item | Current adaptation | | ||
| 52 | +|------|--------------------| | ||
| 53 | +| Basic FSDP | Megatron FSDP in Core 0.18; the existing script uses `optim_grads_params`, not PyTorch FSDP2 | | ||
| 54 | +| Parameters and gradients | Unquantized FP32/FP16/BF16 DTensor parameters, ordinary or decoupled gradients, and empty local shards through the matching TENPU version | | ||
| 55 | +| Optimizer states | Floating-point moments and the existing FP32/FP16 master-weight paths | | ||
| 56 | +| Communication lifecycle | Upstream communication dtype, double buffering, and asynchronous release are preserved; target-device validation remains necessary | | ||
| 57 | +| HSDP/HFSDP and AVG | Existing branches are retained with separate RS outputs; multi-device combinations remain unverified | | ||
| 58 | +| Quantization and remainders | The TENPU DTensor path does not support quantized model parameters, FP8/uint8 moments, or INT16 parameter remainders | | ||
| 59 | +| Checkpoints | Existing `fsdp_dtensor` save/load integration; real multi-device I/O and recovery with a different DP size remain unverified | | ||
| 60 | +| Feature combinations | Arbitrary combinations are not guaranteed; the existing MoE script also requires Ascend accuracy and performance validation | | ||
| 61 | + | ||
| 62 | +These are implementation boundaries, not claims that all configurations have passed NPU end-to-end tests. CPU local-shard checks do not replace HCCL or real checkpoint validation. The Core 0.18 checkpoint default remains `torch_dist`; explicitly selecting `fsdp_dtensor` does not convert existing checkpoints. | ||
| 63 | + | ||
| 64 | +The default script exits at iteration 50 but uses a save interval of 2000, and it includes `--no-load-optim` and `--no-load-rng`. To validate full recovery, configure save/load directories and an appropriate save interval in the same existing test, remove those two options, and compare the next-step parameters, optimizer states, and loss. Prepare the data and tokenizer paths before running it. | ||
| @@ -14,7 +14,7 @@ Figure 1 Virtual pipeline parallelism | |||
| 14 | 14 | ||
| 15 |  | 15 |  |
| 16 | 16 | ||
| 17 | -For more details, see the paper [Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM](https://people.eecs.berkeley.edu/~matei/papers/2021/sc_megatron_lm.pdf). | 17 | +For more details, see the paper [Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM](https://dl.acm.org/doi/10.1145/3458817.3476209). |
| 18 | 18 | ||
| 19 | For example, assuming the model has a total of 16 layers, tensor parallelism size is 1, pipeline parallelism size is 4, and virtual pipeline parallelism size is 2, the model will be divided into 4 * 2 = 8 stages, with each stage containing 16/8 = 2 layers, as shown below: | 19 | For example, assuming the model has a total of 16 layers, tensor parallelism size is 1, pipeline parallelism size is 4, and virtual pipeline parallelism size is 2, the model will be divided into 4 * 2 = 8 stages, with each stage containing 16/8 = 2 layers, as shown below: |
| 20 | 20 | ||
| @@ -128,8 +128,7 @@ self.start grad sync() | |||
| 128 | File “/home/Megatron-LM/megatron/core/distributed/param and grad buffer.py", Line 114, in start_grad_s | 128 | File “/home/Megatron-LM/megatron/core/distributed/param and grad buffer.py", Line 114, in start_grad_s |
| 129 | ync | 129 | ync |
| 130 | assert not norm.isnan( ), ( | 130 | assert not norm.isnan( ), ( |
| 131 | -AssertionError: Rank 13: found NaN in local grad norm in backward pass before data-parallel communication collectie | 131 | +AssertionError: Rank 13: found NaN in local grad norm in backward pass before data-parallel communication collectieve. Device: 5, node: node-15-11 |
| 132 | -ve. Device: 5, node: node-15-11 | ||
| 133 | ``` | 132 | ``` |
| 134 | 133 | ||
| 135 | ### 问题根因 | 134 | ### 问题根因 |
| @@ -73,7 +73,7 @@ | |||
| 73 | | 开源引入 | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/sharded_moe.py> | mindspeed/moe/utils.py | <https://arxiv.org/pdf/2006.16668.pdf> | einsum论文地址 | | 73 | | 开源引入 | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/sharded_moe.py> | mindspeed/moe/utils.py | <https://arxiv.org/pdf/2006.16668.pdf> | einsum论文地址 | |
| 74 | | 开源引入 | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/experts.py> | mindspeed/moe/experts.py | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/experts.py> | deepspeed moe源码地址 | | 74 | | 开源引入 | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/experts.py> | mindspeed/moe/experts.py | <https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/moe/experts.py> | deepspeed moe源码地址 | |
| 75 | | 开源引入 | <https://github.com/HazyResearch/flash-attention> | docs/zh/features/flash-attention.md | <https://arxiv.org/pdf/2205.14135> | flash-attention说明文档 | | 75 | | 开源引入 | <https://github.com/HazyResearch/flash-attention> | docs/zh/features/flash-attention.md | <https://arxiv.org/pdf/2205.14135> | flash-attention说明文档 | |
| 76 | -| 开源引入 | <https://github.com/nvidia/megatron-lm> | docs/zh/features/virtual-pipeline-parallel.md | <https://people.eecs.berkeley.edu/~matei/papers/2021/sc_megatron_lm.pdf> | virtual-pipeline-parallel说明文档 | | 76 | +| 开源引入 | <https://github.com/nvidia/megatron-lm> | docs/zh/features/virtual-pipeline-parallel.md | <https://dl.acm.org/doi/10.1145/3458817.3476209> | virtual-pipeline-parallel说明文档 | |
| 77 | | 开源引入 | <https://github.com/feifeibear/long-context-attention> | docs/zh/features/hybrid-context-parallel.md | <https://arxiv.org/abs/2405.07719> | hybrid-context-parallel说明文档 | | 77 | | 开源引入 | <https://github.com/feifeibear/long-context-attention> | docs/zh/features/hybrid-context-parallel.md | <https://arxiv.org/abs/2405.07719> | hybrid-context-parallel说明文档 | |
| 78 | | 开源引入 | <https://github.com/feifeibear/long-context-attention> | docs/zh/features/ring-attention-context-parallel.md | <https://arxiv.org/pdf/2310.01889> | ring-attention-context-parallel说明文档 | | 78 | | 开源引入 | <https://github.com/feifeibear/long-context-attention> | docs/zh/features/ring-attention-context-parallel.md | <https://arxiv.org/pdf/2310.01889> | ring-attention-context-parallel说明文档 | |
| 79 | | 开源引入 | <https://github.com/ofirpress/attention_with_linear_biases> | docs/zh/features/alibi.md | <https://arxiv.org/pdf/2108.12409> | alibi说明文档 | | 79 | | 开源引入 | <https://github.com/ofirpress/attention_with_linear_biases> | docs/zh/features/alibi.md | <https://arxiv.org/pdf/2108.12409> | alibi说明文档 | |
| @@ -24,7 +24,7 @@ | |||
| 24 | 图2 一种典型的QoS调度方式——SP调度 | 24 | 图2 一种典型的QoS调度方式——SP调度 |
| 25 | </div> | 25 | </div> |
| 26 | 26 | ||
| 27 | -  如图2所示,将不同类型流量映射至不同的VL,实现流量隔离的目的,并设置不同VL的优先级,采用SP方式(Strict Priority)进行调度,则不同类型流量同时达到UB Switch时,会优先将高优先级VL调度排空后,再调度下一级队列,依此类推,以达到不同类型流量差异化调度的目的。 | 27 | +  如图2所示,将不同类型流量映射至不同的VL,实现流量隔离的目的,并设置不同VL的优先级,采用SP方式(Strict Priority)进行调度,则不同类型流量同时到达UB Switch时,会优先将高优先级VL调度排空后,再调度下一级队列,依此类推,以达到不同类型流量差异化调度的目的。 |
| 28 | 28 | ||
| 29 | ## 2 方案介绍 | 29 | ## 2 方案介绍 |
| 30 | 30 | ||
| @@ -33,7 +33,7 @@ | |||
| 33 |   2)VL间进行差异化调度,从而实现提高整体算效的目的。 | 33 |   2)VL间进行差异化调度,从而实现提高整体算效的目的。 |
| 34 |   特性提供两种类型使能方式: | 34 |   特性提供两种类型使能方式: |
| 35 |   1)自动模式,AI QoS通过感知AI大模型训练的流量类型、通信域、通信量以及算效贡献等,设计了一种算效优先的优先级映射与调度算法,并实现不同类型流量冲突度最小的VL映射以及算效优先的差异化QoS调度 | 35 |   1)自动模式,AI QoS通过感知AI大模型训练的流量类型、通信域、通信量以及算效贡献等,设计了一种算效优先的优先级映射与调度算法,并实现不同类型流量冲突度最小的VL映射以及算效优先的差异化QoS调度 |
| 36 | -  2)手动模式,用户可手工指定不同类型并行策略的QoS优先级,AI QoS按照用户手工指定的优先级,经过多层传递与QoS语义映射,将任务级的QoS语义转换为UB协议QoS语义,在UB报文中设置QoS值,并映射至UB Switch的相应VL,在VL间进行差异化调度。手动模式支持Low/Middle/High三档位的QoS优先级。 | 36 | +  2)手动模式,用户可手动指定不同类型并行策略的QoS优先级,AI QoS按照用户手动指定的优先级,经过多层传递与QoS语义映射,将任务级的QoS语义转换为UB协议QoS语义,在UB报文中设置QoS值,并映射至UB Switch的相应VL,在VL间进行差异化调度。手动模式支持Low/Middle/High三档位的QoS优先级。 |
| 37 |   注:H2D流量由于底层能力,只支持通道级整体QoS优先级,暂不支持算子级QoS优先级,即仅支持H2D流量与D2D等其他流量区分QoS优先级,不支持同为H2D流量的不同算子间的QoS优先级区分。 | 37 |   注:H2D流量由于底层能力,只支持通道级整体QoS优先级,暂不支持算子级QoS优先级,即仅支持H2D流量与D2D等其他流量区分QoS优先级,不支持同为H2D流量的不同算子间的QoS优先级区分。 |
| 38 |   方案整体架构如图3所示: | 38 |   方案整体架构如图3所示: |
| 39 | 39 | ||
| @@ -15,7 +15,7 @@ | |||
| 15 | 15 | ||
| 16 | ### b. 同时启用分布式优化器与梯度通信重叠,即打开 `--use-distributed-optimizer` 和 `--overlap-grad-reduce` | 16 | ### b. 同时启用分布式优化器与梯度通信重叠,即打开 `--use-distributed-optimizer` 和 `--overlap-grad-reduce` |
| 17 | 17 | ||
| 18 | -在打开`--use-distributed-optimizer`的同时打开`--overlap-grad-reduce`,运行流程如下图所示。对梯度的reduce-scatter过程与反向计算过程并行,从而避免了额外的reduce-scatter时间,显著提高了计算与通信的并行效率,如下图所示。 | 18 | +在打开`--use-distributed-optimizer`的同时打开`--overlap-grad-reduce`,运行流程如下图所示。梯度的reduce-scatter过程与反向计算过程并行,从而避免了额外的reduce-scatter时间,显著提高了计算与通信的并行效率,如下图所示。 |
| 19 | <p align="center"> <img src="../figures/async_ddp_param_gather_b.png" height="350px" width="880px"></p> | 19 | <p align="center"> <img src="../figures/async_ddp_param_gather_b.png" height="350px" width="880px"></p> |
| 20 | 20 | ||
| 21 | ### c. 启用分布式优化器、梯度通信重叠与参数聚合重叠,即打开 `--use-distributed-optimizer` 和 `--overlap-grad-reduce` 和 `--overlap-param-gather` | 21 | ### c. 启用分布式优化器、梯度通信重叠与参数聚合重叠,即打开 `--use-distributed-optimizer` 和 `--overlap-grad-reduce` 和 `--overlap-param-gather` |
| @@ -86,4 +86,4 @@ ATB安装方法: | |||
| 86 | 86 | ||
| 87 | 当前暂未适配MoE模型。 | 87 | 当前暂未适配MoE模型。 |
| 88 | 88 | ||
| 89 | -Atlas A2 训练系列产品 / Atlas A3 训练系列产品完全支持此特性,而 Ascend 950 系列产品不支持开启融合算子。 | 89 | +Atlas A2训练系列产品 / Atlas A3训练系列产品完全支持此特性,而Ascend 950PR&950DT系列产品不支持开启融合算子。 |
| @@ -1,42 +0,0 @@ | |||
| 1 | -# compress-activation | ||
| 2 | - | ||
| 3 | -## 背景与挑战 | ||
| 4 | - | ||
| 5 | -随着序列长度增加激活值显存占比会逐渐增加,导致单卡峰值内存过高。 | ||
| 6 | - | ||
| 7 | -通过昇腾无损压缩算子压缩激活值占用的内存。可使用下面的激活压缩入口。 | ||
| 8 | - | ||
| 9 | -- 特性一:`--compress-dense` 对MLP模块中第一个线性层所产生的激活值进行压缩。 | ||
| 10 | -- 特性二:`--compress-activation` 对选定transformer layer所产生的激活值进行压缩。 | ||
| 11 | - | ||
| 12 | -## 解决方案 | ||
| 13 | - | ||
| 14 | -- 特性一: | ||
| 15 | -记录首节点MLP执行顺序,对Dense层MLP模块产生的激活值使用多流异步的方式调用昇腾无损压缩算子进行内存压缩,由于该算子使用vector算力,能够和cube计算及通信做掩盖,压缩及解压缩过程本身基本不会导致性能劣化。具体方法如下图所示: | ||
| 16 | - | ||
| 17 | - | ||
| 18 | -- 特性二: | ||
| 19 | -记录各卡transformer layer的执行顺序,对layer中产生的激活值做无损压缩。通过多流异步的方式调用昇腾无损压缩算子进行内存压缩,压缩算子使用vector算力,能够和cube计算及通信做掩盖,压缩及解压缩过程本身基本不会导致性能劣化。具体流程如下图所示: | ||
| 20 | - | ||
| 21 | - | ||
| 22 | -## 使用场景 | ||
| 23 | - | ||
| 24 | -训练内存不足的大模型训练场景。 | ||
| 25 | - | ||
| 26 | -## 使用方法 | ||
| 27 | - | ||
| 28 | -- 特性一: | ||
| 29 | - `--compress-dense level0` 只进行Vector压缩,节省空间较少,带来极小的性能开销。 | ||
| 30 | - `--compress-dense level1` 在进行Vector压缩的同时,将部分结果swap到CPU上,节省空间较多,但是带来额外的性能开销。 | ||
| 31 | -- 特性二: | ||
| 32 | - `--compress-activation` 表示压缩哪些层产生的激活值,可配置为`1-3`或`1,2,3`,表示压缩1/2/3层产生的激活值,可配置为`1-3,5-8,10`表示压缩1/2/3/5/6/7/8/10层产生的激活值,也可配置为0表示压缩所有层,默认值为空字符串(不启用)。 | ||
| 33 | - | ||
| 34 | -## 使用效果 | ||
| 35 | - | ||
| 36 | -使用激活值压缩特性会降低峰值内存。在如llama,qwen等典型模型下,开启特性一/二平均内存收益在3%/7%。如:qwen3-8b模型在序列长度为8192,并行配置为PP4TP2CP1,开启特性二的情况下获得内存收益6.2%。 | ||
| 37 | - | ||
| 38 | -## 使用约束 | ||
| 39 | - | ||
| 40 | -- 激活值压缩需配套 PTA 支持。 | ||
| 41 | - | ||
| 42 | -- 特性二为特性一的迭代版本,训练时选择其中一种。 | ||
| @@ -0,0 +1,70 @@ | |||
| 1 | +# Megatron 全分片数据并行(Fully Sharded Data Parallel, FSDP) | ||
| 2 | + | ||
| 3 | +## 背景与挑战 | ||
| 4 | + | ||
| 5 | +随着大模型权重增加,需要进一步提高显存利用效率。ZeRO-1 只在 DP 域内切分优化器状态,模型权重和梯度仍占用较多常驻显存。FSDP 进一步切分权重和梯度,以降低每个 DP rank 的常驻训练状态占用。 | ||
| 6 | + | ||
| 7 | +本文介绍 `core_r0.18.0` 中 Megatron FSDP 的基础适配,不是 PyTorch FSDP2。 | ||
| 8 | + | ||
| 9 | +## 解决方案 | ||
| 10 | + | ||
| 11 | +在 `optim_grads_params` 策略下,每个 DP rank 常驻参数分片。前向和反向计算需要完整参数时,在 DP 域内执行 All Gather;计算结束后按上游缓冲区生命周期释放不再需要的完整参数。反向梯度通过 Reduce Scatter 归约并切分,各 rank 使用本地梯度分片更新对应参数。 | ||
| 12 | + | ||
| 13 | +0.18 适配沿用新的梯度 bucket 归约流程,保留通信 dtype 转换、双缓冲和异步释放逻辑。HCCL reduce-scatter 使用独立输出存储;SUM 路径在通信前显式缩放一次,不依赖 NCCL premultiplied SUM。MoE router 沿用 0.18 实现,保留 bias 和 router dtype 支持。 | ||
| 14 | + | ||
| 15 | +## 使用场景 | ||
| 16 | + | ||
| 17 | +DP 大于 1,模型权重、梯度和优化器状态占用较多显存,希望进一步切分这些训练状态。 | ||
| 18 | + | ||
| 19 | +## 使用方法 | ||
| 20 | + | ||
| 21 | +1. 开启 Megatron FSDP,加入以下配置: | ||
| 22 | + | ||
| 23 | + ```bash | ||
| 24 | + --use-megatron-fsdp | ||
| 25 | + --data-parallel-sharding-strategy optim_grads_params | ||
| 26 | + --no-gradient-accumulation-fusion | ||
| 27 | + --use-distributed-optimizer | ||
| 28 | + --ckpt-format fsdp_dtensor | ||
| 29 | + ``` | ||
| 30 | + | ||
| 31 | + 仍兼容 master 的 `--use-custom-fsdp`,在 Megatron 参数校验前将其映射到 `--use-megatron-fsdp`。0.18 的检查点默认格式是 `torch_dist`,Megatron FSDP 必须显式使用 `fsdp_dtensor`;修改格式参数不会自动转换已有检查点。 | ||
| 32 | + | ||
| 33 | +2. 在加载环境脚本后取消 `CUDA_DEVICE_MAX_CONNECTIONS` 设置: | ||
| 34 | + | ||
| 35 | + ```bash | ||
| 36 | + unset CUDA_DEVICE_MAX_CONNECTIONS | ||
| 37 | + ``` | ||
| 38 | + | ||
| 39 | +3. 使用已有 MoE 用例中的 `--moe-grouped-gemm` 时,需要同时指定: | ||
| 40 | + | ||
| 41 | + ```bash | ||
| 42 | + --transformer-impl transformer_engine | ||
| 43 | + ``` | ||
| 44 | + | ||
| 45 | +4. 安装包含 DTensor FusedAdam 修复的 TransformerEngineNPU 版本,例如包含提交 [5c85c0d](https://gitcode.com/GuoHaifeng1999/TransformerEngineNPU/commit/5c85c0df3e9c1887a4aa5a000f96b2f01d9fb031) 的版本,并确认训练环境实际导入该安装包。旧版 TENPU 会拒绝 FSDP 提供的 DTensor 参数;仅调整检查点格式不能解决优化器类型错误。 | ||
| 46 | + | ||
| 47 | +## 支持范围与验证状态 | ||
| 48 | + | ||
| 49 | +| 项目 | 当前适配情况 | | ||
| 50 | +|------|--------------| | ||
| 51 | +| 基础 FSDP | 已接入 0.18 Megatron FSDP;已有脚本使用 `optim_grads_params` | | ||
| 52 | +| 参数与梯度 | 配套 TENPU 支持非量化 FP32/FP16/BF16 DTensor 参数,以及普通梯度、独立梯度和空分片处理 | | ||
| 53 | +| 优化器状态 | 配套 TENPU 支持浮点 moments,以及既有条件下的 FP32/FP16 master weights | | ||
| 54 | +| 通信生命周期 | 保留上游通信 dtype、双缓冲和异步释放;需在目标 NPU 环境验收 | | ||
| 55 | +| HSDP/HFSDP 与 AVG | 保留上游分支并适配独立 RS 输出,尚未完成多卡组合验证 | | ||
| 56 | +| 量化与 remainder | 当前 TENPU DTensor 路径不支持量化模型参数、FP8/uint8 moments 或 INT16 parameter remainder | | ||
| 57 | +| 检查点 | 接入已有 `fsdp_dtensor` 保存加载路径;真实多卡保存恢复及改变 DP 大小的恢复仍待验证 | | ||
| 58 | +| 特性组合 | 不保证与仓内其他特性任意组合;已有 MoE 脚本的训练精度和性能也需在 Ascend 多卡环境验证 | | ||
| 59 | + | ||
| 60 | +上述“已接入”表示源码完成基础适配,不表示所有组合已通过 NPU 端到端测试。TENPU 的 CPU 本地分片验证不能替代 HCCL 训练和真实检查点恢复验收。 | ||
| 61 | + | ||
| 62 | +## 使用效果 | ||
| 63 | + | ||
| 64 | +权重、梯度和优化器状态进一步分片后,可降低常驻训练状态的显存占用。按需收集参数会增加通信,独立 reduce-scatter 输出和通信 dtype 转换也会使用临时缓冲区;实际显存峰值与迭代耗时应在目标模型和并行配置下测量。 | ||
| 65 | + | ||
| 66 | +> [!NOTE] | ||
| 67 | +> | ||
| 68 | +> 复用 master 的已有 [custom_fsdp.sh 脚本](../../../tests_extend/system_tests/feature_tests/custom_fsdp.sh),未新增测试用例。运行前需修改数据和 tokenizer 路径。 | ||
| 69 | +> | ||
| 70 | +> 默认脚本在第 50 步退出,而保存间隔为 2000 步,且包含 `--no-load-optim` 和 `--no-load-rng`,不能用一次默认运行证明完整断点恢复。验证恢复时,应在同一已有用例中配置 save/load 目录和合适的保存间隔,并移除这两个不加载选项,比较恢复后的下一步参数、优化器状态和 loss。 | ||
| @@ -0,0 +1,122 @@ | |||
| 1 | +# VPP 前向 P2P 发送等待延后 | ||
| 2 | + | ||
| 3 | +## 功能与原理 | ||
| 4 | + | ||
| 5 | +Megatron Core 0.18 的交错流水线调度在开启输出伪释放时,会在释放前等待当前 | ||
| 6 | +前向发送完成。这一步可能提前建立通信到计算的依赖,压缩 P2P 发送与后续计算 | ||
| 7 | +的重叠窗口。 | ||
| 8 | + | ||
| 9 | +MindSpeed 的 `defer-p2p-send-wait` 将当前发送的等待延后到下一次受管理的 | ||
| 10 | +前向发送提交之后;最后一笔发送在本次调度退出时收尾。接收等待仍由原调度 | ||
| 11 | +负责,计算顺序、通信内容和通信次数保持不变。 | ||
| 12 | + | ||
| 13 | +该优化面向 NPU 上的原生 VPP 交错调度,主要目标是改善通信与计算重叠, | ||
| 14 | +不承诺降低峰值显存,也不属于 MoE fast ops 开关控制的显存优化。 | ||
| 15 | + | ||
| 16 | +## 使用方式 | ||
| 17 | + | ||
| 18 | +`--defer-p2p-send-wait` 默认开启,属于 optimization level 2 特性。 | ||
| 19 | +实际生效需要 `optimization_level >= 2`,并满足下文全部适用条件。 | ||
| 20 | +显式添加该参数不会绕过兼容性校验;使用 `--no-defer-p2p-send-wait` 关闭。 | ||
| 21 | + | ||
| 22 | +以下是添加到已有合法训练命令中的 PP/VPP 配置示例,其余模型、并行和训练 | ||
| 23 | +参数仍需按实际任务设置: | ||
| 24 | + | ||
| 25 | +```bash | ||
| 26 | +--optimization-level 2 \ | ||
| 27 | +--num-layers 16 \ | ||
| 28 | +--pipeline-model-parallel-size 2 \ | ||
| 29 | +--num-layers-per-virtual-pipeline-stage 4 | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +此例每个 PP rank 有两个虚拟流水线阶段。不要同时设置另一种 VPP/layout | ||
| 33 | +指定方式,也不要添加 `--no-overlap-p2p-communication`。最终配置还需满足 | ||
| 34 | +`batch_p2p_comm=False`、`deallocate_pipeline_outputs=True`。 | ||
| 35 | + | ||
| 36 | +进行开关对比时,保持原配置,关闭组只增加: | ||
| 37 | + | ||
| 38 | +```bash | ||
| 39 | +--no-defer-p2p-send-wait | ||
| 40 | +``` | ||
| 41 | + | ||
| 42 | +## 适用条件与自动回退 | ||
| 43 | + | ||
| 44 | +完整参数校验后,只有以下条件全部满足才保留开启状态: | ||
| 45 | + | ||
| 46 | +| 条件 | 要求 | | ||
| 47 | +| --- | --- | | ||
| 48 | +| 流水线并行 | `pipeline_model_parallel_size > 1` | | ||
| 49 | +| 虚拟流水线 | 推导出的 `virtual_pipeline_model_parallel_size > 0` | | ||
| 50 | +| P2P 通信重叠 | `overlap_p2p_comm=True` | | ||
| 51 | +| 批量 P2P | `batch_p2p_comm=False` | | ||
| 52 | +| 输出伪释放 | `deallocate_pipeline_outputs=True` | | ||
| 53 | +| 调度选择 | `schedules_method=None`,使用原生交错调度 | | ||
| 54 | +| 不兼容特性 | 下列开关均未启用 | | ||
| 55 | + | ||
| 56 | +不兼容开关为: | ||
| 57 | + | ||
| 58 | +- `moe_fb_overlap` | ||
| 59 | +- `use_multiparameter_pipeline_model_parallel` | ||
| 60 | +- `recompute_in_bubble`、`recompute_in_advance` | ||
| 61 | +- `tp_2d` | ||
| 62 | +- `variable_seq_lengths` | ||
| 63 | +- `optimize_send_recv_comm` | ||
| 64 | +- `dist_train` | ||
| 65 | + | ||
| 66 | +条件不满足时,校验将 `args.defer_p2p_send_wait` 自动设置为 `False`, | ||
| 67 | +继续走原有调度。PP/VPP 数值允许使用可转换的数字字符串,无法转换时也关闭。 | ||
| 68 | +例如,PP2 但未开启 VPP 的配置不会应用此优化。 | ||
| 69 | + | ||
| 70 | +补丁安装早于完整参数校验。注册时只判断用户开关,避免把尚未推导的 VPP | ||
| 71 | +或早期字符串参数误判为不兼容。每次调度入口读取一次最终开关;关闭后直接 | ||
| 72 | +调用原调度,不接管发送。 | ||
| 73 | + | ||
| 74 | +运行中,未处于受管理的调度、未开启 P2P overlap、没有待发送输出、输出不是 | ||
| 75 | +单个 NPU Tensor,或通信配置使用 batch P2P / 关闭输出伪释放时,该次调用 | ||
| 76 | +直接走原通信接口。 | ||
| 77 | + | ||
| 78 | +自动回退仅处理这些预先可判断的适用条件,不会吞掉原训练配置的错误,也不会 | ||
| 79 | +在发送已经提交后捕获异常并重新执行通信。 | ||
| 80 | + | ||
| 81 | +## 发送存储的生命周期 | ||
| 82 | + | ||
| 83 | +Megatron 的输出伪释放会替换输出张量的 `.data`。仅保存同一个 Tensor 的 | ||
| 84 | +Python 引用不能保护原发送存储,因此实现按以下顺序管理异步发送: | ||
| 85 | + | ||
| 86 | +1. 提交前,通过 `detach()` 创建独立的 Tensor 元数据并持有原 storage; | ||
| 87 | + 不复制发送载荷,也不额外持有其 autograd 图。 | ||
| 88 | +2. 调用原 `send_forward_recv_forward`,接管返回的 `send_next` Work。 | ||
| 89 | + 只从交还调度器的 handles 中移除这一项,保留全部接收等待。 | ||
| 90 | +3. 当前发送提交后,对前一笔受管理发送执行 `wait()`,再释放对应持有者。 | ||
| 91 | + 正常稳定运行时保留最新一笔发送;提交新发送到前一笔收尾之间会短暂持有两笔。 | ||
| 92 | +4. `Work.wait()` 可能只向当前 NPU stream 加入事件依赖,因此在丢弃持有者前 | ||
| 93 | + 对发送张量调用 `record_stream()`,保护存储直到相关流上的工作完成。 | ||
| 94 | +5. 调度正常退出、forward-only 返回或发生异常时,通过 `finally` 收尾剩余发送, | ||
| 95 | + 并恢复调度上下文。 | ||
| 96 | + | ||
| 97 | +正常路径不新增载荷拷贝、通信调用或全设备同步。若提交过程抛出异常,未能返回 | ||
| 98 | +Work,则清理路径使用设备同步确认存储安全;若等待或清理失败,错误继续传播, | ||
| 99 | +相关存储保留到进程退出。原接口没有返回预期的 `send_next` Work 时也明确报错。 | ||
| 100 | + | ||
| 101 | +## 验证与性能观察 | ||
| 102 | + | ||
| 103 | +对比时固定模型、PP/VPP 布局、microbatch 数量、精度、重计算配置和随机种子, | ||
| 104 | +分别运行默认开启组与显式关闭组: | ||
| 105 | + | ||
| 106 | +- 检查最终参数中 `defer_p2p_send_wait` 的值,确认优化实际生效。 | ||
| 107 | +- 对比 loss、梯度或参数更新,确认训练结果符合所用精度的容差。 | ||
| 108 | +- 预热后比较稳态 step time 和吞吐;在时间线中观察前向发送与后续计算的重叠。 | ||
| 109 | +- 同时记录 peak allocated / reserved。延长发送存储的存活时间可能提高局部 | ||
| 110 | + 显存占用,不能仅凭等待被延后推断显存下降或吞吐一定提升。 | ||
| 111 | + | ||
| 112 | +收益取决于流水线布局、通信时长和可重叠的计算量,需要实际多卡 NPU 验证。 | ||
| 113 | + | ||
| 114 | +## 实现位置 | ||
| 115 | + | ||
| 116 | +- 参数与兼容性校验: | ||
| 117 | + [`defer_p2p_send_wait.py`](../../../mindspeed/features_manager/pipeline_parallel/defer_p2p_send_wait.py) | ||
| 118 | +- 调度包装与发送存储管理: | ||
| 119 | + [`defer_p2p_send_wait.py`](../../../mindspeed/core/pipeline_parallel/defer_p2p_send_wait.py) | ||
| 120 | + | ||
| 121 | +实现由 MindSpeed 安装在 Megatron 的调度和 P2P 接口上,不需要在 TENPU 重复 | ||
| 122 | +安装补丁。 | ||
| @@ -3,11 +3,11 @@ | |||
| 3 | ## 背景与挑战 | 3 | ## 背景与挑战 |
| 4 | 4 | ||
| 5 | 在传统的权重保存加载过程中,即训练脚本中指定了`--ckpt-format torch`参数的场景中,每张卡上都会持有完整的优化器状态,在保存阶段,每张卡上都会将完整的优化器状态保存到磁盘中,存在数据冗余。 | 5 | 在传统的权重保存加载过程中,即训练脚本中指定了`--ckpt-format torch`参数的场景中,每张卡上都会持有完整的优化器状态,在保存阶段,每张卡上都会将完整的优化器状态保存到磁盘中,存在数据冗余。 |
| 6 | -为了消减优化器状态的数据冗余,尽管可以通过开启分布式优化器,使得每张卡上仅持有分片后的优化器状态,来减小运行时的内存开销和保存的权重文件的磁盘空间占用,但是这种策略会在保存阶段和加载阶段分别引入All-Gather操作和Scatter操作,从而增加通信开销。 | 6 | +为了削减优化器状态的数据冗余,尽管可以通过开启分布式优化器,使得每张卡上仅持有分片后的优化器状态,来减小运行时的内存开销和保存的权重文件的磁盘空间占用,但是这种策略会在保存阶段和加载阶段分别引入All-Gather操作和Scatter操作,从而增加通信开销。 |
| 7 | 7 | ||
| 8 | ## 解决思路 | 8 | ## 解决思路 |
| 9 | 9 | ||
| 10 | -为解决上述问题,引入完全分片策略,将模型参数和优化器状态进行完全分片,在权重保存和加载过程中,每张卡仅保存和加载各自的分片数据,消减数据冗余。和分布式优化器相比,省去了保存阶段All-Gather操作和加载阶段的Scatter操作。 | 10 | +为解决上述问题,引入完全分片策略,将模型参数和优化器状态进行完全分片,在权重保存和加载过程中,每张卡仅保存和加载各自的分片数据,削减数据冗余。和分布式优化器相比,省去了保存阶段All-Gather操作和加载阶段的Scatter操作。 |
| 11 | 11 | ||
| 12 | ## 使用场景 | 12 | ## 使用场景 |
| 13 | 13 | ||
| @@ -1,40 +0,0 @@ | |||
| 1 | -# Double Ring Attention长序列并行 | ||
| 2 | - | ||
| 3 | -## 背景与挑战 | ||
| 4 | - | ||
| 5 | -在训练长序列的大语言模型时需要大量的内存资源和计算资源。业界已经提出了基于头并行和基于上下文并行的序列并行方法。在Attention块中,头并行方法保留整个序列,并行计算不同头的注意力,而上下文并行方法将QKV张量沿序列维度分成块。然而,当应用于大规模极长序列的大语言模型时,这两种方法都面临限制。首先,头并行遇到可扩展性问题。在头并行中,序列并行的程度本质上不能超过注意力头的数量。因此,头并行能够扩展的程度存在一个上限。其次,上下文并行遇到了通信效率问题。上下文并行采用了点对点(P2P)通信原语。然而,P2P遇到了低节点内带宽利用率和低节点间网络资源利用率的问题。这一瓶颈使得在扩展上下文并行维度时难以将通信与计算重叠。 | ||
| 6 | - | ||
| 7 | -## 解决方案 | ||
| 8 | - | ||
| 9 | -支持Double Ring Attention算法,进一步加速原始Ring Attention实现。算法细节参见原文: | ||
| 10 | -> LoongTrain: Efficient Training of Long-Sequence LLMs with Head-Context Parallelism (<https://arxiv.org/pdf/2406.18485>) | ||
| 11 | - | ||
| 12 | -### 解决思路 | ||
| 13 | - | ||
| 14 | -原有的Ring Attention借鉴了分块Softmax原理,在不需要获取整个序列的完整矩阵情况下进行分块attention计算。 以分块方式执行自注意力和前馈网络计算,跨多个设备分布序列维度。具体地,该方法在进程之间构建注意力计算块的环状通信结构(Ring),每个进程具有一个切分后的本地QKV块。在计算完本地的attention后,通过向后发送和向前获取KV块,遍历进程设备环,以逐块的方式进行注意力和前馈网络计算。同时,本地的attention计算和KV块的通信理想情况下可以互相掩盖,从而消除了额外引入的通信开销。另外该方案在计算attention的过程中全程不需要数据拼接,支持的序列长度理论上可以无限拓展。 在此基础上Double Ring Attention算法采用分布式注意力机制,通过双环结构(Double Ring Attention)来优化计算和内存使用。 | ||
| 15 | - | ||
| 16 | -## 使用场景 | ||
| 17 | - | ||
| 18 | -**后端限制:** CP>1 必须设置 `--transformer-impl transformer_engine`。 | ||
| 19 | - | ||
| 20 | -已开启Ring Attention的训练场景 | ||
| 21 | - | ||
| 22 | -Ring Attention使能方式参考[此处](ring-attention-context-parallel.md) | ||
| 23 | - | ||
| 24 | -## 使用方法 | ||
| 25 | - | ||
| 26 | -在设置 `--transformer-impl transformer_engine --cp-comm-type p2p` 的 [Ring Attention](ring-attention-context-parallel.md) 训练场景中,将`--cp-window-size`设置为大于1的整数,即可使能Double Ring Attention算法,优化原始Ring Attention性能。 | ||
| 27 | - | ||
| 28 | -| 重要参数 | 参数说明 | | ||
| 29 | -|------------------------|---------------------------------------------------------------------------------------------------------------------------------------------| | ||
| 30 | -| --cp-window-size [int] | 默认为`1`,即使用原始的Ring Attention算法,将`--cp-window-size`设置为大于1的整数,即可使能Double Ring Attention算法,该参数为Double Ring Attention算法中双层Ring Attention的内层窗口大小; | | ||
| 31 | - | ||
| 32 | -## 使用效果 | ||
| 33 | - | ||
| 34 | -利用多个计算设备对输入序列进行并行切分,通过双环结构(Double Ring Attention)提升计算效率。 | ||
| 35 | - | ||
| 36 | -## 注意事项 | ||
| 37 | - | ||
| 38 | -1. Ring 度数必须能被 `--cp-window-size` 整除;纯 Ring 的度数为 CP,混合 CP 的度数为 `--hierarchical-context-parallel-sizes A R` 中的 R。 | ||
| 39 | -2. `--cp-window-size` 必须小于 Ring 度数。`--use-cp-send-recv-overlap`、`--use-fused-ring-attention-update` 仅支持 `p2p` / `a2a+p2p`。 | ||
| 40 | -3. 内层窗口`--cp-window-size`增大时,通信与计算并发程度更高,但是计算、通信并发时可能由于片上内存带宽抢占,整体效率下降,需要结合实际场景进行调试,例如Llama2裁剪模型32k序列长度,cp为16且无其他并行切分时,实测内层窗口大小为2时性能最优。 | ||
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | ## 背景与挑战 | 3 | ## 背景与挑战 |
| 4 | 4 | ||
| 5 | -MoE类模型一直以来存在All2All通信耗时占比高和显存开销大等关键问题。为了更好地进行All2All通信掩盖,DeepSeek提出了DualPipe流水排布和MoE跨microbatch前反向通信掩盖[1](https://github.com/deepseek-ai/DualPipe)。 | 5 | +MoE类模型一直以来存在All2All通信耗时占比高和显存开销大等关键问题。为了更好的进行All2All通信掩盖,DeepSeek提出了DualPipe流水排布和MoE跨microbatch前反向通信掩盖[1](https://github.com/deepseek-ai/DualPipe)。 |
| 6 | 6 | ||
| 7 | DualPipe流水不仅可以创造跨microbatch计算通信并行的条件,实现稳定阶段的All2All全掩盖,在空泡比率和warmup阶段激活显存上相比传统方案也有更好地综合表现。在warmup和cooldown阶段,DualPipe都采取了Zero Bubble思想中的dw分离来进一步压缩气泡。同时,该流水排布天然亲和MTP模型结构,由于首尾stage都在同一张卡上,该流水也可以更方便地调整PP间的负载均衡策略。缺点是每张卡上需要的参数量翻倍。 | 7 | DualPipe流水不仅可以创造跨microbatch计算通信并行的条件,实现稳定阶段的All2All全掩盖,在空泡比率和warmup阶段激活显存上相比传统方案也有更好地综合表现。在warmup和cooldown阶段,DualPipe都采取了Zero Bubble思想中的dw分离来进一步压缩气泡。同时,该流水排布天然亲和MTP模型结构,由于首尾stage都在同一张卡上,该流水也可以更方便地调整PP间的负载均衡策略。缺点是每张卡上需要的参数量翻倍。 |
| 8 | 8 | ||
| @@ -36,7 +36,7 @@ CP>1 时需保证各层的 CP 通信类型一致。 | |||
| 36 | | `--reset-position-ids` | 可开可关;开启后各文档的位置编码重新计数,关闭后保持连续。 | | 36 | | `--reset-position-ids` | 可开可关;开启后各文档的位置编码重新计数,关闭后保持连续。 | |
| 37 | | `--eod-mask-loss` | 可选,屏蔽 EOD token 对应位置的 loss;DSA 不支持该选项。 | | 37 | | `--eod-mask-loss` | 可选,屏蔽 EOD token 对应位置的 loss;DSA 不支持该选项。 | |
| 38 | | `--fix-sub-seq-length N` | 默认 -1,按 EOD 边界划分;0<N≤seq-length 时改用固定子序列长度,最后一段保留余长;其他取值仍按 EOD 边界划分。 | | 38 | | `--fix-sub-seq-length N` | 默认 -1,按 EOD 边界划分;0<N≤seq-length 时改用固定子序列长度,最后一段保留余长;其他取值仍按 EOD 边界划分。 | |
| 39 | -| `--variable-seq-lengths` | CP>1 时必需;CP=1 不因 EOD Reset 强制要求开启。 | | 39 | +| `--variable-seq-lengths` | CP>1 时必须设置;CP=1 不因 EOD Reset 强制要求开启。 | |
| 40 | 40 | ||
| 41 | ### 3. 注意事项 | 41 | ### 3. 注意事项 |
| 42 | 42 | ||
| @@ -41,7 +41,7 @@ | |||
| 41 | <td><a href="../features/recomputation.md">Megatron重计算</a></td> | 41 | <td><a href="../features/recomputation.md">Megatron重计算</a></td> |
| 42 | </tr> | 42 | </tr> |
| 43 | <tr> | 43 | <tr> |
| 44 | - <td><a href="../features/dist_ckpt.md">Megatron分布式权重</a></td> | 44 | + <td><a href="../features/custom_fsdp.md">Megatron全分片数据并行</a></td> |
| 45 | </tr> | 45 | </tr> |
| 46 | <tr> | 46 | <tr> |
| 47 | <td><a href="../features/transformer_engine.md">Megatron Transformer Engine</a></td> | 47 | <td><a href="../features/transformer_engine.md">Megatron Transformer Engine</a></td> |
| @@ -50,18 +50,12 @@ | |||
| 50 | <td><a href="../features/multi-head-latent-attention.md">Megatron Multi-head Latent Attention</a></td> | 50 | <td><a href="../features/multi-head-latent-attention.md">Megatron Multi-head Latent Attention</a></td> |
| 51 | </tr> | 51 | </tr> |
| 52 | <tr> | 52 | <tr> |
| 53 | - <td rowspan="8">并行策略特性</td> | 53 | + <td rowspan="6">并行策略特性</td> |
| 54 | <td><a href="../features/ulysses-context-parallel.md">Ascend Ulysses长序列并行</a></td> | 54 | <td><a href="../features/ulysses-context-parallel.md">Ascend Ulysses长序列并行</a></td> |
| 55 | </tr> | 55 | </tr> |
| 56 | <tr> | 56 | <tr> |
| 57 | <td><a href="../features/ring-attention-context-parallel.md">Ascend Ring Attention长序列并行</a></td> | 57 | <td><a href="../features/ring-attention-context-parallel.md">Ascend Ring Attention长序列并行</a></td> |
| 58 | </tr> | 58 | </tr> |
| 59 | - <tr> | ||
| 60 | - <td><a href="../features/double-ring.md">Ascend Double Ring Attention长序列并行</a></td> | ||
| 61 | - </tr> | ||
| 62 | - <tr> | ||
| 63 | - <td><a href="../features/hybrid-context-parallel.md">Ascend混合长序列并行</a></td> | ||
| 64 | - </tr> | ||
| 65 | <tr> | 59 | <tr> |
| 66 | <td><a href="../features/noop-layers.md">Ascend自定义空操作层</a></td> | 60 | <td><a href="../features/noop-layers.md">Ascend自定义空操作层</a></td> |
| 67 | </tr> | 61 | </tr> |
| @@ -75,12 +69,9 @@ | |||
| 75 | <td><a href="../features/pipeline-model-parallel-layout.md">Megatron 自定义流水线布局</a></td> | 69 | <td><a href="../features/pipeline-model-parallel-layout.md">Megatron 自定义流水线布局</a></td> |
| 76 | </tr> | 70 | </tr> |
| 77 | <tr> | 71 | <tr> |
| 78 | - <td rowspan="12">内存优化特性</td> | 72 | + <td rowspan="10">内存优化特性</td> |
| 79 | <td><a href="../features/activation-function-recompute.md">Ascend激活函数重计算</a></td> | 73 | <td><a href="../features/activation-function-recompute.md">Ascend激活函数重计算</a></td> |
| 80 | </tr> | 74 | </tr> |
| 81 | - <tr> | ||
| 82 | - <td><a href="../features/recompute_independent_pipelining.md">Ascend重计算流水线独立调度</a></td> | ||
| 83 | - </tr> | ||
| 84 | <tr> | 75 | <tr> |
| 85 | <td><a href="../features/generate-mask.md">Ascend Mask归一</a></td> | 76 | <td><a href="../features/generate-mask.md">Ascend Mask归一</a></td> |
| 86 | </tr> | 77 | </tr> |
| @@ -108,9 +99,6 @@ | |||
| 108 | <tr> | 99 | <tr> |
| 109 | <td><a href="../features/swap-layer-input.md">Transformer 层输入卸载</a></td> | 100 | <td><a href="../features/swap-layer-input.md">Transformer 层输入卸载</a></td> |
| 110 | </tr> | 101 | </tr> |
| 111 | - <tr> | ||
| 112 | - <td><a href="../features/compress-tensor.md">compress-activation</a></td> | ||
| 113 | - </tr> | ||
| 114 | <tr> | 102 | <tr> |
| 115 | <td rowspan="10">亲和计算特性</td> | 103 | <td rowspan="10">亲和计算特性</td> |
| 116 | <td><a href="../features/rms_norm.md">Ascend rms_norm 融合算子</a></td> | 104 | <td><a href="../features/rms_norm.md">Ascend rms_norm 融合算子</a></td> |
| @@ -140,15 +128,12 @@ | |||
| 140 | <td><a href="../features/hif8_dts.md">HiF8 DTS (Delayed Tensor Scaling) 训练</a></td> | 128 | <td><a href="../features/hif8_dts.md">HiF8 DTS (Delayed Tensor Scaling) 训练</a></td> |
| 141 | </tr> | 129 | </tr> |
| 142 | <tr> | 130 | <tr> |
| 143 | - <td><a href="../features/te-comparsion-online.md">低精度在线比对</a></td> | 131 | + <td><a href="../features/te-comparison-online.md">低精度在线比对</a></td> |
| 144 | </tr> | 132 | </tr> |
| 145 | <tr> | 133 | <tr> |
| 146 | - <td rowspan="3">通信优化特性</td> | 134 | + <td rowspan="2">通信优化特性</td> |
| 147 | <td><a href="../features/hccl-replace-gloo.md">Ascend Gloo存档落盘优化</a></td> | 135 | <td><a href="../features/hccl-replace-gloo.md">Ascend Gloo存档落盘优化</a></td> |
| 148 | </tr> | 136 | </tr> |
| 149 | - <tr> | ||
| 150 | - <td><a href="../features/tensor-parallel-2d.md">Ascend高维张量并行</a></td> | ||
| 151 | - </tr> | ||
| 152 | <tr> | 137 | <tr> |
| 153 | <td><a href="../features/async-log-allreduce.md">异步日志全归约 (Async Log Allreduce)</a></td> | 138 | <td><a href="../features/async-log-allreduce.md">异步日志全归约 (Async Log Allreduce)</a></td> |
| 154 | </tr> | 139 | </tr> |
| @@ -193,19 +178,6 @@ | |||
| 193 | <tr> | 178 | <tr> |
| 194 | <td><a href="../features/preprocess-eod-data.md">pack模式预训练数据集处理</a></td> | 179 | <td><a href="../features/preprocess-eod-data.md">pack模式预训练数据集处理</a></td> |
| 195 | </tr> | 180 | </tr> |
| 196 | - <tr> | ||
| 197 | - <td rowspan="4">多模态特性</td> | ||
| 198 | - <td><a href="../features/variable_seq_lengths.md">Ascend PP支持动态形状</a></td> | ||
| 199 | - </tr> | ||
| 200 | - <tr> | ||
| 201 | - <td><a href="../features/multi_parameter_pipeline.md">Ascend PP支持多参数传递</a></td> | ||
| 202 | - </tr> | ||
| 203 | - <tr> | ||
| 204 | - <td><a href="../features/multi_parameter_pipeline_and_variable_seq_lengths.md">Ascend PP支持多参数传递和动态形状</a></td> | ||
| 205 | - </tr> | ||
| 206 | - <tr> | ||
| 207 | - <td><a href="../features/unaligned_linear.md">Ascend非对齐线性层</a></td> | ||
| 208 | - </tr> | ||
| 209 | <tr> | 181 | <tr> |
| 210 | <td rowspan="7">其它特性</td> | 182 | <td rowspan="7">其它特性</td> |
| 211 | <td><a href="../features/ops_flops_cal.md">Ascend TFLOPS计算</a></td> | 183 | <td><a href="../features/ops_flops_cal.md">Ascend TFLOPS计算</a></td> |
| @@ -24,8 +24,8 @@ | |||
| 24 | ## 使用影响 | 24 | ## 使用影响 |
| 25 | 25 | ||
| 26 | 1.由于fused_ema_adamw优化器在训练时需要额外维护```ema_params```状态,内存开销会有所增加。<br> | 26 | 1.由于fused_ema_adamw优化器在训练时需要额外维护```ema_params```状态,内存开销会有所增加。<br> |
| 27 | -2.权重保存时,优化器的```ema_params```优化器状态将会存储在distrib_optim.pt文件中。<br> | 27 | +2.权重保存时,优化器的```ema_params```状态将会存储在distrib_optim.pt文件中。<br> |
| 28 | -3.权重保存时,ema模型权重数据将会存储在model_optim_rng.pt文件中的```ema_model```字段中。<br> | 28 | +3.权重保存时,ema模型权重数据将会存储在model_optim_rng.pt文件的```ema_model```字段中。<br> |
| 29 | 29 | ||
| 30 | ## 注意事项 | 30 | ## 注意事项 |
| 31 | 31 | ||
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | ## 使用场景 | 3 | ## 使用场景 |
| 4 | 4 | ||
| 5 | -本方法为FlashAttention的V2版本,对V1版本进行了一定功能拓展,当前仅支持特定场景如[Alibi位置编码](./alibi.md),默认关闭。 | 5 | +本方法为Flash Attention的V2版本,对V1版本进行了一定功能拓展,当前仅支持特定场景如[Alibi位置编码](./alibi.md),默认关闭。 |
| 6 | 6 | ||
| 7 | 其它场景原则上与V1版本无差异,不建议主动开启。算子说明详情见[接口说明](../ops/fusion_attention.md)。 | 7 | 其它场景原则上与V1版本无差异,不建议主动开启。算子说明详情见[接口说明](../ops/fusion_attention.md)。 |
| 8 | 8 | ||
| @@ -12,4 +12,4 @@ | |||
| 12 | 12 | ||
| 13 | ## 使用效果 | 13 | ## 使用效果 |
| 14 | 14 | ||
| 15 | -基础效果等同于FlashAttention,特定场景如[Alibi位置编码](./alibi.md)需手动开启。 | 15 | +基础效果等同于Flash Attention,特定场景如[Alibi位置编码](./alibi.md)需手动开启。 |
| @@ -1,10 +1,10 @@ | |||
| 1 | -# Gloo 存档落盘优化 | 1 | +# Gloo 存档落盘优化 |
| 2 | 2 | ||
| 3 | ## 背景与挑战 | 3 | ## 背景与挑战 |
| 4 | 4 | ||
| 5 | 在大规模集群下,Gloo 通信存在规模限制和稳定性问题。一方面,容易出现 Gloo 通信组创建失败的情况;另一方面,与 HCCL 通信相比,Gloo 通信较慢。 | 5 | 在大规模集群下,Gloo 通信存在规模限制和稳定性问题。一方面,容易出现 Gloo 通信组创建失败的情况;另一方面,与 HCCL 通信相比,Gloo 通信较慢。 |
| 6 | 6 | ||
| 7 | -对于Gloo通信组创建失败报错`Gloo connectFullMesh failed with ...`的问题,本质上是由于N张卡链接到主Master来完成建链,集群规模大时,Master处理能力不足,可能造成建链失败。可通过调整和网络建链相关参数进行规避(云上8k卡场景验证有效): | 7 | +对于Gloo通信组创建失败报错`Gloo connectFullMesh failed with ...`的问题,本质上是由于N张卡连接到主Master来完成建链,集群规模大时,Master处理能力不足,可能造成建链失败。可通过调整和网络建链相关参数进行规避(云上8k卡场景验证有效): |
| 8 | 8 | ||
| 9 | ```bash | 9 | ```bash |
| 10 | net.ipv4.tcp_max_syn_backlog = 65536 | 10 | net.ipv4.tcp_max_syn_backlog = 65536 |
| @@ -33,11 +33,11 @@ MindSpeed 为 HiF8 DTS 训练提供了 **Step Recovery** 特性,在框架层 | |||
| 33 | 33 | ||
| 34 | 每次 `all_reduce` 的 payload 仅为 2 个 int32(8 字节),开销可忽略。这两个同步点确保任意 rank 发现异常时,所有 rank 都能在 optimizer commit 前一致地停止并重试。 | 34 | 每次 `all_reduce` 的 payload 仅为 2 个 int32(8 字节),开销可忽略。这两个同步点确保任意 rank 发现异常时,所有 rank 都能在 optimizer commit 前一致地停止并重试。 |
| 35 | 35 | ||
| 36 | -在非 `hif8_delayed` recipe 场景下,wrapper 直接短路到原始 `train_step`,无任何额外开销。 | 36 | +在非 HiF8 DTS 策略(`--fp8-format hif8` 且 `--fp8-recipe delayed`)场景下,wrapper 直接短路到原始 `train_step`,无任何额外开销。 |
| 37 | 37 | ||
| 38 | ## 使用场景 | 38 | ## 使用场景 |
| 39 | 39 | ||
| 40 | -- 使用 `--fp8-format hif8 --fp8-recipe hif8_delayed` 进行 HiF8 DTS 低精度训练时,Step Recovery 默认启用。 | 40 | +- 使用 `--fp8-format hif8 --fp8-recipe delayed` 进行 HiF8 DTS 低精度训练时,Step Recovery 默认启用。 |
| 41 | - 训练过程中偶发的 NaN/Inf(如异常数据、梯度爆炸)需要自动恢复而不中断训练的场景。 | 41 | - 训练过程中偶发的 NaN/Inf(如异常数据、梯度爆炸)需要自动恢复而不中断训练的场景。 |
| 42 | - 对训练数据流连续性有要求、不希望跳过批次的场景。 | 42 | - 对训练数据流连续性有要求、不希望跳过批次的场景。 |
| 43 | 43 | ||
| @@ -50,7 +50,7 @@ HiF8 DTS 训练通过以下参数组合启用,Step Recovery 随之自动激活 | |||
| 50 | ```bash | 50 | ```bash |
| 51 | --transformer-impl transformer_engine | 51 | --transformer-impl transformer_engine |
| 52 | --fp8-format hif8 | 52 | --fp8-format hif8 |
| 53 | ---fp8-recipe hif8_delayed | 53 | +--fp8-recipe delayed |
| 54 | ``` | 54 | ``` |
| 55 | 55 | ||
| 56 | ### 显式禁用 Step Recovery | 56 | ### 显式禁用 Step Recovery |
| @@ -80,12 +80,12 @@ HiF8 DTS recipe 提供以下可调参数,用于控制 amax 收集与 scale fac | |||
| 80 | - **训练连续性**:Step Recovery 在检测到 NaN/Inf 后重试同一批次而非跳过,保证训练数据流连续,避免收敛偏移。 | 80 | - **训练连续性**:Step Recovery 在检测到 NaN/Inf 后重试同一批次而非跳过,保证训练数据流连续,避免收敛偏移。 |
| 81 | - **数值稳定性**:通过重置 HiF8 amax 历史,消除被污染的 scale factor 对后续 step 的影响,避免级联失败。 | 81 | - **数值稳定性**:通过重置 HiF8 amax 历史,消除被污染的 scale factor 对后续 step 的影响,避免级联失败。 |
| 82 | - **确定性**:通过恢复完整的 RNG 状态,使重试 attempt 尽可能复现原始 attempt 的随机行为(dropout、mask、routing 等)。 | 82 | - **确定性**:通过恢复完整的 RNG 状态,使重试 attempt 尽可能复现原始 attempt 的随机行为(dropout、mask、routing 等)。 |
| 83 | -- **开销**:仅在检测到 NaN/Inf 时产生额外开销(清理、重置、RNG 恢复、批次重放、一次额外前向反向)。正常 step 的额外开销仅为两次 2 x int32 的 `all_reduce(MAX)`,开销可忽略。wrapper 在非 `hif8_delayed` 场景下直接短路。 | 83 | +- **开销**:仅在检测到 NaN/Inf 时产生额外开销(清理、重置、RNG 恢复、批次重放、一次额外前向反向)。正常 step 的额外开销仅为两次 2 x int32 的 `all_reduce(MAX)`,开销可忽略。wrapper 在非 HiF8 策略场景下直接短路。 |
| 84 | - **重试限制**:每个 step 最多重试一次。若重试仍失败,训练将中止并输出结构化诊断日志(包含 iteration、reason、rank、loss、grad_norm)。 | 84 | - **重试限制**:每个 step 最多重试一次。若重试仍失败,训练将中止并输出结构化诊断日志(包含 iteration、reason、rank、loss、grad_norm)。 |
| 85 | 85 | ||
| 86 | ## 参数组合限制 | 86 | ## 参数组合限制 |
| 87 | 87 | ||
| 88 | -`hif8_delayed` recipe 仅允许与 `--fp8-format hif8` 组合使用。其他 fp8-format(如 `e4m3`)与 `hif8_delayed` 组合会在参数校验阶段报错。 | 88 | +`--fp8-recipe delayed` 仅允许与 `--fp8-format hif8` 组合使用。其他 fp8-format(如 `e4m3`)与 HiF8 策略组合会在参数校验阶段报错。 |
| 89 | 89 | ||
| 90 | <table><thead> | 90 | <table><thead> |
| 91 | <tr> | 91 | <tr> |
| @@ -98,7 +98,7 @@ HiF8 DTS recipe 提供以下可调参数,用于控制 amax 收集与 scale fac | |||
| 98 | <td rowspan="3">HiF8 DTS 训练</td> | 98 | <td rowspan="3">HiF8 DTS 训练</td> |
| 99 | <td rowspan="3">--transformer-impl transformer_engine | 99 | <td rowspan="3">--transformer-impl transformer_engine |
| 100 | <br> --fp8-format hif8 | 100 | <br> --fp8-format hif8 |
| 101 | - <br> --fp8-recipe hif8_delayed </td> | 101 | + <br> --fp8-recipe delayed </td> |
| 102 | <td style="text-align: center; vertical-align: middle">✅</td> | 102 | <td style="text-align: center; vertical-align: middle">✅</td> |
| 103 | </tr> | 103 | </tr> |
| 104 | </tbody> | 104 | </tbody> |
| @@ -107,7 +107,7 @@ HiF8 DTS recipe 提供以下可调参数,用于控制 amax 收集与 scale fac | |||
| 107 | <td rowspan="3">HiF8 DTS + Step Recovery</td> | 107 | <td rowspan="3">HiF8 DTS + Step Recovery</td> |
| 108 | <td rowspan="3">--transformer-impl transformer_engine | 108 | <td rowspan="3">--transformer-impl transformer_engine |
| 109 | <br> --fp8-format hif8 | 109 | <br> --fp8-format hif8 |
| 110 | - <br> --fp8-recipe hif8_delayed | 110 | + <br> --fp8-recipe delayed |
| 111 | <br>(默认启用,无需额外参数)</td> | 111 | <br>(默认启用,无需额外参数)</td> |
| 112 | <td style="text-align: center; vertical-align: middle">✅</td> | 112 | <td style="text-align: center; vertical-align: middle">✅</td> |
| 113 | </tr> | 113 | </tr> |
| @@ -117,7 +117,7 @@ HiF8 DTS recipe 提供以下可调参数,用于控制 amax 收集与 scale fac | |||
| 117 | <td rowspan="3">HiF8 DTS + 显式禁用 Step Recovery</td> | 117 | <td rowspan="3">HiF8 DTS + 显式禁用 Step Recovery</td> |
| 118 | <td rowspan="3">--transformer-impl transformer_engine | 118 | <td rowspan="3">--transformer-impl transformer_engine |
| 119 | <br> --fp8-format hif8 | 119 | <br> --fp8-format hif8 |
| 120 | - <br> --fp8-recipe hif8_delayed | 120 | + <br> --fp8-recipe delayed |
| 121 | <br> --no-hif8-step-recovery </td> | 121 | <br> --no-hif8-step-recovery </td> |
| 122 | <td style="text-align: center; vertical-align: middle">✅</td> | 122 | <td style="text-align: center; vertical-align: middle">✅</td> |
| 123 | </tr> | 123 | </tr> |
| @@ -1,55 +0,0 @@ | |||
| 1 | -# 混合长序列并行 | ||
| 2 | - | ||
| 3 | -## 背景与挑战 | ||
| 4 | - | ||
| 5 | -从生成性AI到科研模型,长序列训练正在变得非常重要。 在生成性AI领域,会话式AI、长文档摘要和视频生成等任务都需要在空间和时间层面对长上下文进行推理。 同样,章节和书籍级别的摘要(数万甚至数十万字)在会话式AI和摘要任务中也受到重视。现有的数据、张量和流水线等并行方法无法在序列维度进行切分。当序列维度(S)增长时,训练内存开销会以 $O$($S^2$) 的速度增长。因此需要针对长序列场景进行特定的优化解决长训练场景的训练需求。 | ||
| 6 | - | ||
| 7 | -目前流行的序列并行方案,Ulysses和Ring Attention存在各自的局限性。 | ||
| 8 | - | ||
| 9 | -Ulysses需要确保attention head数可以被序列并行维度整除,在GQA、MQA场景下序列并行的大小有限制,导致序列长度的扩展有限。 | ||
| 10 | - | ||
| 11 | -Ring Attention的并行维度不受attention head数限制,因此理论上序列长度可以无限拓展。但相比于Ulysses,Ring Attention不能充分利用通信和计算带宽,在序列块大小较低时性能劣于Ulysses。 | ||
| 12 | - | ||
| 13 | -## 解决方案 | ||
| 14 | - | ||
| 15 | -对Ulysses和Ring Attention做融合,实现混合序列并行,以此解决两个方案各自缺陷。 | ||
| 16 | -具体细节可参见文献[USP: A Unified Sequence Parallelism Approach for Long Context Generative AI](https://arxiv.org/abs/2405.07719)。 | ||
| 17 | - | ||
| 18 | -## 使用场景 | ||
| 19 | - | ||
| 20 | -**后端限制:** CP>1 必须设置 `--transformer-impl transformer_engine`。 | ||
| 21 | - | ||
| 22 | -可兼容FlashAttention,目前已默认开启FlashAttention。 | ||
| 23 | - | ||
| 24 | -序列并行维度被分为Ulysses维度和Ring Attention维度,Ulysses维度和Ring Attention维度乘积即为序列并行维度。 | ||
| 25 | - | ||
| 26 | -## 使用方法 | ||
| 27 | - | ||
| 28 | -| 训练类型 | 支持的 mask 类型 | | ||
| 29 | -| --- | --- | | ||
| 30 | -| 普通训练 | causal、general | | ||
| 31 | -| EOD Reset | 不支持 | | ||
| 32 | - | ||
| 33 | -使用 `--cp-comm-type` 选择通信方式。 | ||
| 34 | - | ||
| 35 | -| 重要参数 | 参数说明 | | ||
| 36 | -| --- | --- | | ||
| 37 | -| `--transformer-impl transformer_engine` | CP>1 的必需后端。 | | ||
| 38 | -| `--context-parallel-size C` | 长序列并行大小,默认 1。 | | ||
| 39 | -| `--cp-comm-type a2a+p2p` | 开启混合长序列并行。 | | ||
| 40 | -| `--hierarchical-context-parallel-sizes A R` | A 为 Ulysses 度数,R 为 Ring 度数;A×R=C。注意力头数应能被 TP×A 整除。 | | ||
| 41 | - | ||
| 42 | -`--attention-mask-type` 可选择 `causal`(默认)或 `general`。支持 `--use-cp-send-recv-overlap`、`--use-fused-ring-attention-update` 和 `--cp-window-size`;窗口大小须小于 Ring 度数 R 且能整除 R。不支持 EOD Reset。 | ||
| 43 | - | ||
| 44 | -## 使用效果 | ||
| 45 | - | ||
| 46 | -利用多个计算设备对输入序列进行并行切分,降低单设备的内存消耗,相比不开启序列并行单步耗时增加,相比重计算计算效率提升。 | ||
| 47 | - | ||
| 48 | -## 鸣谢 | ||
| 49 | - | ||
| 50 | -1. GitHub项目地址: | ||
| 51 | -<https://github.com/feifeibear/long-context-attention> | ||
| 52 | - | ||
| 53 | -2. 论文预印本地址: | ||
| 54 | -USP: A Unified Sequence Parallelism Approach for Long Context Generative AI | ||
| 55 | -<https://arxiv.org/abs/2405.07719> | ||
| @@ -20,7 +20,7 @@ KVAllGather通过收集完整的key、value计算本地query对应的attention | |||
| 20 | 20 | ||
| 21 | 在GQA(Grouped-Query Attention)、MQA(Multi-Query Attention)等场景下,由于对key和value进行all-gather通信所需的时间远少于整体计算时间,因此该方案带来的收益更为显著。 | 21 | 在GQA(Grouped-Query Attention)、MQA(Multi-Query Attention)等场景下,由于对key和value进行all-gather通信所需的时间远少于整体计算时间,因此该方案带来的收益更为显著。 |
| 22 | 22 | ||
| 23 | -该方案可与FlashAttention完全兼容,目前已默认启用FlashAttention进行加速计算。 | 23 | +该方案可与Flash Attention完全兼容,目前已默认启用Flash Attention进行加速计算。 |
| 24 | 24 | ||
| 25 | ## 使用方法 | 25 | ## 使用方法 |
| 26 | 26 | ||
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | ## 使用前提 | 3 | ## 使用前提 |
| 4 | 4 | ||
| 5 | -**后端限制:** MC2 仅作用于原生 ColumnParallelLinear/RowParallelLinear,不覆盖 TENPU 的 TE Linear。 | 5 | +**后端限制:** MC2 仅作用于原生 ColumnParallelLinear/RowParallelLinear,不覆盖 TE 路径(`--transformer-impl transformer_engine`,昇腾上由 TENPU 提供实现)下的线性层。 |
| 6 | 6 | ||
| 7 | 仅限于版本标识为`CANN 8.0.RC2`和`Ascend HDK 24.1.RC2`及其后续所有迭代版本的系统环境。 | 7 | 仅限于版本标识为`CANN 8.0.RC2`和`Ascend HDK 24.1.RC2`及其后续所有迭代版本的系统环境。 |
| 8 | 8 | ||
| @@ -37,7 +37,7 @@ MC2算子接口参见[mc2_opraters_api](https://www.hiascend.com/document/detail | |||
| 37 | ```python | 37 | ```python |
| 38 | # 举例1:冻结所有参数 | 38 | # 举例1:冻结所有参数 |
| 39 | for param in model.parameters(): | 39 | for param in model.parameters(): |
| 40 | - param.requires_grad = False | 40 | + param.requires_grad = False |
| 41 | ``` | 41 | ``` |
| 42 | 42 | ||
| 43 | ```python | 43 | ```python |
| @@ -50,6 +50,45 @@ for name, module in model.named_modules(): | |||
| 50 | param.requires_grad = False | 50 | param.requires_grad = False |
| 51 | ``` | 51 | ``` |
| 52 | 52 | ||
| 53 | +> [!NOTE] | ||
| 54 | +> | ||
| 55 | +> **适用范围**:举例2只适用于`--transformer-impl local`路径。在`--transformer-impl transformer_engine`路径下,线性层是Megatron的TE封装类,不是`ColumnParallelLinear` / `RowParallelLinear`的子类,`isinstance`恒为`False` —— **冻结静默失效:不报错、不打印、不冻任何参数**。 | ||
| 56 | + | ||
| 57 | +两条路径下线性层的类: | ||
| 58 | + | ||
| 59 | +| 模块 | `local` | `transformer_engine` | | ||
| 60 | +| --- | --- | --- | | ||
| 61 | +| `self_attention.linear_qkv` | `ColumnParallelLinear` | `TELayerNormColumnParallelLinear` | | ||
| 62 | +| `mlp.linear_fc1` | `ColumnParallelLinear` | `TELayerNormColumnParallelLinear` | | ||
| 63 | +| `self_attention.linear_proj` | `RowParallelLinear` | `TERowParallelLinear` | | ||
| 64 | +| `mlp.linear_fc2` | `RowParallelLinear` | `TERowParallelLinear` | | ||
| 65 | + | ||
| 66 | +- `local`:线性层为Megatron原生实现;开启`--use-ascend-mc2`后替换为`MindSpeedMC2Column/RowParallelLinear`,仍继承原生类,举例2 的`isinstance`照样命中。 | ||
| 67 | +- `transformer_engine`:昇腾上由TENPU(环境中的`transformer_engine`包)提供实现;模型线性层是Megatron的TE封装类,位于`megatron.core.extensions.transformer_engine`,继承TENPU的`te.pytorch.Linear` / `LayerNormLinear`。 | ||
| 68 | +- `TELayerNormColumnParallelLinear`融合了LayerNorm且不继承`TELinear`,需单独匹配,其`layer_norm_weight`保留可训练。 | ||
| 69 | + | ||
| 70 | +```python | ||
| 71 | +# 举例3:冻结所有 column + row 线性层,两条路径通用 | ||
| 72 | +from megatron.core.tensor_parallel.layers import ColumnParallelLinear, RowParallelLinear | ||
| 73 | +from megatron.core.extensions.transformer_engine import TEColumnParallelLinear, TERowParallelLinear | ||
| 74 | +from megatron.core.extensions.transformer_engine import TELayerNormColumnParallelLinear | ||
| 75 | + | ||
| 76 | +FREEZE_TYPES = (ColumnParallelLinear, RowParallelLinear, | ||
| 77 | + TEColumnParallelLinear, TERowParallelLinear, TELayerNormColumnParallelLinear) | ||
| 78 | +for name, module in model.named_modules(): | ||
| 79 | + if 'output_layer' in name or not isinstance(module, FREEZE_TYPES): | ||
| 80 | + continue | ||
| 81 | + for param_name, param in module.named_parameters(recurse=False): | ||
| 82 | + if 'norm' in param_name: # 融合进线性层的 LayerNorm,保留可训练 | ||
| 83 | + continue | ||
| 84 | + param.requires_grad = False | ||
| 85 | + print(f'rank:{torch.distributed.get_rank()}, frozen: {name}') | ||
| 86 | +``` | ||
| 87 | + | ||
| 88 | +举例3必须从`megatron.core.extensions.transformer_engine`导入TE封装类(模型实例就是这一层的类);`transformer_engine.pytorch.*`是TENPU的基类,模型里没有这种实例,TENPU改成不继承后会再次静默失效。 | ||
| 89 | + | ||
| 90 | +失效是静默的,建议保留打印并在CI断言条数:`rank数 × (num_layers / pipeline_model_parallel_size) × 4`(8卡/8层/PP=2时=128,只冻row=64)。 | ||
| 91 | + | ||
| 53 | ## 使用方法 | 92 | ## 使用方法 |
| 54 | 93 | ||
| 55 | 原生线性层路径设置 `--transformer-impl local --use-ascend-mc2` 使能 MC2 算子。 | 94 | 原生线性层路径设置 `--transformer-impl local --use-ascend-mc2` 使能 MC2 算子。 |
| @@ -31,6 +31,6 @@ MoE中,存在大量的EP通信没有做通信隐藏,端到端时间占比大 | |||
| 31 | 31 | ||
| 32 | ## 适用场景 | 32 | ## 适用场景 |
| 33 | 33 | ||
| 34 | -适用megatron-moe,dropless方案分支时候,需要提高训练性能的场景。相较基准dispatcher场景,性能可提升10%+。 | 34 | +适用megatron-moe,dropless方案分支,需要提高训练性能的场景。相较基准dispatcher场景,性能可提升10%+。 |
| 35 | 在开启`--moe-shared-expert-overlap`后,仍可提高4%以上的性能。 | 35 | 在开启`--moe-shared-expert-overlap`后,仍可提高4%以上的性能。 |
| 36 | 启动该特性会导致显存占用增加,属正常现象。此时,可搭配ZeroMemory特性调整显存使用状况。ZeroMemory介绍及设置可参考[此处](megatron-moe-zero-memory.md)。 | 36 | 启动该特性会导致显存占用增加,属正常现象。此时,可搭配ZeroMemory特性调整显存使用状况。ZeroMemory介绍及设置可参考[此处](megatron-moe-zero-memory.md)。 |
| @@ -23,7 +23,7 @@ MindSpeed基于昇腾硬件特点,设计实现了一套高性能的MoE跨micro | |||
| 23 | 23 | ||
| 24 | MindSpeed实现的1F1B细粒度计算和通信流水排布如下图: | 24 | MindSpeed实现的1F1B细粒度计算和通信流水排布如下图: |
| 25 |  | 25 |  |
| 26 | -通过分离调度专家和Attention部分反向的dw和dx计算,可实现1F1B阶段的A2A全掩盖。同时,由于昇腾硬件上通信行为由AICPU下发,不会消耗cube计算单元资源,因此计算和通信的并发对计算效率的影响很低。另外,使用了Attention部分的dw计算掩盖了PP的通信,从而实现1F1B阶段通信的全掩盖。 | 26 | +通过分离调度专家和Attention部分反向的dw和dx计算,可实现1F1B阶段的A2A全掩盖。同时,由于昇腾硬件上通信行为由AI CPU下发,不会消耗cube计算单元资源,因此计算和通信的并发对计算效率的影响很低。另外,使用了Attention部分的dw计算掩盖了PP的通信,从而实现1F1B阶段通信的全掩盖。 |
| 27 | 27 | ||
| 28 | 下图是真实671B DeepSeekV3模型使用该特性时,单层内的A2A通信掩盖profiling示意图: | 28 | 下图是真实671B DeepSeekV3模型使用该特性时,单层内的A2A通信掩盖profiling示意图: |
| 29 | 29 | ||
| @@ -23,7 +23,7 @@ | |||
| 23 | 典型场景: | 23 | 典型场景: |
| 24 | 24 | ||
| 25 | - EP变小导致单卡专家数量增大 & DeepSeek MoE专家数量较多等场景。 | 25 | - EP变小导致单卡专家数量增大 & DeepSeek MoE专家数量较多等场景。 |
| 26 | -- DeepSeek MoE finegrained expert单个专家较小 & FFN规模不大 & TP变大导致单卡切分的计算变小。 | 26 | +- DeepSeek MoE fine-grained expert单个专家较小 & FFN规模不大 & TP变大导致单卡切分的计算变小。 |
| 27 | 27 | ||
| 28 | 1. 随着FFN规模提升,计算不再细碎,单专家计算效率提升,Grouped GEMM 收益变小。 | 28 | 1. 随着FFN规模提升,计算不再细碎,单专家计算效率提升,Grouped GEMM 收益变小。 |
| 29 | 29 | ||
| @@ -37,7 +37,7 @@ | |||
| 37 | 37 | ||
| 38 | 2. TP越大,EP越小,收益更大。 | 38 | 2. TP越大,EP越小,收益更大。 |
| 39 | 39 | ||
| 40 | - 表2:Mixtral8*7B模型配置不同性能收益 | 40 | + 表2:Mixtral 8x7B模型配置不同性能收益 |
| 41 | 41 | ||
| 42 | |配置| tp4 ep2 16expert | tp4 ep2 8expert | tp2 ep4 16expert| tp2 ep4 8expert| | 42 | |配置| tp4 ep2 16expert | tp4 ep2 8expert | tp2 ep4 16expert| tp2 ep4 8expert| |
| 43 | |--|--|--|--|--| | 43 | |--|--|--|--|--| |
| @@ -11,13 +11,13 @@ MoE模型训练过程中专家负载具有“冷热不均”现象,尤其是 | |||
| 11 | 11 | ||
| 12 | <p align="center"> <img src="../figures/expert_load_balance1.png" ></p> | 12 | <p align="center"> <img src="../figures/expert_load_balance1.png" ></p> |
| 13 | 13 | ||
| 14 | -该方案主要包括规划器和执行器两部分。 | 14 | +该方案主要包括规划器和执行器两部分。 |
| 15 | **规划器**:进行迁移准备工作,包括专家负载数据收集,负载预测和专家分配方案优化等几个部分。 | 15 | **规划器**:进行迁移准备工作,包括专家负载数据收集,负载预测和专家分配方案优化等几个部分。 |
| 16 | 16 | ||
| 17 | * 专家负载数据收集功能集成在负载预测模块中 | 17 | * 专家负载数据收集功能集成在负载预测模块中 |
| 18 | * 专家负载预测采取指数滑动平均(EMA)方法,计算式为 | 18 | * 专家负载预测采取指数滑动平均(EMA)方法,计算式为 |
| 19 | $ELP_{t+1} = \theta * ELP_{t} + (1-\theta)EL_t, $ | 19 | $ELP_{t+1} = \theta * ELP_{t} + (1-\theta)EL_t, $ |
| 20 | -其中,$ELP_t$为$t$步的专家负载预测, 为采集的$t$步专家负载数据,$θ$为EMA权重,一般取0.9-0.999。$θ$越大,负载预测越关注历史数据,当前负载数据影响越小。本方案中取θ=0.9,更能捕捉到当前的负载特征,基于此的专家迁移对变化负载的适应性更强。 | 20 | +其中,$ELP_t$为$t$步的专家负载预测, $EL_t$为采集的$t$步专家负载数据,$θ$为EMA权重,一般取0.9-0.999。$θ$越大,负载预测越关注历史数据,当前负载数据影响越小。本方案中取θ=0.9,更能捕捉到当前的负载特征,基于此的专家迁移对变化负载的适应性更强。 |
| 21 | EMA方法负载预测更新通过迭代方法处理数据,不需要保存历史负载信息,计算轻量化,预测效果也非常好。 | 21 | EMA方法负载预测更新通过迭代方法处理数据,不需要保存历史负载信息,计算轻量化,预测效果也非常好。 |
| 22 | 22 | ||
| 23 | 在迁移前,在DP域对专家负载预测结果进行allreduce操作,确保所有DP域负载预测和基于该预测结果的专家分配映射关系一致。 | 23 | 在迁移前,在DP域对专家负载预测结果进行allreduce操作,确保所有DP域负载预测和基于该预测结果的专家分配映射关系一致。 |
| @@ -56,7 +56,7 @@ For buffer in buffers: | |||
| 56 | 3.执行allgather操作:对优化器状态交换buffer进行dp组内的allgather操作,得到完整的优化器状态 | 56 | 3.执行allgather操作:对优化器状态交换buffer进行dp组内的allgather操作,得到完整的优化器状态 |
| 57 | 4.执行alltoall操作:将本地专家参数状态从优化器状态交换buffer中取出,通过alltoall操作进行专家迁移 | 57 | 4.执行alltoall操作:将本地专家参数状态从优化器状态交换buffer中取出,通过alltoall操作进行专家迁移 |
| 58 | 5.更新本地状态:保留优化器状态交换buffer中的专家参数状态切片,并更新本地优化器状态切片 | 58 | 5.更新本地状态:保留优化器状态交换buffer中的专家参数状态切片,并更新本地优化器状态切片 |
| 59 | - 6.释放缓冲区:释放临时分配的优化器状态交换缓冲区,以节省内存资源 。 | 59 | + 6.释放缓冲区:释放临时分配的优化器状态交换缓冲区 |
| 60 | ``` | 60 | ``` |
| 61 | 61 | ||
| 62 | ## 使用说明 | 62 | ## 使用说明 |
| @@ -1,54 +0,0 @@ | |||
| 1 | -# PP支持多参数传递 | ||
| 2 | - | ||
| 3 | -## 背景与挑战 | ||
| 4 | - | ||
| 5 | -在深度学习的大模型分布式训练中,流水线并行(Pipeline Parallelism, PP)是一种将模型分割为多个阶段并在不同设备上并发执行以提高效率的技术。然而,在多模态场景下引入多参数传递支持时,PP面临特定的挑战: | ||
| 6 | - | ||
| 7 | -- **通信部分的设计**:传统PP通常只涉及单一张量的传输,但在多参数传递的情况下,需要处理多个变量的传递。这不仅增加了通信复杂度,还要求对每个变量的shape、dtype等属性进行精确管理,这些属性往往与整体模型架构紧密相关,具有高度定制性。 | ||
| 8 | -- **前向传播的变量传递**:在前向计算过程中,不仅要根据定义的shape正确传递多个变量,还要确保每个阶段接收到的数据格式符合预期,这对数据流的设计提出了更高的要求。 | ||
| 9 | -- **反向传播的运算扩展**:对于反向传播,除了对首个输出进行梯度计算外,还需对其他所有输出进行相应的运算,确保整个训练过程的完整性和准确性。 | ||
| 10 | - | ||
| 11 | -## 解决方案 | ||
| 12 | - | ||
| 13 | -针对上述挑战,我们设计了以下解决方案,旨在使PP能够有效支持多参数传递: | ||
| 14 | - | ||
| 15 | -- **优化的通信机制**:开发了一套高效的通信机制,支持多种类型和格式的数据传输。针对每个阶段的具体需求定制化配置传输参数。 | ||
| 16 | -- **增强的梯度计算逻辑**:改进了反向传播算法,使得系统可以自动识别并处理来自多个输出的梯度信息,保证每个输出都能参与到最终的权重更新中。 | ||
| 17 | - | ||
| 18 | -## 使用场景 | ||
| 19 | - | ||
| 20 | -本特性特别适用于以下场景: | ||
| 21 | - | ||
| 22 | -- 需要处理大量多模态数据(如文本、图像、音频)的大型神经网络训练任务,并且流水线并行各个阶段传递多参数。 | ||
| 23 | - | ||
| 24 | -## 使用方法 | ||
| 25 | - | ||
| 26 | -**注意事项**: | ||
| 27 | -用户需修改mindspeed/features_manager/pipeline_parallel/multi_parameter.py模块中validate_args函数里args.pipeline_tensor_shapes值与实际模型流水线阶段的张量传输一致,包括张量维度(Shape)和数据类型(Dtype)。 | ||
| 28 | - | ||
| 29 | -**设置训练脚本参数** | ||
| 30 | - | ||
| 31 | -- 支持PP场景 | ||
| 32 | - | ||
| 33 | -```shell | ||
| 34 | -# PP >= 2 | ||
| 35 | ---pipeline-model-parallel-size ${PP} \ | ||
| 36 | ---use-multiparameter-pipeline-model-parallel \ | ||
| 37 | -``` | ||
| 38 | - | ||
| 39 | -- 支持VPP场景 | ||
| 40 | - | ||
| 41 | -```shell | ||
| 42 | -# PP >= 2, num-layers-per-virtual-pipeline-stage不为None | ||
| 43 | ---pipeline-model-parallel-size ${PP} \ | ||
| 44 | ---num-layers-per-virtual-pipeline-stage 1 \ | ||
| 45 | ---use-multiparameter-pipeline-model-parallel \ | ||
| 46 | -``` | ||
| 47 | - | ||
| 48 | -## 使用限制 | ||
| 49 | - | ||
| 50 | -1. 仅支持 decoder 流水线。 | ||
| 51 | - | ||
| 52 | -## 使用效果 | ||
| 53 | - | ||
| 54 | -采用PP支持多参数传递后,用户可以在保持高通信效率的同时,更灵活地处理复杂的多模态数据。 | ||
| @@ -1,56 +0,0 @@ | |||
| 1 | -# PP支持多参数传递和动态形状 | ||
| 2 | - | ||
| 3 | -## 背景与挑战 | ||
| 4 | - | ||
| 5 | -在深度学习的大规模分布式训练中,流水线并行(Pipeline Parallelism, PP)通过将模型分割为多个阶段并在不同设备上并发执行来提高效率。然而,在处理复杂的多模态数据时,PP面临了新的挑战: | ||
| 6 | - | ||
| 7 | -- **对于多参数传递**:传统PP通常只涉及单一张量的传输,但在多参数传递的情况下,需要处理多个变量的传递,这不仅增加了通信复杂度,还要求对每个变量的shape、dtype等属性进行精确管理 。 | ||
| 8 | -- **对于动态形状**:当输入数据的序列长度不固定时,传统的方法是将所有序列调整到统一长度,这导致了内存和计算资源的浪费 。 | ||
| 9 | - | ||
| 10 | -## 解决方案 | ||
| 11 | - | ||
| 12 | -为了应对这些挑战,开发了一系列优化措施: | ||
| 13 | - | ||
| 14 | -- **多参数传递**:开发了一套高效的通信机制,支持多种类型和格式的数据传输,并改进了反向传播算法,使得系统可以自动识别并处理来自多个输出的梯度信息 。 | ||
| 15 | -- **动态形状**:引入对动态形状的支持,允许每个微批次中的序列保持其原始长度。这样可以通过在发送张量之前,提前通信张量的形状信息,在各个流水线阶段之间同步即将接收的数据形状,确保内存分配和预处理的准确性 。 | ||
| 16 | - | ||
| 17 | -## 使用场景 | ||
| 18 | - | ||
| 19 | -- **多参数传递**:适用于需要处理大量多模态数据的任务,如文本、图像和音频等大型神经网络训练任务,其中流水线并行的各个阶段都需要传递多参数 。 | ||
| 20 | -- **动态形状**:非常适合于处理文本长度差异很大的任务,比如文档分类和机器翻译,同时也增强了模型的泛化能力 。 | ||
| 21 | - | ||
| 22 | -## 使用方法 | ||
| 23 | - | ||
| 24 | -**注意事项**: | ||
| 25 | -用户需修改mindspeed/features_manager/pipeline_parallel/multi_parameter.py模块中validate_args函数里args.pipeline_tensor_shapes值与实际模型流水线阶段的张量传输一致,包括张量维度(Shape)和数据类型(Dtype)。 | ||
| 26 | - | ||
| 27 | -**设置训练脚本参数** | ||
| 28 | - | ||
| 29 | -- # 支持PP场景 | ||
| 30 | - | ||
| 31 | -```shell | ||
| 32 | -# 配置举例 | ||
| 33 | -# PP >= 2 | ||
| 34 | ---pipeline-model-parallel-size ${PP} \ | ||
| 35 | ---use-multiparameter-pipeline-model-parallel \ | ||
| 36 | ---variable-seq-lengths \ | ||
| 37 | -``` | ||
| 38 | - | ||
| 39 | -- # 支持VPP场景 | ||
| 40 | - | ||
| 41 | -```shell | ||
| 42 | -# 配置举例 | ||
| 43 | -# PP >= 2, num-layers-per-virtual-pipeline-stage不为None | ||
| 44 | ---pipeline-model-parallel-size ${PP} \ | ||
| 45 | ---num-layers-per-virtual-pipeline-stage 1 \ | ||
| 46 | ---use-multiparameter-pipeline-model-parallel \ | ||
| 47 | ---variable-seq-lengths \ | ||
| 48 | -``` | ||
| 49 | - | ||
| 50 | -## 使用限制 | ||
| 51 | - | ||
| 52 | -1. 仅支持 decoder 流水线。 | ||
| 53 | - | ||
| 54 | -## 使用效果 | ||
| 55 | - | ||
| 56 | -同时支持在流水线并行中各阶段间传递多个参数和处理变长输入数据。 | ||
| @@ -20,12 +20,12 @@ | |||
| 20 | 20 | ||
| 21 | ## 使用方法 | 21 | ## 使用方法 |
| 22 | 22 | ||
| 23 | -要启用此功能,用户需通过命令行参数设置目标层为无操作层。例如,原模型共126层,该模型参数为 `--num-layers 126`,即执行实际计算的层有126层。 | 23 | +要启用此功能,用户需通过命令行参数设置目标层为空操作层。例如,原模型共126层,该模型参数为 `--num-layers 126`,即执行实际计算的层有126层。 |
| 24 | 若在该模型首和尾各自添加1层空层,则该模型参数应设置为 `--num-layers 128 --noop-layers 0,127` ,表示总共128层,首尾层(即第0层和第127层,层数从0开始计数)为不执行实际计算的空操作层,中间的126层为执行实际计算的层。 | 24 | 若在该模型首和尾各自添加1层空层,则该模型参数应设置为 `--num-layers 128 --noop-layers 0,127` ,表示总共128层,首尾层(即第0层和第127层,层数从0开始计数)为不执行实际计算的空操作层,中间的126层为执行实际计算的层。 |
| 25 | 25 | ||
| 26 | ## 使用效果 | 26 | ## 使用效果 |
| 27 | 27 | ||
| 28 | -通过实施自定义增加无操作层的策略,预期能够显著减少流水线中的空泡现象,从而优化计算流程并提升系统性能。这不仅有助于加速模型训练过程,还能最大化硬件资源的利用率。 | 28 | +通过实施自定义增加空操作层的策略,预期能够显著减少流水线中的空泡现象,从而优化计算流程并提升系统性能。这不仅有助于加速模型训练过程,还能最大化硬件资源的利用率。 |
| 29 | 29 | ||
| 30 | * 减少空泡现象:通过将计算密集型任务重新分配到流水线的不同阶段,减少了因某些阶段计算负载过高而导致的空闲时间,提高了整个系统的吞吐量。 | 30 | * 减少空泡现象:通过将计算密集型任务重新分配到流水线的不同阶段,减少了因某些阶段计算负载过高而导致的空闲时间,提高了整个系统的吞吐量。 |
| 31 | 31 | ||
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | ## 背景与挑战 | 3 | ## 背景与挑战 |
| 4 | 4 | ||
| 5 | -大模型训练中,极小的数据波动就很可能带来最终评分的较大下降,这使得模型在精度对照时往往存在巨大的工作量,尤其是在进行跨平台(GPU→NPU)对照的场景。借助mstt工具,Ascend芯片可以较快的完成整网训练数据的采集,配合确定性计算来达到精度比对的功能。然而mstt使用时需要手动修改代码,并设置调节config,这使得其在mindspeed中的使能存在一定不便。 | 5 | +大模型训练中,极小的数据波动就很可能带来最终评分的较大下降,这使得模型在精度对照时往往存在巨大的工作量,尤其是在进行跨平台(GPU→NPU)对照的场景。借助mstt工具,Ascend芯片可以较快地完成整网训练数据的采集,配合确定性计算来达到精度比对的功能。然而mstt使用时需要手动修改代码,并设置调节config,这使得其在mindspeed中的使能存在一定不便。 |
| 6 | 6 | ||
| 7 | ## 解决方案 | 7 | ## 解决方案 |
| 8 | 8 | ||
| @@ -10,14 +10,14 @@ | |||
| 10 | 10 | ||
| 11 | ## 使用场景 | 11 | ## 使用场景 |
| 12 | 12 | ||
| 13 | -需要进行精度对比、特定场景复现时。 | 13 | +需要进行精度对照、特定场景复现时。 |
| 14 | 14 | ||
| 15 | ## 使用方法 | 15 | ## 使用方法 |
| 16 | 16 | ||
| 17 | 要启用此功能,在脚本中加入`--npu-datadump`即可。使用前请先进行下述config.json的修改。默认状态下,采集RANK0、STEP0下的statistics精度。 | 17 | 要启用此功能,在脚本中加入`--npu-datadump`即可。使用前请先进行下述config.json的修改。默认状态下,采集RANK0、STEP0下的statistics精度。 |
| 18 | > 注意:该功能已随架构拆分迁移至 MegatronAdaptor(MA),config.json 位于 MA 仓对应的 npu_datadump 补丁目录下。 | 18 | > 注意:该功能已随架构拆分迁移至 MegatronAdaptor(MA),config.json 位于 MA 仓对应的 npu_datadump 补丁目录下。 |
| 19 | 通过调整 MA 补丁目录中的`config.json`,可以进行整网dump时各选项的调整,并可配置利用 mstt 进行各 dump 数据的精度比对。 | 19 | 通过调整 MA 补丁目录中的`config.json`,可以进行整网dump时各选项的调整,并可配置利用 mstt 进行各 dump 数据的精度比对。 |
| 20 | -关于config设置的更多细节,请参考mstt官方使用教程:[<td><a href="https://gitcode.com/Ascend/mstt/tree/master/debug/accuracy_tools/msprobe">link</a></td>] | 20 | +关于config设置的更多细节,请参考mstt官方使用教程:[<td><a href="https://gitcode.com/Ascend/mstt/tree/26.0.0/debug/accuracy_tools/msprobe">link</a></td>] |
| 21 | 21 | ||
| 22 | - 暂不支持Lite后端。 | 22 | - 暂不支持Lite后端。 |
| 23 | - dump数据默认保存在Megatron-LM目录下。 | 23 | - dump数据默认保存在Megatron-LM目录下。 |
| @@ -30,4 +30,4 @@ LLaMA及GPT大模型均可使用。 | |||
| 30 | 30 | ||
| 31 | ## 使用效果 | 31 | ## 使用效果 |
| 32 | 32 | ||
| 33 | -在内存没有完全使用或占满的情况下,开启Matmul_Add融合算子,模型训练的性能将得到提升,在LLaMA2-7B模型下,性能增益约2%。 | 33 | +在内存未占满的情况下,开启Matmul_Add融合算子,模型训练的性能将得到提升,在LLaMA2-7B模型下,性能增益约2%。 |
| @@ -23,7 +23,7 @@ | |||
| 23 | 23 | ||
| 24 | ## 注意事项 | 24 | ## 注意事项 |
| 25 | 25 | ||
| 26 | -(1)由于此功能统计的是各卡的TFLOPS信息,在CP/EP/PP场景下,各卡计算量不同,因此在最后需要汇总各卡的信息进行平均,额外增加一个all_reduce通信。 | 26 | +(1)由于此功能统计的是各卡的TFLOP/s信息,在CP/EP/PP场景下,各卡计算量不同,因此在最后需要汇总各卡的信息进行平均,额外增加一个all_reduce通信。 |
| 27 | 27 | ||
| 28 | (2)使用此功能由于会增加一个额外通信以及计算各算子的浮点计算次数,可能影响性能。 | 28 | (2)使用此功能由于会增加一个额外通信以及计算各算子的浮点计算次数,可能影响性能。 |
| 29 | 29 | ||
| @@ -45,7 +45,7 @@ python ./preprocess_data.py \ | |||
| 45 | --pad-to-multiple-of 8 \ | 45 | --pad-to-multiple-of 8 \ |
| 46 | --json-keys text \ | 46 | --json-keys text \ |
| 47 | --workers 4 \ | 47 | --workers 4 \ |
| 48 | - --log-interval 1000 | 48 | + --log-interval 1000 |
| 49 | ``` | 49 | ``` |
| 50 | 50 | ||
| 51 | #### 参数说明 | 51 | #### 参数说明 |
| @@ -66,7 +66,7 @@ python ./preprocess_data.py \ | |||
| 66 | --json-keys text input output | 66 | --json-keys text input output |
| 67 | ``` | 67 | ``` |
| 68 | 68 | ||
| 69 | -- `append-eod`:该参数的作用是将文档结束标记`EOD`显示地添加到每条数据的末尾,防止模型学习无意义的关联 | 69 | +- `append-eod`:该参数的作用是将文档结束标记`EOD`显式地添加到每条数据的末尾,防止模型学习无意义的关联 |
| 70 | - `pad-to-multiple-of`:该参数的作用是将每条数据的长度pad到pad-to-multiple-of的倍数 | 70 | - `pad-to-multiple-of`:该参数的作用是将每条数据的长度pad到pad-to-multiple-of的倍数 |
| 71 | 71 | ||
| 72 | `append-eod`和`pad-to-multiple-of`参数使能后的效果如下: | 72 | `append-eod`和`pad-to-multiple-of`参数使能后的效果如下: |
| @@ -1,51 +0,0 @@ | |||
| 1 | -# 重计算流水线独立调度 | ||
| 2 | - | ||
| 3 | -## 背景与挑战 | ||
| 4 | - | ||
| 5 | -在目前的流水线调度中,重计算由反向计算触发,与反向计算绑定在一起调度,意味着重计算需要等待下一个stage返回梯度才可以开始计算。然而重计算并不需要用到反向计算的梯度,这导致bubble的增多和性能的下降。 | ||
| 6 | - | ||
| 7 | -## 解决方案 | ||
| 8 | - | ||
| 9 | -为了将重计算和反向计算独立调度,需要将重计算的调度修改为由调度器主动触发,并修改调度器,将重计算作为一个调度单元加入到调度器中,这使我们获得了自由地插入或去除部分重计算的能力,进而可以在内存和性能方面做出优化。 | ||
| 10 | - | ||
| 11 | -通过torch的saved_tensors_hooks实现一种新的重计算方法,在反向计算前合适的时机主动触发或者直接去除部分重计算,从而实现对内存或性能的优化。 | ||
| 12 | - | ||
| 13 | -## 使用场景 | ||
| 14 | - | ||
| 15 | -**后端限制:** FP8/FP4 重计算必须使用 `--transformer-impl transformer_engine`。 | ||
| 16 | - | ||
| 17 | -在虚拟流水线调度中,若用户未开启重计算,则可以利用bubble主动插入重计算,以极小的性能代价换取内存峰值的降低,将需要保留激活值的前向计算块的个数减少到PP * VPP(PP表示流水线并行数,VPP表示虚拟流水线并行数)。 | ||
| 18 | - | ||
| 19 | -### 图1 未开启重计算调度图 | ||
| 20 | - | ||
| 21 | -<p align="center"> <img src="../figures/ripipe_a.png" height="154px" width="972px"></p> | ||
| 22 | - | ||
| 23 | -在虚拟流水线调度中,若用户已开启重计算,则可以通过解除重计算与后一个stage的反向计算间的依赖关系从而提前重计算,以及去除模型最后一层的重计算,实现计算性能的提升。 | ||
| 24 | - | ||
| 25 | -#### 图2 开启重计算调度图 | ||
| 26 | - | ||
| 27 | -<p align="center"> <img src="../figures/ripipe_b.png" height="122px" width="954px"></p> | ||
| 28 | - | ||
| 29 | -## 使用方法 | ||
| 30 | - | ||
| 31 | -需在训练脚本中加入以下参数配置: | ||
| 32 | - | ||
| 33 | -* 开启利用bubble进行重计算功能: | ||
| 34 | -`--recompute-in-bubble` | ||
| 35 | -必须开启虚拟流水线并行特性,使用此功能前不能开启重计算,recompute_num_layers参数需为None或0。 | ||
| 36 | - | ||
| 37 | -+ 开启提前重计算以及去除不必要重计算功能: | ||
| 38 | -`--recompute-in-advance` | ||
| 39 | -必须开启虚拟流水线并行特性,使用此功能前需要开启重计算,且不支持recompute_method为uniform,recompute_num_layers不能为None或0。 | ||
| 40 | - | ||
| 41 | -### 说明 | ||
| 42 | - | ||
| 43 | -* --recompute-in-bubble 特性暂不兼容完全重计算uniform、完全重计算block、选择重计算、no-align-grad-reduce和no-overlap-p2p-communication特性,不兼容moe场景下的--moe-layer-recompute特性。 | ||
| 44 | - | ||
| 45 | -+ --recompute-in-advance 特性暂不兼容完全重计算uniform、选择重计算、no-align-grad-reduce和no-overlap-p2p-communication特性。 | ||
| 46 | - | ||
| 47 | -## 使用效果 | ||
| 48 | - | ||
| 49 | -`--recompute-in-bubble`, 在bubble主动插入重计算,实现内存节省。 | ||
| 50 | - | ||
| 51 | -`--recompute-in-advance`, 在bubble处提前开启重计算,相比于默认的完全重计算方案可以实现训练性能提升。 | ||
| @@ -18,7 +18,7 @@ | |||
| 18 | 请参照下图了解参数副本复用的具体流程。 | 18 | 请参照下图了解参数副本复用的具体流程。 |
| 19 | <p align="center"> <img src="../figures/reuse_fp32_param_a.png" height="300px" width="750px"></p> | 19 | <p align="center"> <img src="../figures/reuse_fp32_param_a.png" height="300px" width="750px"></p> |
| 20 | 20 | ||
| 21 | -数值变化的详细逻辑如下图所示: | 21 | +数值变换的详细逻辑如下图所示: |
| 22 | 22 | ||
| 23 | ### 图2 数值变换的详细逻辑 | 23 | ### 图2 数值变换的详细逻辑 |
| 24 | 24 | ||
| @@ -24,7 +24,7 @@ Ring Attention借鉴了分块Softmax原理,在不需要获取整个序列的 | |||
| 24 | 24 | ||
| 25 | 不同于Ulysses方案,该方案不需要确保head_size被cp_size整除。 | 25 | 不同于Ulysses方案,该方案不需要确保head_size被cp_size整除。 |
| 26 | 26 | ||
| 27 | -可兼容FlashAttention,目前已默认开启FlashAttention。 | 27 | +可兼容Flash Attention,目前已默认开启Flash Attention。 |
| 28 | 28 | ||
| 29 | 如果想要使得计算和通信可以互相掩盖,理论上需要确保每个计算块分到的序列长度$c \geq F/B$。其中F是每个device的FLOPS,B是每个device间的带宽。具体推导过程参见原文。在实践中,需要确保每个计算块分到的序列长度足够大,才能较好掩盖。 | 29 | 如果想要使得计算和通信可以互相掩盖,理论上需要确保每个计算块分到的序列长度$c \geq F/B$。其中F是每个device的FLOPS,B是每个device间的带宽。具体推导过程参见原文。在实践中,需要确保每个计算块分到的序列长度足够大,才能较好掩盖。 |
| 30 | 30 | ||
| @@ -16,10 +16,10 @@ | |||
| 16 | 16 | ||
| 17 | 1. 在优化器初始化 `shard_fp32_from_float16_groups` 的时候,会从模型权重(bf16)复制权重到优化器权重(fp32), | 17 | 1. 在优化器初始化 `shard_fp32_from_float16_groups` 的时候,会从模型权重(bf16)复制权重到优化器权重(fp32), |
| 18 | 为了不冲击显存峰值,需要每复制一份权重就将权重 swap 到 host 侧。权重加载的时候同理,每次加载一份权重就进行 swap 操作, | 18 | 为了不冲击显存峰值,需要每复制一份权重就将权重 swap 到 host 侧。权重加载的时候同理,每次加载一份权重就进行 swap 操作, |
| 19 | -由于只在初始化阶段,因此对性能影响可忽略。 | 19 | +由于只在初始化阶段,对性能影响可忽略。 |
| 20 | 2. 在 step 阶段,为了 h2d 和 d2h 的并行,会先一次性下发大约 `numel(shard_fp32_from_float16_groups) // swap_optimizer_times` | 20 | 2. 在 step 阶段,为了 h2d 和 d2h 的并行,会先一次性下发大约 `numel(shard_fp32_from_float16_groups) // swap_optimizer_times` |
| 21 | 大小参数的 h2d 操作,再做 AdamW 计算以及 copy 到模型权重(bf16),最后再 d2h 释放显存。 | 21 | 大小参数的 h2d 操作,再做 AdamW 计算以及 copy 到模型权重(bf16),最后再 d2h 释放显存。 |
| 22 | -3. 由于 d2h 与 h2d 是异步拷贝,为了保证时序正确,第二轮的 d2h 需要等前一轮的 h2d 操作结束之后再下发第二轮。 | 22 | +3. 由于 d2h 与 h2d 是异步拷贝,为了保证时序正确,第二轮的 d2h 需要等前一轮的 h2d 操作结束之后再下发。 |
| 23 | 23 | ||
| 24 |  | 24 |  |
| 25 | 25 | ||
| @@ -31,7 +31,7 @@ | |||
| 31 | 31 | ||
| 32 | Adam 使用 `--swap-optimizer --use-distributed-optimizer` 开启;Muon 使用 `--optimizer muon --use-distributed-optimizer --swap-optimizer`,采用 layer-wise distributed optimizer。 | 32 | Adam 使用 `--swap-optimizer --use-distributed-optimizer` 开启;Muon 使用 `--optimizer muon --use-distributed-optimizer --swap-optimizer`,采用 layer-wise distributed optimizer。 |
| 33 | 33 | ||
| 34 | -`--swap-optimizer-times`: 默认值为16,用于设置 step 更新阶段进行 swap 的次数,越小并行的越多,可减少性能劣化,但会提高显存峰值。 | 34 | +`--swap-optimizer-times`: 默认值为16,用于设置 step 更新阶段进行 swap 的次数,越小并行得越多,可减少性能劣化,但会提高显存峰值。 |
| 35 | 35 | ||
| 36 | 推荐配置 | 36 | 推荐配置 |
| 37 | 37 | ||
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | ## 背景与挑战 | 3 | ## 背景与挑战 |
| 4 | 4 | ||
| 5 | -SwiGLU(Swish-Gated Linear Unit,Swish门控线性单元激活函数)常见于在LLaMA、LLaMA2、Baichuan等大型语言模型中激活层。然而,由于PyTorch标准库中缺乏直接支持SwiGLU的算子接口,模型通常会以一系列基础算子组合的方式来实现SwiGLU功能,这种方式的执行效率并不理想。 | 5 | +SwiGLU(Swish-Gated Linear Unit,Swish门控线性单元激活函数)常见于LLaMA、LLaMA2、Baichuan等大型语言模型中激活层。然而,由于PyTorch标准库中缺乏直接支持SwiGLU的算子接口,模型通常会以一系列基础算子组合的方式来实现SwiGLU功能,这种方式的执行效率并不理想。 |
| 6 | 6 | ||
| 7 | ## 解决方法 | 7 | ## 解决方法 |
| 8 | 8 | ||
| @@ -20,6 +20,6 @@ SwiGLU(Swish-Gated Linear Unit,Swish门控线性单元激活函数)常见 | |||
| 20 | 20 | ||
| 21 | mcore分支下仅支持使能该融合算子。 | 21 | mcore分支下仅支持使能该融合算子。 |
| 22 | 22 | ||
| 23 | -## 使用效果 | 23 | +## 使用效果 |
| 24 | 24 | ||
| 25 | 在LLaMA2-7B模型下,通过启用融合优化后的SwiGLU算子,内存节省约16.6%,性能提升约4.7%,不仅可以有效降低内存消耗,还能大幅提升模型训练的运行效率。 | 25 | 在LLaMA2-7B模型下,通过启用融合优化后的SwiGLU算子,内存节省约16.6%,性能提升约4.7%,不仅可以有效降低内存消耗,还能大幅提升模型训练的运行效率。 |
| @@ -6,7 +6,7 @@ | |||
| 6 | 6 | ||
| 7 | ## 解决方法 | 7 | ## 解决方法 |
| 8 | 8 | ||
| 9 | -低精度在线比对功能通过对比不同硬件(NPU、CPU)和不同精度(BF16)的计算结果,帮助用户实时检查低精度操作(包括 cast 和 quantmatmul)的精度差异。启用该特性后,将同时进行 NPU 和 CPU/BF16 上的计算,并输出误差值,方便用户检测潜在的精度问题。 | 9 | +低精度在线比对功能通过对比不同硬件(NPU、CPU)和不同精度(BF16)的计算结果,帮助用户实时检查低精度操作(包括 cast 和 quant_matmul)的精度差异。启用该特性后,将同时进行 NPU 和 CPU/BF16 上的计算,并输出误差值,方便用户检测潜在的精度问题。 |
| 10 | 10 | ||
| 11 | ## 使用场景 | 11 | ## 使用场景 |
| 12 | 12 | ||
| @@ -19,4 +19,4 @@ | |||
| 19 | 19 | ||
| 20 | ## 使用效果 | 20 | ## 使用效果 |
| 21 | 21 | ||
| 22 | -在低精度计算过程中,将输出每一步NPU上 cast 和 quantmatmul 操作与精度标杆(CPU 或 BF16)之间的误差。如果误差超出预设范围,将会提示错误并终止训练过程。 | 22 | +在低精度计算过程中,将输出每一步NPU上 cast 和 quant_matmul 操作与精度标杆(CPU 或 BF16)之间的误差。如果误差超出预设范围,将会提示错误并终止训练过程。 |
| @@ -1,148 +0,0 @@ | |||
| 1 | -# 高维张量并行 | ||
| 2 | - | ||
| 3 | -## 背景与挑战 | ||
| 4 | - | ||
| 5 | -大模型训练时,张量并行(TP)将模型参数切分到多个设备上以减少其内存的占用,在训练过程中为了更新参数梯度信息等,需要引入allreduce通信。当集群规模较大时,如果设置TP域很大时,其通信开销会变得很大,使得训练效率降低。 | ||
| 6 | - | ||
| 7 | -## 解决方案 | ||
| 8 | - | ||
| 9 | -为了提高大规模TP域通信效率,采用高维张量并行,其将激活值和参数同时切分到多个计算设备上,相对1D-TP降低了通信域、减少通信次数,从而减少通信时间,提升模型训练的性能。 | ||
| 10 | - | ||
| 11 | -### 解决思路 | ||
| 12 | - | ||
| 13 | -#### 2D张量并行策略 | ||
| 14 | - | ||
| 15 | -给定TP域大小,通过建立多通信域,在原Megatron(ColumnParallelLinear、RowParallelLinear)增加了一维的切分维度。将原tp通信域进行分解为两个子通信域tp_x和tp_y,需要满足`tp = tp_x * tp_y`。以MLP层为例,其实现过程如下: | ||
| 16 | - | ||
| 17 | - | ||
| 18 | - | ||
| 19 | -#### 分布式normalization | ||
| 20 | - | ||
| 21 | -在transformer网络中,normalization会将每一层神经元的输入都转换成均值方差都一样的,加快其收敛。在MLP和attention层分别进行2D张量并行时,其输入和输出都分别在first-dim和last-dim做了tp_x和tp_y的切分,如果继续使用原LayerNorm或者RMSNorm需要先将input进行沿first-dim进行all-gather(x)和沿last-dim进行all-gather(y)操作,才能保证input数据的完整性。为了提升这部分的性能,采用了分布式normalization。其处理流程如下: | ||
| 22 | - | ||
| 23 | -##### **步骤1:计算输入的总和** | ||
| 24 | - | ||
| 25 | -首先,计算输入张量$\mathbf{x}$ 在最后一个维度上的总和: | ||
| 26 | - | ||
| 27 | -$$ | ||
| 28 | -e_x = \sum_{i=1}^{H} x_i | ||
| 29 | -\ | ||
| 30 | -$$ | ||
| 31 | - | ||
| 32 | -##### **步骤2:分布式归约操作(All-Reduce)** | ||
| 33 | - | ||
| 34 | -将步骤1中的总和 $e_x$ 在所有tp_y通信域进程中进行归约(求和),确保每个进程都拥有其通信域全局总和: | ||
| 35 | -$$ | ||
| 36 | -\ | ||
| 37 | -e_x^{\text{global}} = \text{AllReduce}\left( e_x \right) = \sum_{p=1}^{P} \sum_{i=1}^{H} x_i^{(p)} | ||
| 38 | -\ | ||
| 39 | -$$ | ||
| 40 | - | ||
| 41 | -其中: | ||
| 42 | - | ||
| 43 | -- $P$ 是分布式进程的数量。 | ||
| 44 | -- $x_i^{(p)}$ 表示第 $p$ 个进程中第 $i$ 个元素的值。 | ||
| 45 | - | ||
| 46 | -##### **步骤3:计算输入元素的平方和** | ||
| 47 | - | ||
| 48 | -接下来,计算输入张量每个元素的平方和: | ||
| 49 | - | ||
| 50 | -$$ | ||
| 51 | -s_x = \sum_{i=1}^{H} x_i^2 | ||
| 52 | -$$ | ||
| 53 | - | ||
| 54 | -##### **步骤4:分布式归约操作(All-Reduce)** | ||
| 55 | - | ||
| 56 | -将步骤3中的平方和 $s_x$ 在所有tp_y通信域进程中进行归约(求和),确保每个进程都拥有其通信域全局平方和: | ||
| 57 | - | ||
| 58 | -$$ | ||
| 59 | -s_x^{\text{global}} = \text{AllReduce}\left( s_x \right) = \sum_{p=1}^{P} \sum_{i=1}^{H} \left( x_i^{(p)} \right)^2 | ||
| 60 | -$$ | ||
| 61 | - | ||
| 62 | -##### **步骤5:中心化输入数据** | ||
| 63 | - | ||
| 64 | -将输入数据 $\mathbf{x}$ 中心化,即减去平均值。平均值 $\mu$ 计算如下: | ||
| 65 | - | ||
| 66 | -$$ | ||
| 67 | -\mu = \frac{e_x^{\text{global}}}{H} | ||
| 68 | -$$ | ||
| 69 | - | ||
| 70 | -然后,中心化输入: | ||
| 71 | - | ||
| 72 | -$$ | ||
| 73 | -x'_i = x_i - \mu \quad \forall i \in \{1, 2, \dots, H\} | ||
| 74 | -$$ | ||
| 75 | - | ||
| 76 | -##### **步骤6:计算总和的平方** | ||
| 77 | - | ||
| 78 | -计算全局总和的平方: | ||
| 79 | - | ||
| 80 | -$$ | ||
| 81 | -e_x'^2 = \left( e_x^{\text{global}} \right)^2 | ||
| 82 | -$$ | ||
| 83 | - | ||
| 84 | -##### **步骤7:计算归一化因子** | ||
| 85 | - | ||
| 86 | -计算归一化因子 $\gamma$,用于标准化输入数据。公式如下: | ||
| 87 | - | ||
| 88 | -$$ | ||
| 89 | -\gamma = \frac{1}{\sqrt{ \left( \frac{s_x^{\text{global}}}{H} \right) - e_x'^2 + \epsilon }} | ||
| 90 | -$$ | ||
| 91 | - | ||
| 92 | -这里: | ||
| 93 | - | ||
| 94 | -- $\frac{s_x^{\text{global}}}{H}$ 是全局平方和的平均值。 | ||
| 95 | -- $e_x'^2$ 是全局总和的平方。 | ||
| 96 | -- $\epsilon$ 是一个小常数,防止分母为零,增加数值稳定性。 | ||
| 97 | - | ||
| 98 | -##### **步骤8:标准化输入数据** | ||
| 99 | - | ||
| 100 | -将中心化后的输入数据 $\mathbf{x}'$ 与归一化因子 $\gamma$ 相乘,得到标准化后的数据 $\mathbf{\hat{x}}$: | ||
| 101 | - | ||
| 102 | -$$ | ||
| 103 | -\hat{x}_i = x'_i \cdot \gamma \quad \forall i \in \{1, 2, \dots, H\} | ||
| 104 | -$$ | ||
| 105 | - | ||
| 106 | -##### **步骤9:应用权重和偏置** | ||
| 107 | - | ||
| 108 | -最后,将标准化后的数据与权重向量 $\mathbf{W}$ 相乘,并根据是否存在偏置向量 $\mathbf{b}$ 来决定最终输出。 | ||
| 109 | - | ||
| 110 | -- **如果存在偏置**: | ||
| 111 | - | ||
| 112 | -$$ | ||
| 113 | -\text{output}_i = b_i + W_i \cdot \hat{x}_i \quad \forall i \in \{1, 2, \dots, H\} | ||
| 114 | -$$ | ||
| 115 | - | ||
| 116 | -- **如果不存在偏置**: | ||
| 117 | - | ||
| 118 | -$$ | ||
| 119 | -\text{output}_i = W_i \cdot \hat{x}_i \quad \forall i \in \{1, 2, \dots, H\} | ||
| 120 | -$$ | ||
| 121 | - | ||
| 122 | -## 使用场景 | ||
| 123 | - | ||
| 124 | -**后端限制:** CP>1 必须设置 `--transformer-impl transformer_engine`。 | ||
| 125 | - | ||
| 126 | -当TP通信域需要设置较大时,通信效率较低,需要通过分解通信域来提升其通信效率。 | ||
| 127 | - | ||
| 128 | -## 使用方法 | ||
| 129 | - | ||
| 130 | -在训练脚本的参数列表中加入 `--tp-2d`,开启2D张量并行,`--tp-x N1`和`--tp-y N2`分别设置其x轴、y轴的切分大小,其中需满足`tp = N1 * N2`(N1 > 1, N2 > 1)。 | ||
| 131 | - | ||
| 132 | -其他优化参数,用于辅助高维张量并行特性进行通信隐藏,需要开启tp-2d时生效: | ||
| 133 | - | ||
| 134 | -- `--enable-overlap-ag-with-matmul`: 在linear层forward计算时,开启all-gather通信和matmul进行隐藏,以便加速 | ||
| 135 | -- `--enable-overlap-matmul-with-rs`: 在linear层forward计算时,开启matmul计算和reduce-scatter通信进行隐藏,以便加速 | ||
| 136 | -- `--coc-fused-kernel`: 在linear层forward计算时,开启计算通信融合算子,将matmul计算与all-gather、reduce-scatter都进行算子级融合,实现进一步加速(依赖ATB加速库) | ||
| 137 | -- `--enable-backward-overlap-ag-with-matmul`: 在linear层backward计算梯度时,开启all-gather通信和matmul进行隐藏,以便加速(该特性依赖ATB加速库) | ||
| 138 | - | ||
| 139 | -上述3个forward计算优化参数`--enable-overlap-ag-with-matmul`、`--enable-overlap-matmul-with-rs`、`--coc-fused-kernel`只能同时开启1个。 | ||
| 140 | - | ||
| 141 | -注意事项: | ||
| 142 | -当前高维张量并行特性不与`--sequence-parallel`、MoE等特性相兼容,请根据实际情况调整配置。 | ||
| 143 | - | ||
| 144 | -## 使用效果 | ||
| 145 | - | ||
| 146 | -在llama3-405B模型训练时,tp=16情况下,开启2D张量并行,tp_x=8,tp_y=2,相比原Megatron 1D张量并行性能提升5%+。 | ||
| 147 | -开启coc-fused-kernel和enable-backward-overlap-ag-with-matmul通信计算融合优化后,进一步提升性能5%+。 | ||
| 148 | -其他场景下,由于计算效率和通信组的划分差异,需根据tp_x和tp_y实际调优情况进行配置,部分配置不能保证效率提升。 | ||
| @@ -11,13 +11,13 @@ | |||
| 11 | 11 | ||
| 12 | * 参数矩阵横切 | 12 | * 参数矩阵横切 |
| 13 | 依据参数矩阵的行方向进行模型切分,此策略要求输入矩阵亦按列进行相应切分。 | 13 | 依据参数矩阵的行方向进行模型切分,此策略要求输入矩阵亦按列进行相应切分。 |
| 14 | - + 横切策略前向时,首先对输入矩阵进行切分,各切分后的输入矩阵进入相应的模型部分进行计算,随后利用All-Reduce操作汇总各部分的计算结果,得到最终的前向计算输出。 | 14 | + + 横切策略前向时,首先对输入矩阵进行切分,各切分后的输入矩阵进入相应的模型部分进行计算,随后利用AllReduce操作汇总各部分的计算结果,得到最终的前向计算输出。 |
| 15 | - + 横切策略反向时,将最终输出的梯度等比例分配给各部分模型的输出梯度,再通过All-Gather操作将各切分输入矩阵的梯度合并,以恢复初始输入矩阵的梯度。 | 15 | + + 横切策略反向时,将最终输出的梯度等比例分配给各部分模型的输出梯度,再通过AllGather操作将各切分输入矩阵的梯度合并,以恢复初始输入矩阵的梯度。 |
| 16 | * 参数矩阵纵切 | 16 | * 参数矩阵纵切 |
| 17 | 依据参数矩阵的列方向进行模型切分,此时输入矩阵无需切分。 | 17 | 依据参数矩阵的列方向进行模型切分,此时输入矩阵无需切分。 |
| 18 | 18 | ||
| 19 | - + 纵切策略前向时,将完整的输入矩阵送入各部分模型,各模型独立完成计算后,通过All-Gather操作拼接各部分的输出结果,形成最终的前向计算输出。 | 19 | + + 纵切策略前向时,将完整的输入矩阵送入各部分模型,各模型独立完成计算后,通过AllGather操作拼接各部分的输出结果,形成最终的前向计算输出。 |
| 20 | - + 纵切策略反向时,先将最终输出的梯度按比例切分并传递给各部分模型的输出梯度,随后通过All-Reduce操作汇总各部分模型输入矩阵的梯度,以求得初始输入矩阵的梯度。 | 20 | + + 纵切策略反向时,先将最终输出的梯度按比例切分并传递给各部分模型的输出梯度,随后通过AllReduce操作汇总各部分模型输入矩阵的梯度,以求得初始输入矩阵的梯度。 |
| 21 | 21 | ||
| 22 | ### 图1 张量并行示意图 | 22 | ### 图1 张量并行示意图 |
| 23 | 23 | ||
| @@ -49,14 +49,14 @@ TransformerEngineNPU 提供昇腾 NPU 上的 TE 接口,MindSpeed 提供 HiF8 / | |||
| 49 | 49 | ||
| 50 | 安装配套 TransformerEngineNPU 和 MegatronAdaptor 后,使用 `--transformer-impl transformer_engine`(默认值)启用 TE。 | 50 | 安装配套 TransformerEngineNPU 和 MegatronAdaptor 后,使用 `--transformer-impl transformer_engine`(默认值)启用 TE。 |
| 51 | 设置`--fp8-format e4m3`,选择低精度数据格式,目前支持`e4m3`、`hybrid`和`hif8`,开启`hybrid`时,前向训练采用E4M3数据格式,反向传播采用E5M2数据格式。 | 51 | 设置`--fp8-format e4m3`,选择低精度数据格式,目前支持`e4m3`、`hybrid`和`hif8`,开启`hybrid`时,前向训练采用E4M3数据格式,反向传播采用E5M2数据格式。 |
| 52 | -设置`--fp8-recipe delayed` 选择低精度训练scaling策略,目前支持`tensorwise`、`delayed`、`hif8_delayed`、`mxfp8`和`blockwise`,默认值为`delayed`。 | 52 | +设置`--fp8-recipe delayed` 选择低精度训练scaling策略,目前支持`tensorwise`、`delayed`、`mxfp8`和`blockwise`,默认值为`delayed`。 |
| 53 | 53 | ||
| 54 | **注意** | 54 | **注意** |
| 55 | 55 | ||
| 56 | - `--use-ascend-mc2` 替换模型中的原生线性层,不覆盖 TENPU TE Linear,详见 [MC2](mc2.md)。Grouped GEMM 的配置见 [MoE GMM](megatron_moe/megatron-moe-gmm.md)。 | 56 | - `--use-ascend-mc2` 替换模型中的原生线性层,不覆盖 TENPU TE Linear,详见 [MC2](mc2.md)。Grouped GEMM 的配置见 [MoE GMM](megatron_moe/megatron-moe-gmm.md)。 |
| 57 | -- 低精度 GMM 当前仅使用 tensorwise、mxfp8、delayed recipe;其他 recipe(含 blockwise、hif8_delayed)回退 BF16 GMM,如不需要启用,可使能参数`--no-use-gmm-fp8` | 57 | +- 低精度 GMM 当前仅使用 tensorwise、mxfp8、delayed recipe(`--fp8-format hif8 --fp8-recipe delayed` 同样走 FP8 GMM);其他 recipe(含 blockwise)回退 BF16 GMM,如不需要启用,可使能参数`--no-use-gmm-fp8` |
| 58 | - FP8 不支持 `--transformer-impl local`。 | 58 | - FP8 不支持 `--transformer-impl local`。 |
| 59 | -- HiF8 数据格式支持 `--fp8-recipe tensorwise`、`delayed` 或 `hif8_delayed`;`hif8_delayed` 必须搭配 `--fp8-format hif8`,默认启用 step recovery,使用 `--no-hif8-step-recovery` 关闭,详见 [HiF8 DTS](hif8_dts.md)。 | 59 | +- HiF8 数据格式通过 `--fp8-format hif8` 选择:使用 `--fp8-recipe delayed`(按 delayed 调度,单个外层量化上下文);`tensorwise` 为逐张量 current scaling。HiF8 默认启用 step recovery,使用 `--no-hif8-step-recovery` 关闭,详见 [HiF8 DTS](hif8_dts.md)。 |
| 60 | - MXFP4 使用 `--fp4-format e2m1 --fp4-recipe mxfp4`。 | 60 | - MXFP4 使用 `--fp4-format e2m1 --fp4-recipe mxfp4`。 |
| 61 | - `--fp8-reuse-quantized-weight` 仅在启用 FP8 时有效。 | 61 | - `--fp8-reuse-quantized-weight` 仅在启用 FP8 时有效。 |
| 62 | - FP8 通算融合仅支持 MXFP8 recipe 配合 MC2。 | 62 | - FP8 通算融合仅支持 MXFP8 recipe 配合 MC2。 |
| @@ -75,7 +75,7 @@ TransformerEngineNPU 提供昇腾 NPU 上的 TE 接口,MindSpeed 提供 HiF8 / | |||
| 75 | <td rowspan="5"> 低精度训练</td> | 75 | <td rowspan="5"> 低精度训练</td> |
| 76 | <td rowspan="5">--transformer-impl transformer_engine | 76 | <td rowspan="5">--transformer-impl transformer_engine |
| 77 | <br> --fp8-format e4m3/hybrid/hif8 | 77 | <br> --fp8-format e4m3/hybrid/hif8 |
| 78 | - <br> --fp8-recipe tensorwise/delayed/hif8_delayed/mxfp8/blockwise </td> | 78 | + <br> --fp8-recipe tensorwise/delayed/mxfp8/blockwise </td> |
| 79 | <td style="text-align: center; vertical-align: middle">✅</td> | 79 | <td style="text-align: center; vertical-align: middle">✅</td> |
| 80 | </tr> | 80 | </tr> |
| 81 | </tbody> | 81 | </tbody> |
| @@ -1,40 +0,0 @@ | |||
| 1 | -# unaligned linear 非对齐线性层 | ||
| 2 | - | ||
| 3 | -## 背景与挑战 | ||
| 4 | - | ||
| 5 | -类Megatron-LM框架已成为大模型训练的主流方案之一,TP(张量并行 Tensor Parallelism)是大模型训练的基本并行范式,该范式在部分场景仍存在不足,例如要求大模型的注意力头数、序列长度要能整除TP,不满足条件将在参数校验中抛出异常;本特性提供了一种注意力头数、序列长度不能整除TP的解决方案; | ||
| 6 | - | ||
| 7 | -## 解决方案 | ||
| 8 | - | ||
| 9 | -- **序列长度不能整除TP**:和pad方案(将序列长度pad到TP的整数倍)不同,该方案通过序列分配策略来解决,小于 **(seq_len%tp_size)** 的tp卡分配 **(seq_len//tp_size+1)** 序列长度,其他分配 **(seq_len//tp_size)** 序列长度,例如seq_len=1026,tp_size=4, tp0和tp1分配的序列长度为257,tp2和tp3分配的序列长度为256; | ||
| 10 | -- **注意力头数不能整除TP**:对于MHA结构模型,小于 **(num_attention_heads%tp_size)** 的tp卡分配 **(num_attention_heads//tp_size+1)** 个注意力头,其他卡分配 **(num_attention_heads//tp_size)** 注意力头,例如num_attention_heads=25,tp_size=4, tp0分配的注意力头为7个,tp1、tp2和tp3分配的注意力头均为6个;值得注意的是,模型的注意力相关权重TP切分和头数相关,假设hidden_size=3200, qkv_weight大小为(9600,3200), dense_weight大小为(3200,3200), tp0的qkv权重大小为(2688,3200),dense权重大小为(3200,896), tp1、tp2和tp3的qkv权重大小为(2304, 3200),dense权重大小为(3200,768); 注意,对于GQA结构模型,权重切分和注意力头切分按num_query_groups比例分配; | ||
| 11 | - | ||
| 12 | -## 使用场景 | ||
| 13 | - | ||
| 14 | -**后端限制:** 必须设置 `--transformer-impl local`,不支持 TENPU 的 TE Linear。 | ||
| 15 | - | ||
| 16 | -- 序列长度或注意力头数不能整除TP的场景可以使用该特性。 | ||
| 17 | - | ||
| 18 | -## 使用方法 | ||
| 19 | - | ||
| 20 | -在模型参数中添加 `--transformer-impl local --unaligned-linear`。 | ||
| 21 | - | ||
| 22 | -**注意事项:** | ||
| 23 | - | ||
| 24 | -- 非对齐的线性层会引起各TP的负载不均衡 | ||
| 25 | -- 该特性不支持CP特性(要求TP*CP能被注意力头数整除) | ||
| 26 | -- 特殊的模型结构需要特殊适配该特性,当前已适配MHA、GQA结构,暂不支持MOE、MLA等结构 | ||
| 27 | - | ||
| 28 | -**设置训练脚本参数** | ||
| 29 | - | ||
| 30 | -```shell | ||
| 31 | -# 开启非对齐线性层 | ||
| 32 | ---unaligned-linear \ | ||
| 33 | -``` | ||
| 34 | - | ||
| 35 | -## 使用效果 | ||
| 36 | - | ||
| 37 | -- **补充功能场景**:补充注意力头数、序列长度不能被TP整除的场景。 | ||
| 38 | -- **潜在性能影响**:各TP处理的注意力头数、序列长度不一致,负载不均衡,建议模型结构设计时考虑该情况。 | ||
| 39 | - | ||
| 40 | -综上所述,该特性是为了完善TP(张量并行)场景下的限制约束,特性本身会带来负载不均衡的性能影响,所以在模型设计和超参优化时注意这一影响。 | ||
| @@ -1,50 +0,0 @@ | |||
| 1 | -# PP支持动态形状 | ||
| 2 | - | ||
| 3 | -## 背景与挑战 | ||
| 4 | - | ||
| 5 | -在深度学习模型训练中,尤其是涉及多模态任务时,输入数据的序列长度往往不是固定的。对于采用流水线并行(Pipeline Parallelism, PP)策略的模型, | ||
| 6 | -处理不同长度的序列通常需要将所有序列调整为统一长度,通过填充或截断来实现。这种做法虽然简化了数据处理和模型设计,但会导致计算资源和内存的浪费,特别是在处理较短序列时,因为需要大量的填充。 | ||
| 7 | -**主要挑战:** | ||
| 8 | - | ||
| 9 | -- **内存效率低下**:可能存在大量填充导致内存利用率低。 | ||
| 10 | -- **计算效率低下**:对填充部分进行不必要的计算。 | ||
| 11 | - | ||
| 12 | -## 解决方案 | ||
| 13 | - | ||
| 14 | -为了应对上述挑战,我们引入了对动态形状的支持,允许每个微批次中的序列保持其原始长度。此功能通过在发送张量之前,提前通信张量的形状信息,在各个流水线阶段之间同步即将接收的数据形状,确保内存分配和预处理的准确性。 | ||
| 15 | - | ||
| 16 | -## 使用场景 | ||
| 17 | - | ||
| 18 | -- **多变长度文本处理**:如文档分类、机器翻译等任务,其中文本长度差异很大。 | ||
| 19 | -- **增强模型泛化能力**:让模型更好地适应各种长度的输入,从而提高其在实际应用中的表现。 | ||
| 20 | - | ||
| 21 | -## 使用方法 | ||
| 22 | - | ||
| 23 | -**注意事项:** | ||
| 24 | - | ||
| 25 | -- 当采用流水线并行策略且序列长度固定时,启用该特性将增加不必要的通信开销,因此不建议使用。 | ||
| 26 | -- 密切监控训练过程中的内存消耗,避免因序列长度变动引起的溢出问题。 | ||
| 27 | - | ||
| 28 | -**设置训练脚本参数** | ||
| 29 | - | ||
| 30 | -```shell | ||
| 31 | -# 开启流水线并行, PP >= 2 | ||
| 32 | ---pipeline-model-parallel-size ${PP} \ | ||
| 33 | -# 开启PP支持动态形状 | ||
| 34 | ---variable-seq-lengths | ||
| 35 | -``` | ||
| 36 | - | ||
| 37 | -限制条件: | ||
| 38 | - | ||
| 39 | -1. MoE 场景使用 `--moe-token-dispatcher-type alltoall`;`allgather` 不支持动态序列长度,`flex` 不支持。 | ||
| 40 | -2. CP>1 的 EOD Reset 需要开启本选项,即使未开启 PP;仅支持 `p2p/all_gather + causal`,并设置 `--micro-batch-size 1`,见 [EOD Reset](eod-reset.md)。 | ||
| 41 | -3. 仅支持 decoder 流水线。 | ||
| 42 | - | ||
| 43 | -## 使用效果 | ||
| 44 | - | ||
| 45 | -- **优化资源利用**:与传统方法中所有序列需填充至统一长度相比,本方案通过减少不必要的填充操作,有效节省内存空间,降低计算负载,提高整体性能。 | ||
| 46 | -- **提高灵活性**:该特性赋予模型更强的适应性,使其能够高效处理各种长度的输入数据,进而增强了模型的泛化能力。这对于需要处理变长输入的任务(如文本分类、机器翻译等)尤为重要。 | ||
| 47 | -- **更真实的数据表示**:保留了原始文本的真实长度,有助于模型更准确地捕捉文本特征。 | ||
| 48 | -- **潜在性能影响**:尽管有诸多优点,但在某些情况下(如开启流水线并行,并且原序列为等长或需被截断以保持一致长度时),启用该特性可能会增加复杂度并减慢训练速度。因此,在设计和部署时应综合考虑这些因素,确保系统整体性能最优化。 | ||
| 49 | - | ||
| 50 | -综上所述,PP支持动态形状是针对特定应用场景的一种有效优化手段,它能够在保证模型性能的同时,显著改善资源利用率和数据处理的灵活性。用户应根据实际情况权衡利弊,决定是否启用这一特性。 | ||
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | ## 背景与挑战 | 3 | ## 背景与挑战 |
| 4 | 4 | ||
| 5 | -[Megatron流水线并行](./pipeline-parallel.md)策略虽能有效分割模型,但在运行过程中仍存在较高的空泡率,计算资源利用率仍有提高空间。 | 5 | +[Megatron流水线并行](./pipeline-parallel.md)策略虽能有效分割模型,但在运行过程中仍存在较高的空泡比率,计算资源利用率仍有提高空间。 |
| 6 | 6 | ||
| 7 | ## 解决方案 | 7 | ## 解决方案 |
| 8 | 8 | ||
| @@ -14,7 +14,7 @@ | |||
| 14 | 14 | ||
| 15 |  | 15 |  |
| 16 | 16 | ||
| 17 | -[原文链接](https://people.eecs.berkeley.edu/~matei/papers/2021/sc_megatron_lm.pdf) | 17 | +[原文链接](https://dl.acm.org/doi/10.1145/3458817.3476209) |
| 18 | 18 | ||
| 19 | 例如,假设模型总层数为16,张量并行大小为1,流水线并行大小为4,虚拟流水线并行大小为2,则模型将被划分为4 * 2 = 8个阶段,每个阶段包含16 / 8 = 2个层。如下所示: | 19 | 例如,假设模型总层数为16,张量并行大小为1,流水线并行大小为4,虚拟流水线并行大小为2,则模型将被划分为4 * 2 = 8个阶段,每个阶段包含16 / 8 = 2个层。如下所示: |
| 20 | 20 | ||
| @@ -18,7 +18,7 @@ MindSpeed Core提供并行、内存、通信、计算优化及工具、特性与 | |||
| 18 | 18 | ||
| 19 | 图1 MindSpeed架构图 | 19 | 图1 MindSpeed架构图 |
| 20 | 20 | ||
| 21 | - | 21 | +<img src="./figures/01_architecture_mindspeed_core.png" width="60%"/> |
| 22 | 22 | ||
| 23 | ## 功能特性 | 23 | ## 功能特性 |
| 24 | 24 | ||
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | ## 注意事项 | 3 | ## 注意事项 |
| 4 | 4 | ||
| 5 | -Atlas A2 训练系列产品 / Atlas A3 训练系列产品支持此接口,而 Ascend 950 系列产品不支持此接口。 | 5 | +Atlas A2训练系列产品 / Atlas A3训练系列产品支持此接口,而Ascend 950PR&950DT系列产品不支持此接口。 |
| 6 | 6 | ||
| 7 | ## matmul_all_reduce接口 | 7 | ## matmul_all_reduce接口 |
| 8 | 8 | ||
| @@ -57,7 +57,7 @@ def initialize_model_parallel( | |||
| 57 | pipeline_model_parallel_split_rank=pipeline_model_parallel_split_rank, | 57 | pipeline_model_parallel_split_rank=pipeline_model_parallel_split_rank, |
| 58 | context_parallel_size=context_parallel_size, | 58 | context_parallel_size=context_parallel_size, |
| 59 | ) | 59 | ) |
| 60 | - | 60 | + |
| 61 | 61 | ||
| 62 | def test_coc_matmul_all_reduce(rank, world_size, master_ip, master_port): | 62 | def test_coc_matmul_all_reduce(rank, world_size, master_ip, master_port): |
| 63 | torch_npu.npu.set_device(rank) | 63 | torch_npu.npu.set_device(rank) |
| @@ -65,7 +65,7 @@ def test_coc_matmul_all_reduce(rank, world_size, master_ip, master_port): | |||
| 65 | dist.init_process_group(backend='hccl', rank=rank, world_size=world_size, init_method=init_method) | 65 | dist.init_process_group(backend='hccl', rank=rank, world_size=world_size, init_method=init_method) |
| 66 | initialize_model_parallel(world_size) | 66 | initialize_model_parallel(world_size) |
| 67 | from mindspeed.ops.lcal_functional import coc_ops | 67 | from mindspeed.ops.lcal_functional import coc_ops |
| 68 | - | 68 | + |
| 69 | m, k, n = 2048, 4096, 8192 | 69 | m, k, n = 2048, 4096, 8192 |
| 70 | dtype = torch.float16 | 70 | dtype = torch.float16 |
| 71 | input1 = torch.rand(m, k, dtype=dtype, device=torch.npu.current_device()) | 71 | input1 = torch.rand(m, k, dtype=dtype, device=torch.npu.current_device()) |
| @@ -1,5 +1,7 @@ | |||
| 1 | # 版本说明 | 1 | # 版本说明 |
| 2 | 2 | ||
| 3 | +## 关键特性 | ||
| 4 | + | ||
| 3 | ## 版本配套说明 | 5 | ## 版本配套说明 |
| 4 | 6 | ||
| 5 | ### 产品版本信息 | 7 | ### 产品版本信息 |
| @@ -12,7 +14,7 @@ | |||
| 12 | </tr> | 14 | </tr> |
| 13 | <tr> | 15 | <tr> |
| 14 | <th class="firstcol" valign="top" width="26.25%"><p>产品版本</p></th> | 16 | <th class="firstcol" valign="top" width="26.25%"><p>产品版本</p></th> |
| 15 | - <td class="cellrowborder" valign="top" width="73.75%"><p>26.1.0</p></td> | 17 | + <td class="cellrowborder" valign="top" width="73.75%"><p>26.2.0</p></td> |
| 16 | </tr> | 18 | </tr> |
| 17 | <tr> | 19 | <tr> |
| 18 | <th class="firstcol" valign="top" width="26.25%"><p>版本类型</p></th> | 20 | <th class="firstcol" valign="top" width="26.25%"><p>版本类型</p></th> |
| @@ -24,7 +26,7 @@ | |||
| 24 | </tr> | 26 | </tr> |
| 25 | <tr> | 27 | <tr> |
| 26 | <th class="firstcol" valign="top" width="26.25%"><p>发布时间</p></th> | 28 | <th class="firstcol" valign="top" width="26.25%"><p>发布时间</p></th> |
| 27 | - <td class="cellrowborder" valign="top" width="73.75%"><p>2026年7月</p></td> | 29 | + <td class="cellrowborder" valign="top" width="73.75%"><p>2026年9月</p></td> |
| 28 | </tr> | 30 | </tr> |
| 29 | <tr> | 31 | <tr> |
| 30 | <th class="firstcol" valign="top" width="26.25%"><p>维护周期</p></th> | 32 | <th class="firstcol" valign="top" width="26.25%"><p>维护周期</p></th> |
| @@ -35,21 +37,24 @@ | |||
| 35 | 37 | ||
| 36 | > [!NOTE] | 38 | > [!NOTE] |
| 37 | > | 39 | > |
| 38 | -> 有关MindSpeed的版本维护,具体请参见[分支维护策略](https://gitcode.com/Ascend/MindSpeed/tree/26.1.0_core_r0.12.1#%E5%88%86%E6%94%AF%E7%BB%B4%E6%8A%A4%E7%AD%96%E7%95%A5)。 | 40 | +> 有关MindSpeed的版本维护,具体请参见[分支维护策略](https://gitcode.com/Ascend/MindSpeed/tree/core_r0.18.0#%E5%88%86%E6%94%AF%E7%BB%B4%E6%8A%A4%E7%AD%96%E7%95%A5)。 |
| 39 | 41 | ||
| 40 | ### 相关产品版本配套说明 | 42 | ### 相关产品版本配套说明 |
| 41 | 43 | ||
| 42 | **表 1** MindSpeed Core软件版本配套表 | 44 | **表 1** MindSpeed Core软件版本配套表 |
| 43 | 45 | ||
| 44 | -|MindSpeed Core代码分支名称|CANN版本|TorchNPU版本|Python版本|PyTorch版本| | 46 | +|MindSpeed Core代码分支名称|CANN版本|TorchNPU版本|Python版本|PyTorch版本|MegatronAdaptor|TransformerEngineNPU|Triton-Ascend版本| |
| 45 | -|--|--|--|--|--| | 47 | +|--|--|--|--|--|--|--|--| |
| 46 | -|master(在研版本)|在研版本|在研版本|Python3.12|2.10.0| | 48 | +|core_r0.18.0(在研版本)|在研版本|在研版本|Python3.12|2.10.0|在研版本|在研版本|3.2.2| |
| 47 | -|26.1.0_core_r0.12.1|9.1.0|26.1.0|Python3.10|2.7.1| | 49 | +|26.2.0_core_r0.18.0|9.2.0|26.2.0|Python3.12|2.10.0|26.2.0_core_r0.18.0|26.2.0_release_v2.17|3.2.2| |
| 48 | -|26.0.0_core_r0.12.1|9.0.0|26.0.0|Python3.10|2.7.1| | 50 | +|26.1.0_core_r0.12.1|9.1.0|26.1.0|Python3.10|2.7.1|/|/|/| |
| 51 | +|26.0.0_core_r0.12.1|9.0.0|26.0.0|Python3.10|2.7.1|/|/|/| | ||
| 49 | 52 | ||
| 50 | >[!NOTE] | 53 | >[!NOTE] |
| 51 | > | 54 | > |
| 52 | ->用户可根据需要选择MindSpeed代码分支下载源码并进行安装。 | 55 | +>- 用户可根据需要选择MindSpeed代码分支下载源码并进行安装。 |
| 56 | +> | ||
| 57 | +>- Triton-Ascend版本与CANN版本强绑定,Triton-Ascend的使用应该与CANN版本一一对应,详见[Triton-Ascend兼容性](https://triton-ascend.readthedocs.io/zh-cn/latest/release_note.html#id13)。 | ||
| 53 | 58 | ||
| 54 | ## 版本兼容性说明 | 59 | ## 版本兼容性说明 |
| 55 | 60 | ||
| @@ -66,17 +71,19 @@ | |||
| 66 | <col style="width: 150px"> | 71 | <col style="width: 150px"> |
| 67 | <col style="width: 150px"> | 72 | <col style="width: 150px"> |
| 68 | <col style="width: 150px"> | 73 | <col style="width: 150px"> |
| 74 | + <col style="width: 150px"> | ||
| 69 | </colgroup> | 75 | </colgroup> |
| 70 | <thead> | 76 | <thead> |
| 71 | <tr> | 77 | <tr> |
| 72 | <th rowspan="2">MindSpeed Core</th> | 78 | <th rowspan="2">MindSpeed Core</th> |
| 73 | - <th colspan="4">TorchNPU版本</th> | 79 | + <th colspan="5">TorchNPU版本</th> |
| 74 | </tr> | 80 | </tr> |
| 75 | <tr> | 81 | <tr> |
| 76 | <th>7.2.0</th> | 82 | <th>7.2.0</th> |
| 77 | <th>7.3.0</th> | 83 | <th>7.3.0</th> |
| 78 | <th>26.0.0</th> | 84 | <th>26.0.0</th> |
| 79 | - <th>26.1.0</th> | 85 | + <th>26.1.X</th> |
| 86 | + <th>26.2.X</th> | ||
| 80 | </tr> | 87 | </tr> |
| 81 | </thead> | 88 | </thead> |
| 82 | <tbody> | 89 | <tbody> |
| @@ -85,7 +92,8 @@ | |||
| 85 | <td>Y</td> | 92 | <td>Y</td> |
| 86 | <td>Y</td> | 93 | <td>Y</td> |
| 87 | <td>Y</td> | 94 | <td>Y</td> |
| 88 | - <td>/</td> | 95 | + <td>Y</td> |
| 96 | + <td>Y</td> | ||
| 89 | </tr> | 97 | </tr> |
| 90 | <tr> | 98 | <tr> |
| 91 | <td>26.1.0_core_r0.12.1</td> | 99 | <td>26.1.0_core_r0.12.1</td> |
| @@ -93,6 +101,15 @@ | |||
| 93 | <td>Y</td> | 101 | <td>Y</td> |
| 94 | <td>Y</td> | 102 | <td>Y</td> |
| 95 | <td>Y</td> | 103 | <td>Y</td> |
| 104 | + <td>Y</td> | ||
| 105 | + </tr> | ||
| 106 | + <tr> | ||
| 107 | + <td>26.2.0_core_r0.18.0</td> | ||
| 108 | + <td>Y</td> | ||
| 109 | + <td>Y</td> | ||
| 110 | + <td>Y</td> | ||
| 111 | + <td>Y</td> | ||
| 112 | + <td>Y</td> | ||
| 96 | </tr> | 113 | </tr> |
| 97 | </tbody> | 114 | </tbody> |
| 98 | </table> | 115 | </table> |
| @@ -106,17 +123,19 @@ | |||
| 106 | <col style="width: 150px"> | 123 | <col style="width: 150px"> |
| 107 | <col style="width: 150px"> | 124 | <col style="width: 150px"> |
| 108 | <col style="width: 150px"> | 125 | <col style="width: 150px"> |
| 126 | + <col style="width: 150px"> | ||
| 109 | </colgroup> | 127 | </colgroup> |
| 110 | <thead> | 128 | <thead> |
| 111 | <tr> | 129 | <tr> |
| 112 | <th rowspan="2">MindSpeed Core</th> | 130 | <th rowspan="2">MindSpeed Core</th> |
| 113 | - <th colspan="4">CANN版本</th> | 131 | + <th colspan="5">CANN版本</th> |
| 114 | </tr> | 132 | </tr> |
| 115 | <tr> | 133 | <tr> |
| 116 | <th>8.3.RCX</th> | 134 | <th>8.3.RCX</th> |
| 117 | <th>8.5.X</th> | 135 | <th>8.5.X</th> |
| 118 | <th>9.0.X</th> | 136 | <th>9.0.X</th> |
| 119 | <th>9.1.X</th> | 137 | <th>9.1.X</th> |
| 138 | + <th>9.2.X</th> | ||
| 120 | </tr> | 139 | </tr> |
| 121 | </thead> | 140 | </thead> |
| 122 | <tbody> | 141 | <tbody> |
| @@ -125,15 +144,26 @@ | |||
| 125 | <td>Y</td> | 144 | <td>Y</td> |
| 126 | <td>Y</td> | 145 | <td>Y</td> |
| 127 | <td>Y</td> | 146 | <td>Y</td> |
| 128 | - <td>/</td> | 147 | + <td>Y</td> |
| 148 | + <td>Y</td> | ||
| 129 | </tr> | 149 | </tr> |
| 130 | - <tr> | 150 | + <tr> |
| 131 | <td>26.1.0_core_r0.12.1</td> | 151 | <td>26.1.0_core_r0.12.1</td> |
| 132 | <td>Y</td> | 152 | <td>Y</td> |
| 133 | <td>Y</td> | 153 | <td>Y</td> |
| 134 | <td>Y</td> | 154 | <td>Y</td> |
| 135 | <td>Y</td> | 155 | <td>Y</td> |
| 156 | + <td>Y</td> | ||
| 136 | </tr> | 157 | </tr> |
| 158 | + <tr> | ||
| 159 | + <td>26.2.0_core_r0.18.0</td> | ||
| 160 | + <td>Y</td> | ||
| 161 | + <td>Y</td> | ||
| 162 | + <td>Y</td> | ||
| 163 | + <td>Y</td> | ||
| 164 | + <td>Y</td> | ||
| 165 | + </tr> | ||
| 166 | + | ||
| 137 | </tbody> | 167 | </tbody> |
| 138 | </table> | 168 | </table> |
| 139 | 169 | ||
| @@ -145,16 +175,23 @@ | |||
| 145 | 175 | ||
| 146 | ### 新增特性 | 176 | ### 新增特性 |
| 147 | 177 | ||
| 148 | -- 新增FP8/MXFP8/HiFloat8低精格式训练支持,以及w8a16量化支持。 | 178 | +- 适配Megatron-LM core_r0.18.0版本 |
| 149 | -- 新增MXFP8-32x32量化及FSDP支持,量化后释放bf16权重优化内存。 | 179 | +- 解耦MindSpeed、MegatronAdaptor和TransformerEngineNPU |
| 150 | -- 新增SwapMuon及mcore muon特性,支持checkpoint保存与加载。 | 180 | +- 新增get_batch 配置缓存特性 |
| 151 | -- 新增DeepSeek V4模型适配及自定义PP布局支持。 | ||
| 152 | -- 新增TE算子层Hamilton attention实现。 | ||
| 153 | 181 | ||
| 154 | ### 删除特性 | 182 | ### 删除特性 |
| 155 | 183 | ||
| 156 | -- 删除SFA/SFAG/SLI临时版本算子适配,相关功能通过正式算子承载。 | 184 | +- 删除特性Ascend Double Ring Attention长序列并行 |
| 157 | -- 删除mindspeed/lite模块,Triton算子迁移至mindspeed/ops/triton目录。 | 185 | +- 删除特性Ascend混合长序列并行 |
| 186 | +- 删除特性Ascend重计算流水线独立调度 | ||
| 187 | +- 删除特性Ascend高维张量并行 | ||
| 188 | +- 删除特性Ascend Megatron MoE TP拓展EP | ||
| 189 | +- 删除特性专家并行动态负载均衡(数参互寻) | ||
| 190 | +- 删除特性Ascend PP支持动态形状 | ||
| 191 | +- 删除特性Ascend PP支持多参数传递 | ||
| 192 | +- 删除特性Ascend PP支持多参数传递和动态形状 | ||
| 193 | +- 删除特性Ascend非对齐线性层 | ||
| 194 | +- 删除特性Ascend非对齐Ulysses长序列并行 | ||
| 158 | 195 | ||
| 159 | ### 接口变更说明 | 196 | ### 接口变更说明 |
| 160 | 197 | ||
| @@ -162,10 +199,7 @@ | |||
| 162 | 199 | ||
| 163 | ### 已解决问题 | 200 | ### 已解决问题 |
| 164 | 201 | ||
| 165 | -- 修复TE分支LayerNormLinear初始化权重顺序与NVTE不一致问题,以及LayerNorm偏置未初始化为零的问题。 | 202 | +- 修复get_batch阶段重复解析config导致性能下降的问题 |
| 166 | -- 修复GMM算子、NPU sparse_attn_sharedkv算子异常,以及l2norm批量一致性和recompute_w_u_fwd的NaN错误。 | ||
| 167 | -- 修复fboverlap场景下异常内存占用问题,以及Triton算子chunk_bwd_dqkwg时间退化问题。 | ||
| 168 | -- 修复VeRL场景下HCCL缓冲区错误。 | ||
| 169 | 203 | ||
| 170 | ### 遗留问题 | 204 | ### 遗留问题 |
| 171 | 205 | ||
| @@ -198,6 +232,18 @@ | |||
| 198 | 232 | ||
| 199 | ### 病毒扫描结果 | 233 | ### 病毒扫描结果 |
| 200 | 234 | ||
| 235 | +|防病毒软件名称|防病毒软件版本|病毒库版本|扫描时间|扫描结果| | ||
| 236 | +|---|---|---|---|---| | ||
| 237 | +|QiAnXin|8.0.5.5260|2026-09-27 08:00:00.0|2026-09-28|无病毒,无恶意| | ||
| 238 | +|Kaspersky|12.0.0.6672|2026-09-28 10:09:00|2026-09-28|无病毒,无恶意| | ||
| 239 | +|Bitdefender|7.5.1.200224|7.101487|2026-09-28|无病毒,无恶意| | ||
| 240 | + | ||
| 201 | ### 漏洞修补列表 | 241 | ### 漏洞修补列表 |
| 202 | 242 | ||
| 203 | 无 | 243 | 无 |
| 244 | + | ||
| 245 | +## 修订记录 | ||
| 246 | + | ||
| 247 | +|文档版本|发布日期|修改说明| | ||
| 248 | +|--|--|--| | ||
| 249 | +|01|2026-10-15|第一次正式发布| | ||
| @@ -8,4 +8,9 @@ | |||
| 8 | |:---|:---| | 8 | |:---|:---| |
| 9 | |MindSpeed LLM|请参见《[安全声明](https://gitcode.com/Ascend/MindSpeed-LLM/blob/master/docs/zh/SECURITYNOTE.md)》| | 9 | |MindSpeed LLM|请参见《[安全声明](https://gitcode.com/Ascend/MindSpeed-LLM/blob/master/docs/zh/SECURITYNOTE.md)》| |
| 10 | |MindSpeed MM|请参考《[安全声明](https://gitcode.com/Ascend/MindSpeed-MM/blob/master/SECURITYNOTE.md)》| | 10 | |MindSpeed MM|请参考《[安全声明](https://gitcode.com/Ascend/MindSpeed-MM/blob/master/SECURITYNOTE.md)》| |
| 11 | +|MindSpeed Bridge|请参考《[安全声明](https://gitcode.com/Ascend/MindSpeed-Bridge/blob/master/docs/zh/SECURITYNOTE.md)》| | ||
| 12 | +|TransformerEngineNPU|请参考《[安全声明](https://gitcode.com/Ascend/TransformerEngineNPU/blob/main/docs/zh/SECURITYNOTE.md)》| | ||
| 13 | +|MegatronAdaptor|请参考《[安全声明](https://gitcode.com/Ascend/MegatronAdaptor/blob/core_r0.18.0/docs/zh/SECURITYNOTE.md)》| | ||
| 14 | +|FSDPTurbo|请参考《[安全声明](https://gitcode.com/Ascend/FSDPTurbo/blob/main/docs/zh/SECURITYNOTE.md)》| | ||
| 11 | |MindSpeed Core|请参考《[安全声明](SECURITYNOTE.md)》| | 15 | |MindSpeed Core|请参考《[安全声明](SECURITYNOTE.md)》| |
| 16 | +|MindSpeed Ops|请参考《[安全声明](https://gitcode.com/Ascend/MindSpeed-Ops/blob/master/docs/zh/SECURITYNOTE.md)》| | ||
| @@ -83,6 +83,7 @@ MindSpeed Core采用**插件化**的特性管理架构,核心组件: | |||
| 83 | - 参数校验完整性:充分利用`pre_validate_args`、`validate_args`、`post_validate_args`三个阶段确保参数合法性。 | 83 | - 参数校验完整性:充分利用`pre_validate_args`、`validate_args`、`post_validate_args`三个阶段确保参数合法性。 |
| 84 | - 兼容性检查:使用`incompatible_check`和`dependency_check`确保特性组合的正确性。 | 84 | - 兼容性检查:使用`incompatible_check`和`dependency_check`确保特性组合的正确性。 |
| 85 | - patch幂等性:确保patch注册不会相互冲突,必要时使用`force_patch`参数。`MindSpeedFeaturesManager.remove_patches` 只移除 MindSpeed 自己的补丁层。 | 85 | - patch幂等性:确保patch注册不会相互冲突,必要时使用`force_patch`参数。`MindSpeedFeaturesManager.remove_patches` 只移除 MindSpeed 自己的补丁层。 |
| 86 | +- 完整替换`train_step`的约定:直接替换模式会把 MegatronAdaptor 已安装的 wrapper 链整体覆盖。如替换目标是`megatron.training.training.train_step`,必须在每个训练步正常返回前显式调用一次 MegatronAdaptor 的稳定接口 `profile_step()`(`from megatron_adaptor.patches.megatron.profile import profile_step`),否则 NPU Profiling 的采集窗口将不再推进。该调用在未开启 profiling 时零开销返回,可无条件调用。参考实现:`mindspeed.core.pipeline_parallel.dualpipev.dualpipev_chunks.train_step`、`mindspeed.core.data_parallel.async_log_allreduce.train_step`。 | ||
| 86 | - 参数获取:使用 `mindspeed.args_utils.get_full_args` 获取完整参数。 | 87 | - 参数获取:使用 `mindspeed.args_utils.get_full_args` 获取完整参数。 |
| 87 | 88 | ||
| 88 | ### 创建新特性的Checklist | 89 | ### 创建新特性的Checklist |
| @@ -8,14 +8,14 @@ | |||
| 8 | 8 | ||
| 9 | |产品|是否支持(训练场景)| | 9 | |产品|是否支持(训练场景)| |
| 10 | |--|:-:| | 10 | |--|:-:| |
| 11 | -|<term>Ascend 950 系列产品</term>|√| | 11 | +|<term>Ascend 950PR&950DT系列产品</term>|√| |
| 12 | -|<term>Atlas A3 训练系列产品</term>|√| | 12 | +|<term>Atlas A3训练系列产品</term>|√| |
| 13 | -|<term>Atlas A3 推理系列产品</term>|x| | 13 | +|<term>Atlas A3推理系列产品</term>|x| |
| 14 | -|<term>Atlas A2 训练系列产品</term>|√| | 14 | +|<term>Atlas A2训练系列产品</term>|√| |
| 15 | -|<term>Atlas A2 推理系列产品</term>|x| | 15 | +|<term>Atlas A2推理系列产品</term>|x| |
| 16 | -|<term>Atlas 200I/500 A2 推理产品</term>|x| | 16 | +|<term>Atlas 200I/500 A2推理产品</term>|x| |
| 17 | -|<term>Atlas 推理系列产品</term>|x| | 17 | +|<term>Atlas推理系列产品</term>|x| |
| 18 | -|<term>Atlas 训练系列产品</term>|x| | 18 | +|<term>Atlas训练系列产品</term>|x| |
| 19 | 19 | ||
| 20 | > [!NOTE] | 20 | > [!NOTE] |
| 21 | > | 21 | > |
| @@ -42,28 +42,28 @@ | |||
| 42 | 42 | ||
| 43 | > [!NOTE] | 43 | > [!NOTE] |
| 44 | > | 44 | > |
| 45 | -> - 使用镜像前,请先确认机器型号。最新镜像支持aarch64及X86_64架构,可通过uname -a命令确认当前环境是否符合要求。 | 45 | +> - 使用镜像前,请先确认机器型号。最新镜像支持aarch64及X86_64架构,可通过`uname -a`命令确认当前环境是否符合要求。 |
| 46 | -> - 配套镜像已预装配套的CANN 9.1.0软件及TorchNPU 26.1.0插件,可根据需要选用。 | 46 | +> - 配套镜像已预装配套的CANN 9.2.0软件及TorchNPU 26.2.0插件,可根据需要选用。 |
| 47 | > - 若当前环境与提供的镜像不兼容,请选择[方式二:源码安装](#方式二源码安装)。 | 47 | > - 若当前环境与提供的镜像不兼容,请选择[方式二:源码安装](#方式二源码安装)。 |
| 48 | -> - master分支后续会更新新的镜像,如果需要自定义构建镜像请参见[镜像概述](../../../docker/OVERVIEW.zh.md)。 | 48 | +> - core_r0.18.0分支后续会更新新的镜像,如果需要自定义构建镜像请参见[镜像概述](../../../docker/OVERVIEW.zh.md)。 |
| 49 | 49 | ||
| 50 | 1. 获取镜像 | 50 | 1. 获取镜像 |
| 51 | 51 | ||
| 52 | - 最新镜像均配套[MindSpeed Core的26.1.0_core_r0.12.1分支](https://gitcode.com/Ascend/MindSpeed/tree/26.1.0_core_r0.12.1),请按需[获取镜像](https://www.hiascend.com/developer/ascendhub/detail/4ad248a439a44b4bb72e0534bfda8e2a)。 | 52 | + 最新镜像均配套[MindSpeed Core的26.2.0_core_r0.18.0分支](https://gitcode.com/Ascend/MindSpeed/tree/26.2.0_core_r0.18.0),该镜像即将上线,当前可使用MindSpeed Core 26.1.0_core_r0.12.1,请按需[获取镜像](https://www.hiascend.com/developer/ascendhub/detail/4ad248a439a44b4bb72e0534bfda8e2a)。 |
| 53 | <!-- npu="950" id5 --> | 53 | <!-- npu="950" id5 --> |
| 54 | - - <term>Ascend 950 系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-950-openeuler24.03-py3.12 | 54 | + - <term>Ascend 950PR&950DT系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-950-openeuler24.03-py3.12 |
| 55 | 55 | ||
| 56 | - - <term>Ascend 950 系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-950-ubuntu22.04-py3.12 | 56 | + - <term>Ascend 950PR&950DT系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-950-ubuntu22.04-py3.12 |
| 57 | <!-- end id5 --> | 57 | <!-- end id5 --> |
| 58 | <!-- npu="A3" id4 --> | 58 | <!-- npu="A3" id4 --> |
| 59 | - - <term>Atlas A3 训练系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-a3-openeuler24.03-py3.12 | 59 | + - <term>Atlas A3训练系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-a3-openeuler24.03-py3.12 |
| 60 | 60 | ||
| 61 | - - <term>Atlas A3 训练系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-a3-ubuntu22.04-py3.12 | 61 | + - <term>Atlas A3训练系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-a3-ubuntu22.04-py3.12 |
| 62 | <!-- end id4 --> | 62 | <!-- end id4 --> |
| 63 | <!-- npu="910b" id3 --> | 63 | <!-- npu="910b" id3 --> |
| 64 | - - <term>Atlas A2 训练系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-910b-openeuler24.03-py3.12 | 64 | + - <term>Atlas A2训练系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-910b-openeuler24.03-py3.12 |
| 65 | 65 | ||
| 66 | - - <term>Atlas A2 训练系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-910b-ubuntu22.04-py3.12 | 66 | + - <term>Atlas A2训练系列产品</term>:v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-910b-ubuntu22.04-py3.12 |
| 67 | <!-- end id3 --> | 67 | <!-- end id3 --> |
| 68 | 以镜像v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-a3-openeuler24.03-py3.12为例: | 68 | 以镜像v26.1.0_core_r0.12.1-cann9.1.0-torch_npu2.7.1.post8-a3-openeuler24.03-py3.12为例: |
| 69 | 69 | ||
| @@ -146,8 +146,11 @@ | |||
| 146 | 4. 安装TransformerEngineNPU(TENPU) | 146 | 4. 安装TransformerEngineNPU(TENPU) |
| 147 | 147 | ||
| 148 | ```shell | 148 | ```shell |
| 149 | - git clone --branch main https://gitcode.com/Ascend/TransformerEngineNPU.git | 149 | + git clone https://gitcode.com/Ascend/TransformerEngineNPU.git |
| 150 | - pip install -e TransformerEngineNPU --no-build-isolation | 150 | + cd TransformerEngineNPU |
| 151 | + git checkout main | ||
| 152 | + pip install -e . --no-build-isolation | ||
| 153 | + cd .. | ||
| 151 | ``` | 154 | ``` |
| 152 | 155 | ||
| 153 | > [!NOTE] | 156 | > [!NOTE] |
| @@ -166,16 +169,25 @@ | |||
| 166 | pip install -e MindSpeed | 169 | pip install -e MindSpeed |
| 167 | ``` | 170 | ``` |
| 168 | 171 | ||
| 169 | -6. 获取Megatron-LM源码并切换至0.18.0版本 | 172 | +6. 获取Megatron-LM源码并切换至0.18.2版本 |
| 170 | 173 | ||
| 171 | ```shell | 174 | ```shell |
| 172 | git clone https://github.com/NVIDIA/Megatron-LM.git | 175 | git clone https://github.com/NVIDIA/Megatron-LM.git |
| 173 | cd Megatron-LM | 176 | cd Megatron-LM |
| 174 | - git checkout core_v0.18.0 | 177 | + git checkout core_v0.18.2 |
| 175 | cd .. | 178 | cd .. |
| 176 | ``` | 179 | ``` |
| 177 | 180 | ||
| 178 | - Megatron-LM上游版本标签为`core_v0.18.0`,与MA配套分支`core_r0.18.0`的命名不同。安装后请参考[快速入门](quickstart.md)准备数据并启动训练。 | 181 | +7. 安装Triton-Ascend |
| 182 | + | ||
| 183 | + 安装配套版本的Triton-Ascend,请参考《[Triton-Ascend安装指南](https://triton-ascend.readthedocs.io/zh-cn/latest/installation_guide.html#piptriton-ascend)》,获取配套版本的Triton-Ascend安装指令。 | ||
| 184 | + | ||
| 185 | + 可参考如下安装命令: | ||
| 186 | + | ||
| 187 | + ```shell | ||
| 188 | + # 注意:triton-ascend 3.2.0 及以下 Triton-Ascend和Triton 不能同时存在。需要先卸载社区 Triton,再安装 Triton-Ascend。 | ||
| 189 | + pip install triton-ascend==3.2.2 --extra-index-url=https://mirrors.huaweicloud.com/ascend/repos/pypi | ||
| 190 | + ``` | ||
| 179 | 191 | ||
| 180 | ## 卸载MindSpeed | 192 | ## 卸载MindSpeed |
| 181 | 193 | ||
| @@ -15,11 +15,18 @@ | |||
| 15 | python -m pip install -e TransformerEngineNPU --no-build-isolation | 15 | python -m pip install -e TransformerEngineNPU --no-build-isolation |
| 16 | # 可选加速:在源码仓的同级目录安装当前版本MindSpeed | 16 | # 可选加速:在源码仓的同级目录安装当前版本MindSpeed |
| 17 | python -m pip install -e MindSpeed | 17 | python -m pip install -e MindSpeed |
| 18 | + | ||
| 19 | + # 默认参数训练需要MindSpeed-Ops提供权重梯度融合算子 | ||
| 20 | + git clone https://gitcode.com/Ascend/MindSpeed-Ops.git | ||
| 21 | + python -m pip install -e MindSpeed-Ops --extra-index-url=https://triton-ascend.osinfra.cn/pypi/simple --no-build-isolation --no-deps | ||
| 22 | + python -c "from mindspeed_ops.api.atb.npu_matmul_add import npu_matmul_add_fp32, npu_matmul_add_fp16; print('MindSpeed-Ops MatmulAdd API loaded successfully')" | ||
| 18 | ``` | 23 | ``` |
| 19 | 24 | ||
| 20 | > [!NOTE] | 25 | > [!NOTE] |
| 21 | > | 26 | > |
| 22 | > TENPU与原生TransformerEngine共用`transformer_engine`模块名,不能在同一环境中同时安装。若已安装原生TransformerEngine,请先执行`pip uninstall transformer_engine`,再安装TENPU。 | 27 | > TENPU与原生TransformerEngine共用`transformer_engine`模块名,不能在同一环境中同时安装。若已安装原生TransformerEngine,请先执行`pip uninstall transformer_engine`,再安装TENPU。 |
| 28 | + > | ||
| 29 | + > Megatron-LM默认开启`gradient_accumulation_fusion`,因此本手册的训练场景需要安装MindSpeed-Ops。纯推理,或训练时增加`--no-gradient-accumulation-fusion`关闭权重梯度融合时,可以不安装。详细场景和依赖说明请参见[软件安装](install_guide.md#方式二源码安装)。 | ||
| 23 | 30 | ||
| 24 | 3. 在Megatron-LM中导入MA适配器。 | 31 | 3. 在Megatron-LM中导入MA适配器。 |
| 25 | 32 | ||
| @@ -28,14 +35,13 @@ | |||
| 28 | ```Python | 35 | ```Python |
| 29 | import torch | 36 | import torch |
| 30 | import megatron_adaptor # NPU基础适配及增强特性 | 37 | import megatron_adaptor # NPU基础适配及增强特性 |
| 31 | - from functools import partial | 38 | + from gpt_builders import gpt_builder |
| 32 | - from contextlib import nullcontext | 39 | + from megatron.core import mpu |
| 33 | - import inspect | ||
| 34 | ``` | 40 | ``` |
| 35 | 41 | ||
| 36 | > [!NOTE] | 42 | > [!NOTE] |
| 37 | > | 43 | > |
| 38 | -> MindSpeed Core支持<term>Ascend 950 系列产品</term>、<term>Atlas A3 训练系列产品</term>和<term>Atlas A2 训练系列产品</term>,且要求单NPU的片上内存为64GB及以上 | 44 | +> MindSpeed Core支持<term>Ascend 950PR&950DT系列产品</term>、<term>Atlas A3训练系列产品</term>和<term>Atlas A2训练系列产品</term>,且要求单NPU的片上内存为64GB及以上 |
| 39 | > | 45 | > |
| 40 | > 当前示例脚本中`NPUS_PER_NODE=8`表示需要8个NPU,如果实际情况低于此配置,可能遇到OOM问题。 | 46 | > 当前示例脚本中`NPUS_PER_NODE=8`表示需要8个NPU,如果实际情况低于此配置,可能遇到OOM问题。 |
| 41 | 47 | ||
| @@ -0,0 +1,83 @@ | |||
| 1 | +# MindSpeed core_r0.18.0版本升级兼容性变更 | ||
| 2 | + | ||
| 3 | +## get_batch 重复构造配置导致 Host 开销增加 | ||
| 4 | + | ||
| 5 | +### 问题现象 | ||
| 6 | + | ||
| 7 | +升级到 Megatron-LM core_r0.18.0 后,如果训练性能分析显示 `get_batch` 在 Host 侧耗时较高,且 `core_transformer_config_from_args` 被反复调用,可以考虑开启 `cache-get-batch-config`。这类开销随 microbatch 的重复执行累积,可能影响训练吞吐。 | ||
| 8 | + | ||
| 9 | +### 问题根因 | ||
| 10 | + | ||
| 11 | +训练入口的 `get_batch` 会调用 `core_transformer_config_from_args(args)`,构造 `TransformerConfig`,用于判断流水线布局、MTP 层所在阶段等信息。即使模型配置没有变化,每次调用仍会重复构造和校验配置,增加 Host 侧开销;部分流水线中间阶段即使无需读取数据,也会先执行这一步。 | ||
| 12 | + | ||
| 13 | +### 解决方案 | ||
| 14 | + | ||
| 15 | +在已接入 MindSpeed 的训练启动参数中添加: | ||
| 16 | + | ||
| 17 | +```bash | ||
| 18 | +--cache-get-batch-config | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +`--cache-get-batch-config` 默认关闭,属于 optimization level 2 特性。当前 `--optimization-level` 默认值为 `2`;若脚本将其设置为 `0` 或 `1`,需要同时调整为 `2`。关闭配置缓存时,移除 `--cache-get-batch-config` 即可。 | ||
| 22 | + | ||
| 23 | +该特性的核心作用是复用 `get_batch` 所需的配置,减少重复构造开销。生效机制如下: | ||
| 24 | + | ||
| 25 | +1. MindSpeed 在 `pretrain` 入口根据传入的 `forward_step_func` 定位训练入口,并包装其中的 `core_transformer_config_from_args`。该入口需同时提供可调用的 `get_batch` 和 `core_transformer_config_from_args`。 | ||
| 26 | +2. 首次由该 `get_batch` 直接发起配置构造时,正常创建并缓存配置;后续相同缓存键的调用直接复用。缓存键包含 args 对象标识、配置类、MLA 开关和异构层配置路径。 | ||
| 27 | +3. 其他函数调用配置构造接口时仍执行原逻辑。缓存对象是 `TransformerConfig`,数据 batch 仍按原流程读取。 | ||
| 28 | + | ||
| 29 | +自定义训练入口若不满足上述条件,或通过其他辅助函数间接构造配置,则不会命中该缓存。使用时应保持相关配置稳定:原地修改同一个 args 对象中未纳入缓存键的字段,不会自动刷新已缓存的配置。 | ||
| 30 | + | ||
| 31 | +验证时保持其余训练参数一致,对比开启前后的 `get_batch` Host 耗时、稳态单步耗时和吞吐,并检查 loss 是否正常。若主要耗时来自数据读取或数据传输,应继续定位对应瓶颈。更多说明参见 [get_batch 配置缓存](features/cache-get-batch-config.md)。 | ||
| 32 | + | ||
| 33 | +## RoPE 融合默认开启,旧脚本需要显式使用 no-rope-fusion 关闭 | ||
| 34 | + | ||
| 35 | +### 问题现象 | ||
| 36 | + | ||
| 37 | +升级到 core_r0.18.0 适配版本后,即使训练脚本未添加旧参数 `--use-fused-rotary-pos-emb`,RoPE 仍可能走融合计算路径。仅删除旧的开启参数,已不能保证恢复未融合实现,迁移前后的性能或数值对比也可能因此使用不同的计算路径。 | ||
| 38 | + | ||
| 39 | +对于当前 MindSpeed 的 MLA YaRN 适配路径,未关闭融合时还可能遇到以下报错: | ||
| 40 | + | ||
| 41 | +```text | ||
| 42 | +AssertionError: MLA Yarn RoPE does not support RoPE fusion | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +### 问题根因 | ||
| 46 | + | ||
| 47 | +RoPE 融合的控制统一到 Megatron 的 `apply_rope_fusion` 字段,命令行采用“默认开启、显式关闭”的方式。`--no-rope-fusion` 将该字段设置为 `False`;旧参数 `--use-fused-rotary-pos-emb` 保留为兼容别名,将同一字段设置为 `True`,不再使用独立的旧字段控制融合。 | ||
| 48 | + | ||
| 49 | +因此,脚本没有传入旧的开启参数,不代表融合已关闭。融合是否适用还取决于模型路径:例如,当前 MindSpeed 的 MLA YaRN 适配实现要求 `apply_rope_fusion=False`。 | ||
| 50 | + | ||
| 51 | +### 解决方案 | ||
| 52 | + | ||
| 53 | +**保持默认融合行为:** 在已通过 `import mindspeed.megatron_adaptor` 接入 MindSpeed 的训练脚本中,使用 RoPE 位置编码即可,无需额外添加融合开启参数: | ||
| 54 | + | ||
| 55 | +```bash | ||
| 56 | +--position-embedding-type rope | ||
| 57 | +``` | ||
| 58 | + | ||
| 59 | +**关闭融合:** 若需保持旧脚本的未融合行为、进行融合开关对比,或使用上述要求关闭融合的 MLA YaRN 路径,在已有训练参数中添加: | ||
| 60 | + | ||
| 61 | +```bash | ||
| 62 | +--no-rope-fusion | ||
| 63 | +``` | ||
| 64 | + | ||
| 65 | +该参数关闭的是 RoPE 融合计算,模型仍使用原有的位置编码。恢复默认融合行为时,移除该参数即可。 | ||
| 66 | + | ||
| 67 | +旧脚本迁移时可按下表调整: | ||
| 68 | + | ||
| 69 | +| 原有意图 | 当前推荐配置 | | ||
| 70 | +| --- | --- | | ||
| 71 | +| 开启 RoPE 融合 | 保留 RoPE 位置编码配置,无需添加旧的开启参数 | | ||
| 72 | +| 不使用 RoPE 融合 | 显式添加 `--no-rope-fusion` | | ||
| 73 | +| 保留旧参数 `--use-fused-rotary-pos-emb` | 仍可兼容,但新脚本建议使用默认开启方式 | | ||
| 74 | + | ||
| 75 | +不要同时传入 `--use-fused-rotary-pos-emb` 和 `--no-rope-fusion`:两者写入同一个字段,解析结果受命令行先后顺序影响。 | ||
| 76 | + | ||
| 77 | +该变更的核心作用是统一融合开关,并提供明确的关闭方式。生效机制如下: | ||
| 78 | + | ||
| 79 | +1. MindSpeed 的 RoPE 适配属于 optimization level 0 基础补丁,在支持的 level 0/1/2 下均会注册。无需通过 `--optimization-level 2` 开启,也不能通过降低优化等级关闭融合。 | ||
| 80 | +2. 参数解析将开关写入 `args.apply_rope_fusion`,随后传入模型配置。Megatron 的 RoPE 分发逻辑据此选择融合或未融合路径;MindSpeed 的普通 RoPE 实现也读取该字段。关闭后,该实现使用旋转、乘法和加法组合计算。 | ||
| 81 | +3. 默认开启仍受适用条件约束:非 RoPE 位置编码会在 Megatron 参数校验时关闭融合;开启 `--reset-attention-mask` 的 EOD Reset 场景也会由 MindSpeed 校验关闭融合。 | ||
| 82 | + | ||
| 83 | +验证时查看最终参数中的 `apply_rope_fusion`,并确认模型配置与之保持一致。固定模型、精度和输入,对比默认配置与增加 `--no-rope-fusion` 后的 loss、梯度及稳态单步耗时,确认实际计算路径和性能变化。更多说明参见 [Rotary Position Embedding 融合优化](features/rotary-embedding.md)。 | ||
| @@ -21,6 +21,7 @@ import torch | |||
| 21 | import megatron.training.training as megatron_training | 21 | import megatron.training.training as megatron_training |
| 22 | 22 | ||
| 23 | from megatron.core import mpu | 23 | from megatron.core import mpu |
| 24 | +from megatron_adaptor.patches.megatron.profile import profile_step | ||
| 24 | from mindspeed.args_utils import get_full_args as get_args | 25 | from mindspeed.args_utils import get_full_args as get_args |
| 25 | from megatron.core.num_microbatches_calculator import get_num_microbatches | 26 | from megatron.core.num_microbatches_calculator import get_num_microbatches |
| 26 | from megatron.training import get_timers | 27 | from megatron.training import get_timers |
| @@ -256,6 +257,10 @@ def train_step( | |||
| 256 | if args.empty_unused_memory_level >= 2: | 257 | if args.empty_unused_memory_level >= 2: |
| 257 | torch.cuda.empty_cache() | 258 | torch.cuda.empty_cache() |
| 258 | 259 | ||
| 260 | + # Full replacement of train_step shadows the profile feature's wrapper on | ||
| 261 | + # the same target; drive the profiler explicitly. | ||
| 262 | + profile_step() | ||
| 263 | + | ||
| 259 | if mpu.is_pipeline_last_stage(ignore_virtual=True): | 264 | if mpu.is_pipeline_last_stage(ignore_virtual=True): |
| 260 | loss_reduced = finish_async_loss_reductions(pending_loss_reductions) | 265 | loss_reduced = finish_async_loss_reductions(pending_loss_reductions) |
| 261 | return ( | 266 | return ( |
| @@ -9,7 +9,7 @@ Replaced mindspeed.core.fp8.* imports with TENPU direct calls. | |||
| 9 | 9 | ||
| 10 | import warnings | 10 | import warnings |
| 11 | from contextlib import AbstractContextManager, ContextDecorator | 11 | from contextlib import AbstractContextManager, ContextDecorator |
| 12 | -from typing import List, Callable, Tuple, Dict, Any, Union | 12 | +from typing import Callable, Tuple, Dict, Any, Union |
| 13 | 13 | ||
| 14 | import torch | 14 | import torch |
| 15 | from torch.utils.checkpoint import noop_context_fn, detach_variable | 15 | from torch.utils.checkpoint import noop_context_fn, detach_variable |
| @@ -18,19 +18,30 @@ from megatron.core.tensor_parallel.random import _get_cuda_rng_state | |||
| 18 | from megatron.core.utils import safely_set_viewless_tensor_data | 18 | from megatron.core.utils import safely_set_viewless_tensor_data |
| 19 | from megatron.core.parallel_state import ( | 19 | from megatron.core.parallel_state import ( |
| 20 | get_tensor_model_parallel_group, | 20 | get_tensor_model_parallel_group, |
| 21 | - get_tensor_model_parallel_world_size, | ||
| 22 | ) | 21 | ) |
| 23 | from transformer_engine.pytorch import fp8_autocast | 22 | from transformer_engine.pytorch import fp8_autocast |
| 23 | +from transformer_engine.pytorch import distributed as te_distributed | ||
| 24 | from transformer_engine.pytorch.quantization.manager import ( | 24 | from transformer_engine.pytorch.quantization.manager import ( |
| 25 | FP8GlobalStateManager as TENPU_FP8GlobalStateManager, | 25 | FP8GlobalStateManager as TENPU_FP8GlobalStateManager, |
| 26 | ) | 26 | ) |
| 27 | 27 | ||
| 28 | -_FP8_ACTIVATION_RECOMPUTE_ENABLED = False | 28 | + |
| 29 | -_FP8_ACTIVATION_RECOMPUTE_PHASE = False | 29 | +class FP8RecomputeState: |
| 30 | + """State owned by one checkpoint, independent of microbatch execution order.""" | ||
| 31 | + | ||
| 32 | + def __init__(self): | ||
| 33 | + self.is_first_module = None | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def get_fp8_autocast_context(state): | ||
| 37 | + """Restore even a disabled context when nested inside a quantized forward.""" | ||
| 38 | + enabled, calibrating, recipe, group, _, graph = state | ||
| 39 | + return fp8_autocast(enabled=enabled, fp8_recipe=recipe, calibrating=calibrating, fp8_group=group, _graph=graph) | ||
| 30 | 40 | ||
| 31 | 41 | ||
| 32 | # ---- Inlined from mindspeed/core/fp8/utils.py ---- | 42 | # ---- Inlined from mindspeed/core/fp8/utils.py ---- |
| 33 | 43 | ||
| 44 | + | ||
| 34 | def _get_tensor_model_parallel_group_if_none(tp_group, is_expert=False, check_initialized=True): | 45 | def _get_tensor_model_parallel_group_if_none(tp_group, is_expert=False, check_initialized=True): |
| 35 | """Return default TP group if tp_group is None.""" | 46 | """Return default TP group if tp_group is None.""" |
| 36 | if not torch.distributed.is_initialized(): | 47 | if not torch.distributed.is_initialized(): |
| @@ -42,6 +53,7 @@ def _get_tensor_model_parallel_group_if_none(tp_group, is_expert=False, check_in | |||
| 42 | # For expert TP, use get_expert_tensor_parallel_group if available | 53 | # For expert TP, use get_expert_tensor_parallel_group if available |
| 43 | try: | 54 | try: |
| 44 | from megatron.core.parallel_state import get_expert_tensor_parallel_group | 55 | from megatron.core.parallel_state import get_expert_tensor_parallel_group |
| 56 | + | ||
| 45 | tp_group = get_expert_tensor_parallel_group(check_initialized=check_initialized) | 57 | tp_group = get_expert_tensor_parallel_group(check_initialized=check_initialized) |
| 46 | except ImportError: | 58 | except ImportError: |
| 47 | pass | 59 | pass |
| @@ -73,71 +85,94 @@ def _gather_split_1d_tensor(tensor, tp_group=None): | |||
| 73 | """Gather values from tensor model parallel ranks.""" | 85 | """Gather values from tensor model parallel ranks.""" |
| 74 | tp_group = _get_tensor_model_parallel_group_if_none(tp_group) | 86 | tp_group = _get_tensor_model_parallel_group_if_none(tp_group) |
| 75 | numel_gathered = torch.numel(tensor) * tp_group.size() | 87 | numel_gathered = torch.numel(tensor) * tp_group.size() |
| 76 | - gathered = torch.empty( | 88 | + gathered = torch.empty(numel_gathered, dtype=tensor.dtype, device=torch.npu.current_device(), requires_grad=False) |
| 77 | - numel_gathered, dtype=tensor.dtype, device=torch.npu.current_device(), requires_grad=False | ||
| 78 | - ) | ||
| 79 | torch.distributed._all_gather_base(gathered, tensor, group=tp_group) | 89 | torch.distributed._all_gather_base(gathered, tensor, group=tp_group) |
| 80 | return gathered | 90 | return gathered |
| 81 | 91 | ||
| 82 | 92 | ||
| 83 | # ---- Context manager ---- | 93 | # ---- Context manager ---- |
| 84 | 94 | ||
| 95 | + | ||
| 85 | class activation_recompute_forward(AbstractContextManager, ContextDecorator): | 96 | class activation_recompute_forward(AbstractContextManager, ContextDecorator): |
| 86 | """Context manager for FP8 activation recompute coordination. | 97 | """Context manager for FP8 activation recompute coordination. |
| 87 | 98 | ||
| 88 | Sets global flags so FP8 modules know whether they are in the first | 99 | Sets global flags so FP8 modules know whether they are in the first |
| 89 | forward pass or the recompute (backward) forward pass. | 100 | forward pass or the recompute (backward) forward pass. |
| 90 | """ | 101 | """ |
| 91 | - _is_first_fp8_module: List = [] | ||
| 92 | 102 | ||
| 93 | - def __init__(self, activation_recompute: bool = False, recompute_phase: bool = False): | 103 | + def __init__(self, activation_recompute: bool = False, recompute_phase: bool = False, state=None): |
| 94 | super().__init__() | 104 | super().__init__() |
| 95 | self.activation_recompute = activation_recompute | 105 | self.activation_recompute = activation_recompute |
| 96 | self.recompute_phase = recompute_phase | 106 | self.recompute_phase = recompute_phase |
| 107 | + self.state = state | ||
| 97 | 108 | ||
| 98 | def __enter__(self): | 109 | def __enter__(self): |
| 99 | - global _FP8_ACTIVATION_RECOMPUTE_ENABLED, _FP8_ACTIVATION_RECOMPUTE_PHASE | 110 | + if self.state is not None and self.activation_recompute and self.recompute_phase: |
| 100 | - _FP8_ACTIVATION_RECOMPUTE_ENABLED = self.activation_recompute | 111 | + if self.state.is_first_module is None: |
| 101 | - _FP8_ACTIVATION_RECOMPUTE_PHASE = self.recompute_phase | 112 | + raise RuntimeError("FP8 recompute requires the matching checkpoint forward state.") |
| 102 | - | 113 | + self.previous = ( |
| 103 | - if self.activation_recompute and not self.recompute_phase: | 114 | + te_distributed.is_fp8_activation_recompute_enabled(), |
| 104 | - activation_recompute_forward._is_first_fp8_module.append( | 115 | + te_distributed.in_fp8_activation_recompute_phase(), |
| 105 | - TENPU_FP8GlobalStateManager.quantization_state.is_first_fp8_module) | 116 | + ) |
| 106 | - if self.activation_recompute and self.recompute_phase: | 117 | + qstate = TENPU_FP8GlobalStateManager.quantization_state |
| 107 | - TENPU_FP8GlobalStateManager.quantization_state.is_first_fp8_module = \ | 118 | + self.previous_first_module = qstate.is_first_fp8_module |
| 108 | - activation_recompute_forward._is_first_fp8_module.pop(0) | 119 | + if self.state is None: |
| 120 | + self.backend_context = te_distributed.activation_recompute_forward( | ||
| 121 | + self.activation_recompute, self.recompute_phase | ||
| 122 | + ) | ||
| 123 | + self.backend_context.__enter__() | ||
| 124 | + else: | ||
| 125 | + # TE modules read these flags from TE's distributed module. A second | ||
| 126 | + # MindSpeed copy silently skips delayed-scaling snapshot/restore. | ||
| 127 | + te_distributed._FP8_ACTIVATION_RECOMPUTE_ENABLED = self.activation_recompute | ||
| 128 | + te_distributed._FP8_ACTIVATION_RECOMPUTE_PHASE = self.recompute_phase | ||
| 129 | + if self.activation_recompute: | ||
| 130 | + if self.recompute_phase: | ||
| 131 | + qstate.is_first_fp8_module = self.state.is_first_module | ||
| 132 | + else: | ||
| 133 | + self.state.is_first_module = qstate.is_first_fp8_module | ||
| 134 | + return self | ||
| 109 | 135 | ||
| 110 | def __exit__(self, *exc_details): | 136 | def __exit__(self, *exc_details): |
| 111 | - global _FP8_ACTIVATION_RECOMPUTE_ENABLED, _FP8_ACTIVATION_RECOMPUTE_PHASE | 137 | + if self.state is None: |
| 112 | - _FP8_ACTIVATION_RECOMPUTE_ENABLED = False | 138 | + self.backend_context.__exit__(*exc_details) |
| 113 | - _FP8_ACTIVATION_RECOMPUTE_PHASE = False | 139 | + ( |
| 140 | + te_distributed._FP8_ACTIVATION_RECOMPUTE_ENABLED, | ||
| 141 | + te_distributed._FP8_ACTIVATION_RECOMPUTE_PHASE, | ||
| 142 | + ) = self.previous | ||
| 143 | + if self.recompute_phase: | ||
| 144 | + TENPU_FP8GlobalStateManager.quantization_state.is_first_fp8_module = self.previous_first_module | ||
| 114 | 145 | ||
| 115 | 146 | ||
| 116 | def get_activation_recompute_contexts(): | 147 | def get_activation_recompute_contexts(): |
| 117 | """Returns context objects for the checkpointed forward pass and the forward recompute phase.""" | 148 | """Returns context objects for the checkpointed forward pass and the forward recompute phase.""" |
| 149 | + state = FP8RecomputeState() | ||
| 118 | forward_ctx = activation_recompute_forward( | 150 | forward_ctx = activation_recompute_forward( |
| 119 | activation_recompute=True, | 151 | activation_recompute=True, |
| 120 | recompute_phase=False, | 152 | recompute_phase=False, |
| 153 | + state=state, | ||
| 121 | ) | 154 | ) |
| 122 | recompute_ctx = activation_recompute_forward( | 155 | recompute_ctx = activation_recompute_forward( |
| 123 | activation_recompute=True, | 156 | activation_recompute=True, |
| 124 | recompute_phase=True, | 157 | recompute_phase=True, |
| 158 | + state=state, | ||
| 125 | ) | 159 | ) |
| 126 | return forward_ctx, recompute_ctx | 160 | return forward_ctx, recompute_ctx |
| 127 | 161 | ||
| 128 | 162 | ||
| 129 | def is_fp8_activation_recompute_enabled() -> bool: | 163 | def is_fp8_activation_recompute_enabled() -> bool: |
| 130 | """Return global boolean for FP8 activation recompute enabled state.""" | 164 | """Return global boolean for FP8 activation recompute enabled state.""" |
| 131 | - return _FP8_ACTIVATION_RECOMPUTE_ENABLED | 165 | + return te_distributed.is_fp8_activation_recompute_enabled() |
| 132 | 166 | ||
| 133 | 167 | ||
| 134 | def in_fp8_activation_recompute_phase() -> bool: | 168 | def in_fp8_activation_recompute_phase() -> bool: |
| 135 | """Return global boolean for FP8 activation recompute phase.""" | 169 | """Return global boolean for FP8 activation recompute phase.""" |
| 136 | - return _FP8_ACTIVATION_RECOMPUTE_PHASE | 170 | + return te_distributed.in_fp8_activation_recompute_phase() |
| 137 | 171 | ||
| 138 | 172 | ||
| 139 | # ---- Checkpoint function ---- | 173 | # ---- Checkpoint function ---- |
| 140 | 174 | ||
| 175 | + | ||
| 141 | def checkpoint( | 176 | def checkpoint( |
| 142 | function: Callable, | 177 | function: Callable, |
| 143 | *args: Tuple[torch.Tensor, ...], | 178 | *args: Tuple[torch.Tensor, ...], |
| @@ -148,8 +183,7 @@ def checkpoint( | |||
| 148 | Adapted from TransformerEngine's checkpoint to support FP8 | 183 | Adapted from TransformerEngine's checkpoint to support FP8 |
| 149 | activation recompute via activation_recompute_forward contexts. | 184 | activation recompute via activation_recompute_forward contexts. |
| 150 | """ | 185 | """ |
| 151 | - global _USE_REENTRANT_ACTIVATION_RECOMPUTE | 186 | + use_reentrant = kwargs.pop("use_reentrant", True) |
| 152 | - _USE_REENTRANT_ACTIVATION_RECOMPUTE = kwargs.pop("use_reentrant", True) | ||
| 153 | distribute_saved_activations = kwargs.pop("distribute_saved_activations", False) | 187 | distribute_saved_activations = kwargs.pop("distribute_saved_activations", False) |
| 154 | tp_group = kwargs.pop("tp_group", None) | 188 | tp_group = kwargs.pop("tp_group", None) |
| 155 | get_rng_state_tracker = kwargs.pop("get_rng_state_tracker", None) | 189 | get_rng_state_tracker = kwargs.pop("get_rng_state_tracker", None) |
| @@ -178,7 +212,7 @@ def checkpoint( | |||
| 178 | debug = kwargs.pop("debug", False) | 212 | debug = kwargs.pop("debug", False) |
| 179 | 213 | ||
| 180 | del determinism_check, debug | 214 | del determinism_check, debug |
| 181 | - if _USE_REENTRANT_ACTIVATION_RECOMPUTE: | 215 | + if use_reentrant: |
| 182 | if distribute_saved_activations: | 216 | if distribute_saved_activations: |
| 183 | assert torch.distributed.is_initialized(), "torch.distributed is not initialized." | 217 | assert torch.distributed.is_initialized(), "torch.distributed is not initialized." |
| 184 | tp_group = torch.distributed.GroupMember.WORLD if tp_group is None else tp_group | 218 | tp_group = torch.distributed.GroupMember.WORLD if tp_group is None else tp_group |
| @@ -204,15 +238,14 @@ def checkpoint( | |||
| 204 | user_forward_ctx, user_recompute_ctx = context_fn() | 238 | user_forward_ctx, user_recompute_ctx = context_fn() |
| 205 | te_forward_ctx, te_recompute_ctx = get_activation_recompute_contexts() | 239 | te_forward_ctx, te_recompute_ctx = get_activation_recompute_contexts() |
| 206 | 240 | ||
| 207 | - fp8 = TENPU_FP8GlobalStateManager.is_fp8_enabled() | 241 | + autocast_state = TENPU_FP8GlobalStateManager.get_fp8_autocast_state() |
| 208 | - fp8_recipe = TENPU_FP8GlobalStateManager.get_fp8_recipe() if fp8 else None | ||
| 209 | 242 | ||
| 210 | def recompute_fn(*args, **kwargs): | 243 | def recompute_fn(*args, **kwargs): |
| 211 | with ( | 244 | with ( |
| 212 | torch.autograd.enable_grad(), | 245 | torch.autograd.enable_grad(), |
| 246 | + get_fp8_autocast_context(autocast_state), | ||
| 213 | te_recompute_ctx, | 247 | te_recompute_ctx, |
| 214 | user_recompute_ctx, | 248 | user_recompute_ctx, |
| 215 | - fp8_autocast(enabled=fp8, fp8_recipe=fp8_recipe), | ||
| 216 | ): | 249 | ): |
| 217 | function(*args, **kwargs) | 250 | function(*args, **kwargs) |
| 218 | 251 | ||
| @@ -259,8 +292,10 @@ class _CheckpointFunction(torch.autograd.Function): | |||
| 259 | else: | 292 | else: |
| 260 | forward_ctx, recompute_ctx = noop_context_fn() | 293 | forward_ctx, recompute_ctx = noop_context_fn() |
| 261 | 294 | ||
| 295 | + ctx.fp8_recompute_state = FP8RecomputeState() | ||
| 296 | + ctx.autocast_state = TENPU_FP8GlobalStateManager.get_fp8_autocast_state() | ||
| 262 | with torch.no_grad(), forward_ctx: | 297 | with torch.no_grad(), forward_ctx: |
| 263 | - with activation_recompute_forward(activation_recompute=True, recompute_phase=False): | 298 | + with activation_recompute_forward(True, False, state=ctx.fp8_recompute_state): |
| 264 | outputs = run_function(*args, **kwargs) | 299 | outputs = run_function(*args, **kwargs) |
| 265 | 300 | ||
| 266 | if distribute_saved_activations: | 301 | if distribute_saved_activations: |
| @@ -311,18 +346,19 @@ class _CheckpointFunction(torch.autograd.Function): | |||
| 311 | get_rng_state_tracker().set_states(ctx.fwd_cuda_rng_state_tracker) | 346 | get_rng_state_tracker().set_states(ctx.fwd_cuda_rng_state_tracker) |
| 312 | 347 | ||
| 313 | detached_inputs = detach_variable(inputs) | 348 | detached_inputs = detach_variable(inputs) |
| 314 | - with ( | 349 | + try: |
| 315 | - torch.enable_grad(), | 350 | + with ( |
| 316 | - ctx.recompute_ctx, | 351 | + torch.enable_grad(), |
| 317 | - activation_recompute_forward(activation_recompute=True, recompute_phase=True), | 352 | + get_fp8_autocast_context(ctx.autocast_state), |
| 318 | - fp8_autocast(enabled=ctx.fp8, fp8_recipe=ctx.fp8_recipe), | 353 | + activation_recompute_forward(True, True, state=ctx.fp8_recompute_state), |
| 319 | - ): | 354 | + ctx.recompute_ctx, |
| 320 | - outputs = ctx.run_function(*detached_inputs, **ctx.kwargs) | 355 | + ): |
| 321 | - | 356 | + outputs = ctx.run_function(*detached_inputs, **ctx.kwargs) |
| 322 | - torch.set_rng_state(bwd_cpu_rng_state) | 357 | + finally: |
| 323 | - _set_cuda_rng_state(bwd_cuda_rng_state, graph_safe=False) | 358 | + torch.set_rng_state(bwd_cpu_rng_state) |
| 324 | - if get_rng_state_tracker is not None: | 359 | + _set_cuda_rng_state(bwd_cuda_rng_state, graph_safe=False) |
| 325 | - get_rng_state_tracker().set_states(bwd_cuda_rng_state_tracker) | 360 | + if get_rng_state_tracker is not None: |
| 361 | + get_rng_state_tracker().set_states(bwd_cuda_rng_state_tracker) | ||
| 326 | 362 | ||
| 327 | if isinstance(outputs, torch.Tensor): | 363 | if isinstance(outputs, torch.Tensor): |
| 328 | outputs = (outputs,) | 364 | outputs = (outputs,) |
| @@ -380,7 +416,6 @@ class _CheckpointFrame: | |||
| 380 | 416 | ||
| 381 | 417 | ||
| 382 | class _recomputation_hook(torch.autograd.graph.saved_tensors_hooks): | 418 | class _recomputation_hook(torch.autograd.graph.saved_tensors_hooks): |
| 383 | - | ||
| 384 | def __init__(self, frame): | 419 | def __init__(self, frame): |
| 385 | def pack_hook(x): | 420 | def pack_hook(x): |
| 386 | frame.recomputed.append(x.detach()) | 421 | frame.recomputed.append(x.detach()) |
| @@ -393,7 +428,6 @@ class _recomputation_hook(torch.autograd.graph.saved_tensors_hooks): | |||
| 393 | 428 | ||
| 394 | 429 | ||
| 395 | class _checkpoint_hook(torch.autograd.graph.saved_tensors_hooks): | 430 | class _checkpoint_hook(torch.autograd.graph.saved_tensors_hooks): |
| 396 | - | ||
| 397 | def __init__(self, frame, args, kwargs): | 431 | def __init__(self, frame, args, kwargs): |
| 398 | def pack_hook(x): | 432 | def pack_hook(x): |
| 399 | del x | 433 | del x |
| @@ -405,9 +439,11 @@ class _checkpoint_hook(torch.autograd.graph.saved_tensors_hooks): | |||
| 405 | if not frame.recomputed: | 439 | if not frame.recomputed: |
| 406 | frame.cache_rng_states(forward=False) | 440 | frame.cache_rng_states(forward=False) |
| 407 | frame.restore_rng_states(forward=True) | 441 | frame.restore_rng_states(forward=True) |
| 408 | - with _recomputation_hook(frame): | 442 | + try: |
| 409 | - frame.recompute_fn(*args, **kwargs) | 443 | + with _recomputation_hook(frame): |
| 410 | - frame.restore_rng_states(forward=False) | 444 | + frame.recompute_fn(*args, **kwargs) |
| 445 | + finally: | ||
| 446 | + frame.restore_rng_states(forward=False) | ||
| 411 | 447 | ||
| 412 | activation = frame.recomputed[idx] | 448 | activation = frame.recomputed[idx] |
| 413 | frame.recomputed[idx] = None | 449 | frame.recomputed[idx] = None |
| @@ -7,11 +7,8 @@ import warnings | |||
| 7 | from contextlib import nullcontext | 7 | from contextlib import nullcontext |
| 8 | from functools import wraps | 8 | from functools import wraps |
| 9 | 9 | ||
| 10 | -from megatron.core import parallel_state | ||
| 11 | -from megatron.core.enums import Fp8Recipe | ||
| 12 | from megatron.core.transformer.transformer_config import TransformerConfig | 10 | from megatron.core.transformer.transformer_config import TransformerConfig |
| 13 | -from megatron.core.extensions.transformer_engine import TEDelayedScaling | 11 | +from megatron.core.fp8_utils import get_fp8_context as megatron_fp8_context |
| 14 | -from mindspeed.args_utils import get_full_args | ||
| 15 | 12 | ||
| 16 | 13 | ||
| 17 | def quantize_param_shard( | 14 | def quantize_param_shard( |
| @@ -27,105 +24,27 @@ def quantize_param_shard( | |||
| 27 | 24 | ||
| 28 | 25 | ||
| 29 | def get_fp8_context(config: TransformerConfig, layer_no: int = -1, is_init: bool = False): | 26 | def get_fp8_context(config: TransformerConfig, layer_no: int = -1, is_init: bool = False): |
| 30 | - """Return fp8 context manager. | 27 | + """Use Megatron's patched FP8/FP4 recipe factories for every MindSpeed path. |
| 31 | 28 | ||
| 32 | - Arguments: | 29 | + The historical name also covers FP4. Duplicating recipe construction here |
| 33 | - config (TransformerConfig): Configuration object. | 30 | + bypasses HiF8, MXFP8-32x32, FP4 and quantization-scope extensions. |
| 34 | - layer_no (int): *Global* layer index (including layers on other | ||
| 35 | - pipeline-parallel ranks). | ||
| 36 | - is_init (bool): Whether the context is fp8_model_init (True) or fp8_autocast (False). | ||
| 37 | - | ||
| 38 | - Returns: | ||
| 39 | - FP8 context. | ||
| 40 | - If layer_no < 0, we return a fp8 context for all layers regardless of layer_no. | ||
| 41 | - We return nullcontext() when: a) not using fp8 to train, b) layer_no is a layer | ||
| 42 | - that needs to be trained in bf16. | ||
| 43 | """ | 31 | """ |
| 44 | - num_bf16_layers_at_start = config.num_layers_at_start_in_bf16 if config.first_last_layers_bf16 else 0 | 32 | + if not is_init and layer_no >= 0 and getattr(config, "first_last_layers_bf16", False): |
| 45 | - num_bf16_layers_at_end = config.num_layers_at_end_in_bf16 if config.first_last_layers_bf16 else 0 | 33 | + first = layer_no < config.num_layers_at_start_in_bf16 |
| 46 | - # Since layer_no is a global layer index, additional checks on whether | 34 | + last = layer_no >= config.num_layers - config.num_layers_at_end_in_bf16 |
| 47 | - # we are in the first or last pipeline-parallel rank are not needed. | 35 | + if first or last: |
| 48 | - is_first_layer = layer_no < num_bf16_layers_at_start | 36 | + # A nullcontext would inherit the outer FB-overlap block's FP8 |
| 49 | - is_last_layer = layer_no >= config.num_layers - num_bf16_layers_at_end | 37 | + # state, quantizing layers explicitly configured to stay in BF16. |
| 38 | + from transformer_engine.pytorch import fp8_autocast | ||
| 50 | 39 | ||
| 51 | - need_fp8_context = config.fp8 if not is_init else config.fp8_param | 40 | + return fp8_autocast(enabled=False) |
| 41 | + if getattr(config, "fp8", None) or (is_init and getattr(config, "fp8_param", False)): | ||
| 42 | + return megatron_fp8_context(config, layer_no, is_init) | ||
| 43 | + if getattr(config, "fp4", None) or (is_init and getattr(config, "fp4_param", False)): | ||
| 44 | + from megatron.core.fp4_utils import get_fp4_context | ||
| 52 | 45 | ||
| 53 | - if not need_fp8_context: | 46 | + return get_fp4_context(config, layer_no, is_init) |
| 54 | - # bf16 training | 47 | + return nullcontext() |
| 55 | - fp8_context = nullcontext() | ||
| 56 | - elif layer_no >= 0 and config.first_last_layers_bf16 and (is_first_layer or is_last_layer): | ||
| 57 | - # fp8 training but this layer_no should be bf16 | ||
| 58 | - fp8_context = nullcontext() | ||
| 59 | - else: | ||
| 60 | - from transformer_engine.common.recipe import ( | ||
| 61 | - Float8CurrentScaling, | ||
| 62 | - MXFP8BlockScaling, | ||
| 63 | - Float8BlockScaling, | ||
| 64 | - Format, | ||
| 65 | - ) | ||
| 66 | - from transformer_engine.pytorch import fp8_autocast, fp8_model_init | ||
| 67 | - | ||
| 68 | - if config.fp8 == "e4m3": | ||
| 69 | - fp8_format = Format.E4M3 | ||
| 70 | - elif config.fp8 == "hybrid": | ||
| 71 | - fp8_format = Format.HYBRID | ||
| 72 | - elif config.fp8 == "hif8": | ||
| 73 | - fp8_format = Format.HIF8 | ||
| 74 | - else: | ||
| 75 | - raise ValueError("E4M3, HYBRID and hif8 are the only supported FP8 formats.") | ||
| 76 | - | ||
| 77 | - # Select fp8 recipe (TE version >= 2.1.0). | ||
| 78 | - if config.fp8_recipe == Fp8Recipe.delayed: | ||
| 79 | - fp8_recipe = TEDelayedScaling( | ||
| 80 | - config=config, | ||
| 81 | - fp8_format=fp8_format, | ||
| 82 | - override_linear_precision=(False, False, not config.fp8_wgrad), | ||
| 83 | - ) | ||
| 84 | - elif config.fp8_recipe == Fp8Recipe.tensorwise: | ||
| 85 | - fp8_recipe = Float8CurrentScaling(fp8_format=fp8_format) | ||
| 86 | - elif getattr(config, "mxfp8_32x32", False) or getattr(get_full_args(), "mxfp8_32x32", False): | ||
| 87 | - try: | ||
| 88 | - from transformer_engine.common.recipe import MXFP832x32BlockScaling | ||
| 89 | - except ImportError as exc: | ||
| 90 | - raise RuntimeError("mxfp8-32x32 requires TENPU branch feat/mxfp8-32x32 or a newer release") from exc | ||
| 91 | - fp8_recipe = MXFP832x32BlockScaling(fp8_format=fp8_format) | ||
| 92 | - elif config.fp8_recipe == Fp8Recipe.mxfp8: | ||
| 93 | - fp8_recipe = MXFP8BlockScaling(fp8_format=fp8_format) | ||
| 94 | - elif config.fp8_recipe == Fp8Recipe.blockwise: | ||
| 95 | - fp8_recipe = Float8BlockScaling(fp8_format=fp8_format) | ||
| 96 | - else: | ||
| 97 | - raise ValueError( | ||
| 98 | - "Float8CurrentScaling, MXFP8BlockScaling, MXFP832x32BlockScaling " | ||
| 99 | - "and DelayedScaling are the only supported FP8 recipes." | ||
| 100 | - ) | ||
| 101 | - fp8_group = None | ||
| 102 | - if parallel_state.model_parallel_is_initialized(): | ||
| 103 | - fp8_group = parallel_state.get_amax_reduction_group( | ||
| 104 | - with_context_parallel=True, tp_only_amax_red=config.tp_only_amax_red | ||
| 105 | - ) | ||
| 106 | - | ||
| 107 | - if not is_init: | ||
| 108 | - fp8_context = fp8_autocast(enabled=True, fp8_recipe=fp8_recipe, fp8_group=fp8_group) | ||
| 109 | - else: | ||
| 110 | - import inspect | ||
| 111 | - | ||
| 112 | - context_args = {"enabled": True} | ||
| 113 | - # Check if fp8_model_init supports setting recipe | ||
| 114 | - if "recipe" in (inspect.signature(fp8_model_init).parameters): | ||
| 115 | - context_args["recipe"] = fp8_recipe | ||
| 116 | - # Check if fp8_model_init supports preserve_high_precision_init_val | ||
| 117 | - if "preserve_high_precision_init_val" in (inspect.signature(fp8_model_init).parameters): | ||
| 118 | - context_args["preserve_high_precision_init_val"] = True | ||
| 119 | - fp8_context = fp8_model_init(**context_args) | ||
| 120 | - | ||
| 121 | - # First / last layer in bf16 isn't supported with delayed scaling since it | ||
| 122 | - # requires entering/exiting fp8 context per layer, causing incorrect amax | ||
| 123 | - # reduction behavior. | ||
| 124 | - assert not (config.first_last_layers_bf16 and isinstance(fp8_recipe, TEDelayedScaling)), ( | ||
| 125 | - "Delayed scaling does not support first / last layer in BF16." | ||
| 126 | - ) | ||
| 127 | - | ||
| 128 | - return fp8_context | ||
| 129 | 48 | ||
| 130 | 49 | ||
| 131 | def fp8_context_wrapper(config: TransformerConfig, layer_no: int = -1, is_init: bool = False): | 50 | def fp8_context_wrapper(config: TransformerConfig, layer_no: int = -1, is_init: bool = False): |
| @@ -1,6 +1,48 @@ | |||
| 1 | +import torch | ||
| 1 | import torch_npu | 2 | import torch_npu |
| 2 | 3 | ||
| 3 | 4 | ||
| 5 | +def _check_empty_weighted_swiglu(y, weights): | ||
| 6 | + # The native kernel does not accept empty tensors. Only the standard empty | ||
| 7 | + # expert has two empty gradients; e.g. [tokens, 0] needs a nonempty zero wgrad. | ||
| 8 | + if y.ndim != 2 or y.shape[0] != 0 or y.shape[1] % 2 or weights.shape != (0, 1): | ||
| 9 | + raise ValueError('Empty weighted SwiGLU requires input [0, 2H] and weights [0, 1].') | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +# Register these helpers directly, without jit_fuser: its NPU shim is named | ||
| 13 | +# "wrapper", which the patch manager interprets as a patch decorator. | ||
| 14 | +def weighted_swiglu(y, weights): | ||
| 15 | + """Fuse the activation while preserving Megatron's weighted output dtype.""" | ||
| 16 | + if y.numel() == 0: | ||
| 17 | + _check_empty_weighted_swiglu(y, weights) | ||
| 18 | + return y.new_empty((0, y.shape[1] // 2)) | ||
| 19 | + return (fused_swiglu(y.contiguous()) * weights).to(y.dtype) | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def weighted_swiglu_back(g, y, weights): | ||
| 23 | + """Use the native SwiGLU derivative; keep router weighting in its own dtype.""" | ||
| 24 | + if torch.is_grad_enabled(): | ||
| 25 | + raise RuntimeError('Fused weighted SwiGLU supports first-order backward only.') | ||
| 26 | + if y.numel() == 0: | ||
| 27 | + _check_empty_weighted_swiglu(y, weights) | ||
| 28 | + return ( | ||
| 29 | + torch.empty_like(y, memory_format=torch.contiguous_format), | ||
| 30 | + torch.empty_like(weights, memory_format=torch.contiguous_format), | ||
| 31 | + ) | ||
| 32 | + | ||
| 33 | + weighted_grad = g * weights | ||
| 34 | + # SwiGluGrad requires matching dtypes. Keep FP32 router weighting rather | ||
| 35 | + # than rounding the weighted gradient down before differentiating. | ||
| 36 | + backward_input = y.to(weighted_grad.dtype).contiguous() | ||
| 37 | + input_grad = torch_npu.npu_swiglu_backward(weighted_grad.contiguous(), backward_input, dim=-1).to(y.dtype) | ||
| 38 | + del backward_input, weighted_grad | ||
| 39 | + # Recompute this activation instead of extending its lifetime across the | ||
| 40 | + # forward/backward boundary. The original Function still saves y and weights. | ||
| 41 | + activation = fused_swiglu(y.contiguous()) | ||
| 42 | + weights_grad = torch.sum(activation * g.to(weights.dtype), dim=-1, keepdim=True).to(weights.dtype) | ||
| 43 | + return input_grad, weights_grad | ||
| 44 | + | ||
| 45 | + | ||
| 4 | def fused_swiglu(x): | 46 | def fused_swiglu(x): |
| 5 | return torch_npu.npu_swiglu(x, dim=-1) | 47 | return torch_npu.npu_swiglu(x, dim=-1) |
| 6 | 48 | ||
| @@ -1,5 +1,7 @@ | |||
| 1 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. | 1 | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. |
| 2 | # Copyright (c) 2025, Huawei Technologies Co., Ltd. All rights reserved. | 2 | # Copyright (c) 2025, Huawei Technologies Co., Ltd. All rights reserved. |
| 3 | +from functools import wraps | ||
| 4 | + | ||
| 3 | import torch | 5 | import torch |
| 4 | from torch import Tensor | 6 | from torch import Tensor |
| 5 | 7 | ||
| @@ -9,6 +11,46 @@ from mindspeed.ops.npu_rotary_position_embedding import npu_rotary_position_embe | |||
| 9 | from mindspeed.core.transformer.multi_head_latent_attention.mla_utils import yarn_get_mscale | 11 | from mindspeed.core.transformer.multi_head_latent_attention.mla_utils import yarn_get_mscale |
| 10 | 12 | ||
| 11 | 13 | ||
| 14 | +def fused_apply_rotary_pos_emb_wrapper(fn): | ||
| 15 | + """Use the native NPU adjoint for ordinary SBHD RoPE. | ||
| 16 | + | ||
| 17 | + Megatron has already selected fusion and sliced CP frequencies before | ||
| 18 | + this entry point. The native autograd op saves forward cos/sin and calls | ||
| 19 | + RotaryPositionEmbeddingGrad directly; it does not inspect device values | ||
| 20 | + in Python or recompute the trigonometric tensors during backward. | ||
| 21 | + Other layouts retain the Transformer Engine implementation. | ||
| 22 | + """ | ||
| 23 | + | ||
| 24 | + @wraps(fn) | ||
| 25 | + def wrapper(t, freqs, transpose_output_memory=False, interleaved=False): | ||
| 26 | + # Keep the compatibility guard short-circuiting without extra hot-path calls. | ||
| 27 | + if ( | ||
| 28 | + transpose_output_memory # pylint: disable=too-many-boolean-expressions | ||
| 29 | + or t.ndim != 4 | ||
| 30 | + or freqs.ndim != 4 | ||
| 31 | + or freqs.shape[1:3] != (1, 1) | ||
| 32 | + or freqs.shape[0] < t.shape[0] | ||
| 33 | + or not 0 < freqs.shape[-1] <= t.shape[-1] | ||
| 34 | + or freqs.shape[-1] % 2 | ||
| 35 | + or freqs.requires_grad | ||
| 36 | + or t.numel() == 0 | ||
| 37 | + or t.dtype not in (torch.float16, torch.bfloat16, torch.float32) | ||
| 38 | + ): | ||
| 39 | + return fn(t, freqs, transpose_output_memory, interleaved) | ||
| 40 | + | ||
| 41 | + # Match TE's float32 frequency computation and partial-RoPE contract. | ||
| 42 | + freqs = freqs[: t.shape[0]].float() | ||
| 43 | + cos = freqs.cos().to(t.dtype) | ||
| 44 | + sin = freqs.sin().to(t.dtype) | ||
| 45 | + rot_dim = freqs.shape[-1] | ||
| 46 | + rotated = npu_rotary_position_embedding(t[..., :rot_dim].contiguous(), cos, sin, 1 if interleaved else 0) | ||
| 47 | + if rot_dim == t.shape[-1]: | ||
| 48 | + return rotated | ||
| 49 | + return torch.cat((rotated, t[..., rot_dim:]), dim=-1) | ||
| 50 | + | ||
| 51 | + return wrapper | ||
| 52 | + | ||
| 53 | + | ||
| 12 | def apply_rotary_pos_emb_bshd( | 54 | def apply_rotary_pos_emb_bshd( |
| 13 | t: Tensor, | 55 | t: Tensor, |
| 14 | freqs: Tensor, | 56 | freqs: Tensor, |
| @@ -1,10 +1,6 @@ | |||
| 1 | # Copyright (c) 2024, Huawei Technologies Co., Ltd. All rights reserved. | 1 | # Copyright (c) 2024, Huawei Technologies Co., Ltd. All rights reserved. |
| 2 | # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. | 2 | # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. |
| 3 | # Copyright (c) 2024, Bytedance Inc. All rights reserved. | 3 | # Copyright (c) 2024, Bytedance Inc. All rights reserved. |
| 4 | -import os | ||
| 5 | -from textwrap import wrap | ||
| 6 | -import types | ||
| 7 | -from functools import wraps | ||
| 8 | import torch | 4 | import torch |
| 9 | import torch.distributed | 5 | import torch.distributed |
| 10 | 6 | ||
| @@ -74,16 +70,16 @@ class ConvertFp32BF16Distrib: | |||
| 74 | for loop in range(loops): | 70 | for loop in range(loops): |
| 75 | start = loop * TRANSPOSE_BF16_BLOCK_SIZE | 71 | start = loop * TRANSPOSE_BF16_BLOCK_SIZE |
| 76 | end = (loop + 1) * TRANSPOSE_BF16_BLOCK_SIZE | 72 | end = (loop + 1) * TRANSPOSE_BF16_BLOCK_SIZE |
| 77 | - odd_even_tensor = ( | 73 | + odd_even_tensor = ((shard_int32_tensor[start:end] & 131071) == 65536).to( |
| 78 | - (shard_int32_tensor[start:end] & 131071) == 65536 | 74 | + dtype=shard_int32_tensor.dtype |
| 79 | - ).to(dtype=shard_int32_tensor.dtype) | 75 | + ) |
| 80 | shard_int32_tensor[start:end].sub_(odd_even_tensor) | 76 | shard_int32_tensor[start:end].sub_(odd_even_tensor) |
| 81 | sign_tensor = odd_even_tensor.to(dtype=exp_avg_sq_flatten.dtype).mul(2.0).sub(1.0) | 77 | sign_tensor = odd_even_tensor.to(dtype=exp_avg_sq_flatten.dtype).mul(2.0).sub(1.0) |
| 82 | exp_avg_sq_flatten[start:end].mul_(sign_tensor) | 78 | exp_avg_sq_flatten[start:end].mul_(sign_tensor) |
| 83 | if remain > 0: | 79 | if remain > 0: |
| 84 | - odd_even_tensor = ( | 80 | + odd_even_tensor = ((shard_int32_tensor[-remain:] & 131071) == 65536).to( |
| 85 | - (shard_int32_tensor[-remain:] & 131071) == 65536 | 81 | + dtype=shard_int32_tensor.dtype |
| 86 | - ).to(dtype=shard_int32_tensor.dtype) | 82 | + ) |
| 87 | shard_int32_tensor[-remain:].sub_(odd_even_tensor) | 83 | shard_int32_tensor[-remain:].sub_(odd_even_tensor) |
| 88 | sign_tensor = odd_even_tensor.to(dtype=exp_avg_sq_flatten.dtype).mul(2.0).sub(1.0) | 84 | sign_tensor = odd_even_tensor.to(dtype=exp_avg_sq_flatten.dtype).mul(2.0).sub(1.0) |
| 89 | exp_avg_sq_flatten[-remain:].mul_(sign_tensor) | 85 | exp_avg_sq_flatten[-remain:].mul_(sign_tensor) |
| @@ -91,8 +87,9 @@ class ConvertFp32BF16Distrib: | |||
| 91 | exp_avg_sq_state.data.copy_(meta.quantization(exp_avg_sq_fp32)) | 87 | exp_avg_sq_state.data.copy_(meta.quantization(exp_avg_sq_fp32)) |
| 92 | 88 | ||
| 93 | 89 | ||
| 94 | -def _copy_model_params_to_main_params(): | 90 | +def _copy_model_params_to_main_params(state_dict=None): |
| 95 | - pass | 91 | + if state_dict is not None: |
| 92 | + raise NotImplementedError("Initialize main params from state dict is not supported with reuse-fp32-param") | ||
| 96 | 93 | ||
| 97 | 94 | ||
| 98 | def load_parameter_state_from_dp_zero(*args, **kwargs): | 95 | def load_parameter_state_from_dp_zero(*args, **kwargs): |
| @@ -112,27 +109,23 @@ def load_parameter_state_from_dp_zero(*args, **kwargs): | |||
| 112 | data_parallel_rank = torch.distributed.get_rank(self.data_parallel_group_gloo) | 109 | data_parallel_rank = torch.distributed.get_rank(self.data_parallel_group_gloo) |
| 113 | data_parallel_group_gloo = self.data_parallel_group_gloo | 110 | data_parallel_group_gloo = self.data_parallel_group_gloo |
| 114 | data_parallel_global_ranks = torch.distributed.get_process_group_ranks(self.data_parallel_group_gloo) | 111 | data_parallel_global_ranks = torch.distributed.get_process_group_ranks(self.data_parallel_group_gloo) |
| 115 | - if data_parallel_world_size == 1 or \ | 112 | + if data_parallel_world_size == 1 or not hasattr(self, "shard_main_param_res_buffers"): |
| 116 | - not hasattr(self, "shard_main_param_res_buffers"): | ||
| 117 | return | 113 | return |
| 118 | for i, shard_main_param_res_buffer in enumerate(self.shard_main_param_res_buffers): | 114 | for i, shard_main_param_res_buffer in enumerate(self.shard_main_param_res_buffers): |
| 119 | shard_res_numel = shard_main_param_res_buffer.numel() | 115 | shard_res_numel = shard_main_param_res_buffer.numel() |
| 120 | recv_tensor = torch.empty((shard_res_numel,), dtype=torch.float16, device="cpu") | 116 | recv_tensor = torch.empty((shard_res_numel,), dtype=torch.float16, device="cpu") |
| 121 | if data_parallel_rank == 0: | 117 | if data_parallel_rank == 0: |
| 122 | send_tensors = [ | 118 | send_tensors = [ |
| 123 | - state_dict["shard_main_param_res"][i][ | 119 | + state_dict["shard_main_param_res"][i][dpr * shard_res_numel : (dpr + 1) * shard_res_numel] |
| 124 | - dpr * shard_res_numel: (dpr + 1) * shard_res_numel] for dpr in range(data_parallel_world_size) | 120 | + for dpr in range(data_parallel_world_size) |
| 125 | ] | 121 | ] |
| 126 | else: | 122 | else: |
| 127 | send_tensors = None | 123 | send_tensors = None |
| 128 | 124 | ||
| 129 | if self.disable_gloo_group: | 125 | if self.disable_gloo_group: |
| 130 | from mindspeed.utils import _scatter_hccl | 126 | from mindspeed.utils import _scatter_hccl |
| 131 | - _scatter_hccl( | 127 | + |
| 132 | - recv_tensor, | 128 | + _scatter_hccl(recv_tensor, send_tensors, data_parallel_global_ranks[0], self.data_parallel_group) |
| 133 | - send_tensors, | ||
| 134 | - data_parallel_global_ranks[0], | ||
| 135 | - self.data_parallel_group) | ||
| 136 | else: | 129 | else: |
| 137 | torch.distributed.scatter( | 130 | torch.distributed.scatter( |
| 138 | recv_tensor, | 131 | recv_tensor, |
| @@ -140,8 +133,9 @@ def load_parameter_state_from_dp_zero(*args, **kwargs): | |||
| 140 | data_parallel_global_ranks[0], | 133 | data_parallel_global_ranks[0], |
| 141 | data_parallel_group_gloo, | 134 | data_parallel_group_gloo, |
| 142 | ) | 135 | ) |
| 143 | - recv_tensor_bf16_view = torch.tensor(recv_tensor.data.untyped_storage(), dtype=torch.bfloat16, | 136 | + recv_tensor_bf16_view = torch.tensor( |
| 144 | - device=recv_tensor.device) | 137 | + recv_tensor.data.untyped_storage(), dtype=torch.bfloat16, device=recv_tensor.device |
| 138 | + ) | ||
| 145 | shard_main_param_res_buffer.copy_(recv_tensor_bf16_view) | 139 | shard_main_param_res_buffer.copy_(recv_tensor_bf16_view) |
| 146 | 140 | ||
| 147 | 141 | ||
| @@ -164,20 +158,26 @@ def get_parameter_state_dp_zero(self): | |||
| 164 | buffer_res_full_shard = [] | 158 | buffer_res_full_shard = [] |
| 165 | for shard_main_param_res_buffer in self.shard_main_param_res_buffers: | 159 | for shard_main_param_res_buffer in self.shard_main_param_res_buffers: |
| 166 | if self.disable_gloo_group: | 160 | if self.disable_gloo_group: |
| 167 | - recv_tensors = [torch.empty(shard_main_param_res_buffer.numel(), dtype=torch.float16, device="cpu") for _ in | 161 | + recv_tensors = [ |
| 168 | - range(data_parallel_world_size)] | 162 | + torch.empty(shard_main_param_res_buffer.numel(), dtype=torch.float16, device="cpu") |
| 163 | + for _ in range(data_parallel_world_size) | ||
| 164 | + ] | ||
| 169 | elif data_parallel_rank == 0: | 165 | elif data_parallel_rank == 0: |
| 170 | - recv_tensors = [torch.empty((shard_main_param_res_buffer.numel(),), dtype=torch.float16, device="cpu") for _ | 166 | + recv_tensors = [ |
| 171 | - in range(data_parallel_world_size)] | 167 | + torch.empty((shard_main_param_res_buffer.numel(),), dtype=torch.float16, device="cpu") |
| 168 | + for _ in range(data_parallel_world_size) | ||
| 169 | + ] | ||
| 172 | else: | 170 | else: |
| 173 | recv_tensors = None | 171 | recv_tensors = None |
| 174 | 172 | ||
| 175 | send_tensor = torch.empty((shard_main_param_res_buffer.numel(),), dtype=torch.float16, device="cpu") | 173 | send_tensor = torch.empty((shard_main_param_res_buffer.numel(),), dtype=torch.float16, device="cpu") |
| 176 | - send_tensor_bf16_view = torch.tensor(send_tensor.data.untyped_storage(), dtype=torch.bfloat16, | 174 | + send_tensor_bf16_view = torch.tensor( |
| 177 | - device=send_tensor.device) | 175 | + send_tensor.data.untyped_storage(), dtype=torch.bfloat16, device=send_tensor.device |
| 176 | + ) | ||
| 178 | send_tensor_bf16_view.copy_(shard_main_param_res_buffer.detach().cpu()) | 177 | send_tensor_bf16_view.copy_(shard_main_param_res_buffer.detach().cpu()) |
| 179 | if self.disable_gloo_group: | 178 | if self.disable_gloo_group: |
| 180 | from mindspeed.utils import _gather_hccl | 179 | from mindspeed.utils import _gather_hccl |
| 180 | + | ||
| 181 | _gather_hccl( | 181 | _gather_hccl( |
| 182 | send_tensor, | 182 | send_tensor, |
| 183 | recv_tensors, | 183 | recv_tensors, |
| @@ -193,7 +193,9 @@ def get_parameter_state_dp_zero(self): | |||
| 193 | if data_parallel_rank == 0: | 193 | if data_parallel_rank == 0: |
| 194 | buffer_res_full_shard.append(torch.cat(recv_tensors)) | 194 | buffer_res_full_shard.append(torch.cat(recv_tensors)) |
| 195 | 195 | ||
| 196 | - state['shard_main_param_res'] = buffer_res_full_shard | 196 | + # All ranks must participate in the gathers, but only DP rank 0 owns state. |
| 197 | + if data_parallel_rank == 0: | ||
| 198 | + state['shard_main_param_res'] = buffer_res_full_shard | ||
| 197 | return state | 199 | return state |
| 198 | 200 | ||
| 199 | 201 | ||
| @@ -212,16 +214,19 @@ def fp16_tensor_convert_to_fp32_tensor_dis(self): | |||
| 212 | if data_parallel_world_size == 1: | 214 | if data_parallel_world_size == 1: |
| 213 | for shard_fp32_param_fp16_view in self.shard_fp32_param_fp16_view_group: | 215 | for shard_fp32_param_fp16_view in self.shard_fp32_param_fp16_view_group: |
| 214 | shard_fp32_param_fp16_view.copy_( | 216 | shard_fp32_param_fp16_view.copy_( |
| 215 | - shard_fp32_param_fp16_view.view(2, -1).transpose(1, 0).reshape(-1).contiguous()) | 217 | + shard_fp32_param_fp16_view.view(2, -1).transpose(1, 0).reshape(-1).contiguous() |
| 218 | + ) | ||
| 216 | 219 | ||
| 217 | if self.npu_deterministic: | 220 | if self.npu_deterministic: |
| 218 | if not self.first_sub_flag: | 221 | if not self.first_sub_flag: |
| 219 | ConvertFp32BF16Distrib().fp16_tensor_convert_to_fp32_tensor_deterministic( | 222 | ConvertFp32BF16Distrib().fp16_tensor_convert_to_fp32_tensor_deterministic( |
| 220 | - self.shard_fp32_from_float16_groups, self.optimizer) | 223 | + self.shard_fp32_from_float16_groups, self.optimizer |
| 224 | + ) | ||
| 221 | else: | 225 | else: |
| 222 | for shard_res_and_buffer_model_param in self.shard_main_param_res_buffers: | 226 | for shard_res_and_buffer_model_param in self.shard_main_param_res_buffers: |
| 223 | shard_main_param_int32_view_buffer = self.model_param_bucket_and_shard_main_param_int32_view_map[ | 227 | shard_main_param_int32_view_buffer = self.model_param_bucket_and_shard_main_param_int32_view_map[ |
| 224 | - shard_res_and_buffer_model_param] | 228 | + shard_res_and_buffer_model_param |
| 229 | + ] | ||
| 225 | if not self.first_sub_flag: | 230 | if not self.first_sub_flag: |
| 226 | shard_main_param_int32_view_buffer.sub_(TRANSPOSE_BF16_BIT) | 231 | shard_main_param_int32_view_buffer.sub_(TRANSPOSE_BF16_BIT) |
| 227 | else: | 232 | else: |
| @@ -231,46 +236,53 @@ def fp16_tensor_convert_to_fp32_tensor_dis(self): | |||
| 231 | param_data_dp_numel = bucket_param_data.numel() // data_parallel_world_size | 236 | param_data_dp_numel = bucket_param_data.numel() // data_parallel_world_size |
| 232 | bucket_res = self.model_param_bucket_and_res_map[bucket_param_data] | 237 | bucket_res = self.model_param_bucket_and_res_map[bucket_param_data] |
| 233 | if data_parallel_rank == 0: | 238 | if data_parallel_rank == 0: |
| 234 | - bucket_param_data[param_data_dp_numel:param_data_dp_numel * 2].copy_( | 239 | + bucket_param_data[param_data_dp_numel : param_data_dp_numel * 2].copy_( |
| 235 | - bucket_param_data[:param_data_dp_numel]) | 240 | + bucket_param_data[:param_data_dp_numel] |
| 241 | + ) | ||
| 236 | bucket_res_position = max(0, data_parallel_rank - 1) * param_data_dp_numel | 242 | bucket_res_position = max(0, data_parallel_rank - 1) * param_data_dp_numel |
| 237 | shard_fp32_main_param_view = bucket_param_data[ | 243 | shard_fp32_main_param_view = bucket_param_data[ |
| 238 | - bucket_res_position: bucket_res_position + param_data_dp_numel * 2] | 244 | + bucket_res_position : bucket_res_position + param_data_dp_numel * 2 |
| 245 | + ] | ||
| 239 | shard_main_param_int32_view_bucket = self.model_param_bucket_and_shard_main_param_int32_view_map[ | 246 | shard_main_param_int32_view_bucket = self.model_param_bucket_and_shard_main_param_int32_view_map[ |
| 240 | - bucket_param_data] | 247 | + bucket_param_data |
| 248 | + ] | ||
| 241 | 249 | ||
| 242 | loops = param_data_dp_numel // TRANSPOSE_BF16_BLOCK_SIZE | 250 | loops = param_data_dp_numel // TRANSPOSE_BF16_BLOCK_SIZE |
| 243 | remain = param_data_dp_numel % TRANSPOSE_BF16_BLOCK_SIZE | 251 | remain = param_data_dp_numel % TRANSPOSE_BF16_BLOCK_SIZE |
| 244 | - workspace = torch.zeros( | 252 | + workspace = torch.zeros(TRANSPOSE_BF16_BLOCK_SIZE * 2, dtype=torch.bfloat16, device=bucket_res.device) |
| 245 | - TRANSPOSE_BF16_BLOCK_SIZE * 2, dtype=torch.bfloat16, device=bucket_res.device) | ||
| 246 | residual_space = bucket_res | 253 | residual_space = bucket_res |
| 247 | bf16_space_dp_rank = max(1, data_parallel_rank) | 254 | bf16_space_dp_rank = max(1, data_parallel_rank) |
| 248 | bf16_space = bucket_param_data[ | 255 | bf16_space = bucket_param_data[ |
| 249 | - param_data_dp_numel * bf16_space_dp_rank:param_data_dp_numel * (bf16_space_dp_rank + 1)] | 256 | + param_data_dp_numel * bf16_space_dp_rank : param_data_dp_numel * (bf16_space_dp_rank + 1) |
| 257 | + ] | ||
| 250 | 258 | ||
| 251 | for loop in range(loops): | 259 | for loop in range(loops): |
| 252 | copy_start = loop * TRANSPOSE_BF16_BLOCK_SIZE | 260 | copy_start = loop * TRANSPOSE_BF16_BLOCK_SIZE |
| 253 | copy_end = (loop + 1) * TRANSPOSE_BF16_BLOCK_SIZE | 261 | copy_end = (loop + 1) * TRANSPOSE_BF16_BLOCK_SIZE |
| 254 | - workspace_convert_view = workspace[:TRANSPOSE_BF16_BLOCK_SIZE * 2] | 262 | + workspace_convert_view = workspace[: TRANSPOSE_BF16_BLOCK_SIZE * 2] |
| 255 | - workspace[:TRANSPOSE_BF16_BLOCK_SIZE].copy_(residual_space[copy_start: copy_end]) | 263 | + workspace[:TRANSPOSE_BF16_BLOCK_SIZE].copy_(residual_space[copy_start:copy_end]) |
| 256 | - workspace[TRANSPOSE_BF16_BLOCK_SIZE:TRANSPOSE_BF16_BLOCK_SIZE * 2].copy_( | 264 | + workspace[TRANSPOSE_BF16_BLOCK_SIZE : TRANSPOSE_BF16_BLOCK_SIZE * 2].copy_( |
| 257 | - bf16_space[copy_start: copy_end]) | 265 | + bf16_space[copy_start:copy_end] |
| 258 | - shard_fp32_main_param_view[copy_start * 2: copy_end * 2].copy_( | 266 | + ) |
| 259 | - workspace_convert_view.view(2, -1).transpose(1, 0).reshape(-1).contiguous()) | 267 | + shard_fp32_main_param_view[copy_start * 2 : copy_end * 2].copy_( |
| 268 | + workspace_convert_view.view(2, -1).transpose(1, 0).reshape(-1).contiguous() | ||
| 269 | + ) | ||
| 260 | 270 | ||
| 261 | if remain > 0: | 271 | if remain > 0: |
| 262 | - workspace_convert_view = workspace[:remain * 2] | 272 | + workspace_convert_view = workspace[: remain * 2] |
| 263 | workspace[:remain].copy_(residual_space[-remain:]) | 273 | workspace[:remain].copy_(residual_space[-remain:]) |
| 264 | - workspace[remain:remain * 2].copy_(bf16_space[-remain:]) | 274 | + workspace[remain : remain * 2].copy_(bf16_space[-remain:]) |
| 265 | - shard_fp32_main_param_view[-remain * 2:].copy_( | 275 | + shard_fp32_main_param_view[-remain * 2 :].copy_( |
| 266 | - workspace_convert_view.view(2, -1).transpose(1, 0).reshape(-1).contiguous()) | 276 | + workspace_convert_view.view(2, -1).transpose(1, 0).reshape(-1).contiguous() |
| 277 | + ) | ||
| 267 | 278 | ||
| 268 | if not self.first_sub_flag and not self.npu_deterministic: | 279 | if not self.first_sub_flag and not self.npu_deterministic: |
| 269 | shard_main_param_int32_view_bucket[:param_data_dp_numel].sub_(TRANSPOSE_BF16_BIT) | 280 | shard_main_param_int32_view_bucket[:param_data_dp_numel].sub_(TRANSPOSE_BF16_BIT) |
| 270 | 281 | ||
| 271 | if not self.first_sub_flag and self.npu_deterministic: | 282 | if not self.first_sub_flag and self.npu_deterministic: |
| 272 | ConvertFp32BF16Distrib().fp16_tensor_convert_to_fp32_tensor_deterministic( | 283 | ConvertFp32BF16Distrib().fp16_tensor_convert_to_fp32_tensor_deterministic( |
| 273 | - self.shard_fp32_from_float16_groups, self.optimizer) | 284 | + self.shard_fp32_from_float16_groups, self.optimizer |
| 285 | + ) | ||
| 274 | 286 | ||
| 275 | 287 | ||
| 276 | def fp32_tensor_convert_to_fp16_tensor_dis(self): | 288 | def fp32_tensor_convert_to_fp16_tensor_dis(self): |
| @@ -288,28 +300,33 @@ def fp32_tensor_convert_to_fp16_tensor_dis(self): | |||
| 288 | if data_parallel_world_size == 1: | 300 | if data_parallel_world_size == 1: |
| 289 | if self.npu_deterministic: | 301 | if self.npu_deterministic: |
| 290 | ConvertFp32BF16Distrib().fp32_tensor_convert_to_fp16_tensor_deterministic( | 302 | ConvertFp32BF16Distrib().fp32_tensor_convert_to_fp16_tensor_deterministic( |
| 291 | - self.shard_fp32_from_float16_groups, self.optimizer) | 303 | + self.shard_fp32_from_float16_groups, self.optimizer |
| 304 | + ) | ||
| 292 | else: | 305 | else: |
| 293 | for shard_res_and_buffer_model_param in self.shard_main_param_res_buffers: | 306 | for shard_res_and_buffer_model_param in self.shard_main_param_res_buffers: |
| 294 | shard_main_param_int32_view_buffer = self.model_param_bucket_and_shard_main_param_int32_view_map[ | 307 | shard_main_param_int32_view_buffer = self.model_param_bucket_and_shard_main_param_int32_view_map[ |
| 295 | - shard_res_and_buffer_model_param] | 308 | + shard_res_and_buffer_model_param |
| 309 | + ] | ||
| 296 | shard_main_param_int32_view_buffer.add_(TRANSPOSE_BF16_BIT) | 310 | shard_main_param_int32_view_buffer.add_(TRANSPOSE_BF16_BIT) |
| 297 | self.first_sub_flag = False | 311 | self.first_sub_flag = False |
| 298 | 312 | ||
| 299 | for shard_fp32_param_fp16_view in self.shard_fp32_param_fp16_view_group: | 313 | for shard_fp32_param_fp16_view in self.shard_fp32_param_fp16_view_group: |
| 300 | shard_fp32_param_fp16_view.copy_( | 314 | shard_fp32_param_fp16_view.copy_( |
| 301 | - shard_fp32_param_fp16_view.view(-1, 2).transpose(1, 0).reshape(-1).contiguous()) | 315 | + shard_fp32_param_fp16_view.view(-1, 2).transpose(1, 0).reshape(-1).contiguous() |
| 316 | + ) | ||
| 302 | else: | 317 | else: |
| 303 | if self.npu_deterministic: | 318 | if self.npu_deterministic: |
| 304 | ConvertFp32BF16Distrib().fp32_tensor_convert_to_fp16_tensor_deterministic( | 319 | ConvertFp32BF16Distrib().fp32_tensor_convert_to_fp16_tensor_deterministic( |
| 305 | - self.shard_fp32_from_float16_groups, self.optimizer) | 320 | + self.shard_fp32_from_float16_groups, self.optimizer |
| 321 | + ) | ||
| 306 | else: | 322 | else: |
| 307 | for buffer in self.buffers: | 323 | for buffer in self.buffers: |
| 308 | for bucket in buffer.buckets: | 324 | for bucket in buffer.buckets: |
| 309 | bucket_param_data = bucket.param_data | 325 | bucket_param_data = bucket.param_data |
| 310 | param_data_dp_numel = bucket_param_data.numel() // data_parallel_world_size | 326 | param_data_dp_numel = bucket_param_data.numel() // data_parallel_world_size |
| 311 | shard_main_param_int32_view_bucket = self.model_param_bucket_and_shard_main_param_int32_view_map[ | 327 | shard_main_param_int32_view_bucket = self.model_param_bucket_and_shard_main_param_int32_view_map[ |
| 312 | - bucket_param_data] | 328 | + bucket_param_data |
| 329 | + ] | ||
| 313 | shard_main_param_int32_view_bucket[:param_data_dp_numel].add_(TRANSPOSE_BF16_BIT) | 330 | shard_main_param_int32_view_bucket[:param_data_dp_numel].add_(TRANSPOSE_BF16_BIT) |
| 314 | 331 | ||
| 315 | for buffer in self.buffers: | 332 | for buffer in self.buffers: |
| @@ -320,35 +337,41 @@ def fp32_tensor_convert_to_fp16_tensor_dis(self): | |||
| 320 | bucket_res = self.model_param_bucket_and_res_map[bucket_param_data] | 337 | bucket_res = self.model_param_bucket_and_res_map[bucket_param_data] |
| 321 | bucket_res_position = max(0, data_parallel_rank - 1) * param_data_dp_numel | 338 | bucket_res_position = max(0, data_parallel_rank - 1) * param_data_dp_numel |
| 322 | shard_fp32_main_param_view = bucket_param_data[ | 339 | shard_fp32_main_param_view = bucket_param_data[ |
| 323 | - bucket_res_position: bucket_res_position + param_data_dp_numel * 2] | 340 | + bucket_res_position : bucket_res_position + param_data_dp_numel * 2 |
| 341 | + ] | ||
| 324 | 342 | ||
| 325 | loops = param_data_dp_numel // TRANSPOSE_BF16_BLOCK_SIZE | 343 | loops = param_data_dp_numel // TRANSPOSE_BF16_BLOCK_SIZE |
| 326 | remain = param_data_dp_numel % TRANSPOSE_BF16_BLOCK_SIZE | 344 | remain = param_data_dp_numel % TRANSPOSE_BF16_BLOCK_SIZE |
| 327 | - workspace = torch.zeros( | 345 | + workspace = torch.zeros(TRANSPOSE_BF16_BLOCK_SIZE * 2, dtype=torch.bfloat16, device=bucket_res.device) |
| 328 | - TRANSPOSE_BF16_BLOCK_SIZE * 2, dtype=torch.bfloat16, device=bucket_res.device) | ||
| 329 | bf16_space_dp_rank = max(0, data_parallel_rank - 1) | 346 | bf16_space_dp_rank = max(0, data_parallel_rank - 1) |
| 330 | residual_space = bucket_res | 347 | residual_space = bucket_res |
| 331 | bf16_space = bucket_param_data[ | 348 | bf16_space = bucket_param_data[ |
| 332 | - param_data_dp_numel * bf16_space_dp_rank:param_data_dp_numel * (bf16_space_dp_rank + 1)] | 349 | + param_data_dp_numel * bf16_space_dp_rank : param_data_dp_numel * (bf16_space_dp_rank + 1) |
| 350 | + ] | ||
| 333 | 351 | ||
| 334 | for loop in range(loops): | 352 | for loop in range(loops): |
| 335 | - workspace_convert_view = workspace[:TRANSPOSE_BF16_BLOCK_SIZE * 2] | 353 | + workspace_convert_view = workspace[: TRANSPOSE_BF16_BLOCK_SIZE * 2] |
| 336 | workspace_convert_view.copy_( | 354 | workspace_convert_view.copy_( |
| 337 | shard_fp32_main_param_view[ | 355 | shard_fp32_main_param_view[ |
| 338 | - loop * TRANSPOSE_BF16_BLOCK_SIZE * 2: (loop + 1) * TRANSPOSE_BF16_BLOCK_SIZE * 2]) | 356 | + loop * TRANSPOSE_BF16_BLOCK_SIZE * 2 : (loop + 1) * TRANSPOSE_BF16_BLOCK_SIZE * 2 |
| 357 | + ] | ||
| 358 | + ) | ||
| 339 | temp = workspace_convert_view.view(-1, 2).transpose(1, 0).reshape(-1).contiguous() | 359 | temp = workspace_convert_view.view(-1, 2).transpose(1, 0).reshape(-1).contiguous() |
| 340 | - residual_space[loop * TRANSPOSE_BF16_BLOCK_SIZE: (loop + 1) * TRANSPOSE_BF16_BLOCK_SIZE].copy_( | 360 | + residual_space[loop * TRANSPOSE_BF16_BLOCK_SIZE : (loop + 1) * TRANSPOSE_BF16_BLOCK_SIZE].copy_( |
| 341 | - temp[:TRANSPOSE_BF16_BLOCK_SIZE]) | 361 | + temp[:TRANSPOSE_BF16_BLOCK_SIZE] |
| 342 | - bf16_space[loop * TRANSPOSE_BF16_BLOCK_SIZE: (loop + 1) * TRANSPOSE_BF16_BLOCK_SIZE].copy_( | 362 | + ) |
| 343 | - temp[TRANSPOSE_BF16_BLOCK_SIZE: TRANSPOSE_BF16_BLOCK_SIZE * 2]) | 363 | + bf16_space[loop * TRANSPOSE_BF16_BLOCK_SIZE : (loop + 1) * TRANSPOSE_BF16_BLOCK_SIZE].copy_( |
| 364 | + temp[TRANSPOSE_BF16_BLOCK_SIZE : TRANSPOSE_BF16_BLOCK_SIZE * 2] | ||
| 365 | + ) | ||
| 344 | 366 | ||
| 345 | if remain > 0: | 367 | if remain > 0: |
| 346 | - workspace_convert_view = workspace[:remain * 2] | 368 | + workspace_convert_view = workspace[: remain * 2] |
| 347 | - workspace_convert_view.copy_(shard_fp32_main_param_view[-remain * 2:]) | 369 | + workspace_convert_view.copy_(shard_fp32_main_param_view[-remain * 2 :]) |
| 348 | temp = workspace_convert_view.view(-1, 2).transpose(1, 0).reshape(-1).contiguous() | 370 | temp = workspace_convert_view.view(-1, 2).transpose(1, 0).reshape(-1).contiguous() |
| 349 | residual_space[-remain:].copy_(temp[:remain]) | 371 | residual_space[-remain:].copy_(temp[:remain]) |
| 350 | - bf16_space[-remain:].copy_(temp[remain: remain * 2]) | 372 | + bf16_space[-remain:].copy_(temp[remain : remain * 2]) |
| 351 | 373 | ||
| 352 | if data_parallel_rank != 0: | 374 | if data_parallel_rank != 0: |
| 353 | - shard_fp32_main_param_view[param_data_dp_numel:param_data_dp_numel * 2].copy_( | 375 | + shard_fp32_main_param_view[param_data_dp_numel : param_data_dp_numel * 2].copy_( |
| 354 | - shard_fp32_main_param_view[:param_data_dp_numel]) | 376 | + shard_fp32_main_param_view[:param_data_dp_numel] |
| 377 | + ) | ||
| @@ -1,25 +1,15 @@ | |||
| 1 | -import os | ||
| 2 | -import types | ||
| 3 | -from functools import wraps | ||
| 4 | - | ||
| 5 | import torch | 1 | import torch |
| 6 | 2 | ||
| 7 | TRANSPOSE_BF16_BIT = 32768 | 3 | TRANSPOSE_BF16_BIT = 32768 |
| 8 | 4 | ||
| 9 | 5 | ||
| 10 | -def _copy_model_params_to_main_params(): | 6 | +def _copy_model_params_to_main_params(state_dict=None): |
| 11 | - pass | 7 | + if state_dict is not None: |
| 8 | + raise NotImplementedError("Initialize main params from state dict is not supported with reuse-fp32-param") | ||
| 12 | 9 | ||
| 13 | 10 | ||
| 14 | class ConvertFp32BF16: | 11 | class ConvertFp32BF16: |
| 15 | - def init_and_reuse_storage_of_tensors( | 12 | + def init_and_reuse_storage_of_tensors(self, fp32_tensor, bf16_fp32_tensor, res_tensor, bf16_tensor, int32_tensor): |
| 16 | - self, | ||
| 17 | - fp32_tensor, | ||
| 18 | - bf16_fp32_tensor, | ||
| 19 | - res_tensor, | ||
| 20 | - bf16_tensor, | ||
| 21 | - int32_tensor | ||
| 22 | - ): | ||
| 23 | """ | 13 | """ |
| 24 | init a list of tensor with length of 2*fp32_tensor.numel() in bf16 to share the same storage. | 14 | init a list of tensor with length of 2*fp32_tensor.numel() in bf16 to share the same storage. |
| 25 | Args: | 15 | Args: |
| @@ -32,6 +22,7 @@ class ConvertFp32BF16: | |||
| 32 | int32_tensors: a list of int32 tensors share the same storages with original list of fp32 tensors. | 22 | int32_tensors: a list of int32 tensors share the same storages with original list of fp32 tensors. |
| 33 | """ | 23 | """ |
| 34 | from mindspeed.op_builder import AlgorithmOpBuilder | 24 | from mindspeed.op_builder import AlgorithmOpBuilder |
| 25 | + | ||
| 35 | reuse_data_ptr = AlgorithmOpBuilder().load().reuse_data_ptr | 26 | reuse_data_ptr = AlgorithmOpBuilder().load().reuse_data_ptr |
| 36 | reuse_data_ptr(bf16_fp32_tensor, fp32_tensor, 0) | 27 | reuse_data_ptr(bf16_fp32_tensor, fp32_tensor, 0) |
| 37 | reuse_data_ptr(int32_tensor, fp32_tensor, 0) | 28 | reuse_data_ptr(int32_tensor, fp32_tensor, 0) |
| @@ -41,22 +32,26 @@ class ConvertFp32BF16: | |||
| 41 | 32 | ||
| 42 | def fp16_tensor_convert_to_fp32_tensor_deterministic(self, ctx): | 33 | def fp16_tensor_convert_to_fp32_tensor_deterministic(self, ctx): |
| 43 | for int32_float32_group, float16_param_group, fp32_from_float16_group in zip( | 34 | for int32_float32_group, float16_param_group, fp32_from_float16_group in zip( |
| 44 | - ctx.int32_float32_groups, ctx.float16_float32_groups, ctx.fp32_from_float16_groups): | 35 | + ctx.int32_float32_groups, ctx.float16_float32_groups, ctx.fp32_from_float16_groups |
| 45 | - self.bf16_tensors_to_fp32_tensors_deterministic(int32_float32_group, float16_param_group, fp32_from_float16_group, ctx.optimizer) | 36 | + ): |
| 37 | + self.bf16_tensors_to_fp32_tensors_deterministic( | ||
| 38 | + int32_float32_group, float16_param_group, fp32_from_float16_group, ctx.optimizer | ||
| 39 | + ) | ||
| 46 | 40 | ||
| 47 | def fp32_tensor_convert_to_fp16_tensor_deterministic(self, ctx): | 41 | def fp32_tensor_convert_to_fp16_tensor_deterministic(self, ctx): |
| 48 | for int32_float32_param_group, float16_param_group, fp32_from_float16_group in zip( | 42 | for int32_float32_param_group, float16_param_group, fp32_from_float16_group in zip( |
| 49 | - ctx.int32_float32_groups, ctx.float16_float32_groups, ctx.fp32_from_float16_groups): | 43 | + ctx.int32_float32_groups, ctx.float16_float32_groups, ctx.fp32_from_float16_groups |
| 50 | - self.fp32_tensors_to_bf16_tensors_deterministic(int32_float32_param_group, float16_param_group, fp32_from_float16_group, ctx.optimizer) | 44 | + ): |
| 45 | + self.fp32_tensors_to_bf16_tensors_deterministic( | ||
| 46 | + int32_float32_param_group, float16_param_group, fp32_from_float16_group, ctx.optimizer | ||
| 47 | + ) | ||
| 51 | 48 | ||
| 52 | def fp16_tensor_convert_to_fp32_tensor(self, ctx): | 49 | def fp16_tensor_convert_to_fp32_tensor(self, ctx): |
| 53 | - for int32_float32_group, float16_param_group in zip( | 50 | + for int32_float32_group, float16_param_group in zip(ctx.int32_float32_groups, ctx.float16_float32_groups): |
| 54 | - ctx.int32_float32_groups, ctx.float16_float32_groups): | ||
| 55 | self.bf16_tensors_to_fp32_tensors(int32_float32_group, float16_param_group) | 51 | self.bf16_tensors_to_fp32_tensors(int32_float32_group, float16_param_group) |
| 56 | 52 | ||
| 57 | def fp32_tensor_convert_to_fp16_tensor(self, ctx): | 53 | def fp32_tensor_convert_to_fp16_tensor(self, ctx): |
| 58 | - for int32_float32_param_group, float16_param_group in zip( | 54 | + for int32_float32_param_group, float16_param_group in zip(ctx.int32_float32_groups, ctx.float16_float32_groups): |
| 59 | - ctx.int32_float32_groups, ctx.float16_float32_groups): | ||
| 60 | self.fp32_tensors_to_bf16_tensors(int32_float32_param_group, float16_param_group) | 55 | self.fp32_tensors_to_bf16_tensors(int32_float32_param_group, float16_param_group) |
| 61 | 56 | ||
| 62 | def fp32_tensors_to_bf16_tensors(self, int32_tensors, bf16_fp32_tensors): | 57 | def fp32_tensors_to_bf16_tensors(self, int32_tensors, bf16_fp32_tensors): |
| @@ -71,7 +66,7 @@ class ConvertFp32BF16: | |||
| 71 | """ | 66 | """ |
| 72 | for int32_tensor, bf16_fp32_tensor in zip(int32_tensors, bf16_fp32_tensors): | 67 | for int32_tensor, bf16_fp32_tensor in zip(int32_tensors, bf16_fp32_tensors): |
| 73 | if bf16_fp32_tensor.numel() == 0: | 68 | if bf16_fp32_tensor.numel() == 0: |
| 74 | - return | 69 | + return |
| 75 | int32_tensor.add_(TRANSPOSE_BF16_BIT) | 70 | int32_tensor.add_(TRANSPOSE_BF16_BIT) |
| 76 | bf16_fp32_tensor.copy_(bf16_fp32_tensor.view(-1, 2).transpose(1, 0).reshape(-1).contiguous()) | 71 | bf16_fp32_tensor.copy_(bf16_fp32_tensor.view(-1, 2).transpose(1, 0).reshape(-1).contiguous()) |
| 77 | 72 | ||
| @@ -94,7 +89,7 @@ class ConvertFp32BF16: | |||
| 94 | def fp32_tensors_to_bf16_tensors_deterministic(self, int32_tensors, bf16_fp32_tensors, fp32_tensors, optimizer): | 89 | def fp32_tensors_to_bf16_tensors_deterministic(self, int32_tensors, bf16_fp32_tensors, fp32_tensors, optimizer): |
| 95 | for int32_tensor, bf16_fp32_tensor, fp32_tensor in zip(int32_tensors, bf16_fp32_tensors, fp32_tensors): | 90 | for int32_tensor, bf16_fp32_tensor, fp32_tensor in zip(int32_tensors, bf16_fp32_tensors, fp32_tensors): |
| 96 | if bf16_fp32_tensor.numel() == 0: | 91 | if bf16_fp32_tensor.numel() == 0: |
| 97 | - return | 92 | + return |
| 98 | odd_even_tensor = ((int32_tensor & 131071) == TRANSPOSE_BF16_BIT).int() | 93 | odd_even_tensor = ((int32_tensor & 131071) == TRANSPOSE_BF16_BIT).int() |
| 99 | int32_tensor.add_(TRANSPOSE_BF16_BIT) | 94 | int32_tensor.add_(TRANSPOSE_BF16_BIT) |
| 100 | self.optimizer_exp_avg_save_sign(optimizer, fp32_tensor, int32_tensor, odd_even_tensor) | 95 | self.optimizer_exp_avg_save_sign(optimizer, fp32_tensor, int32_tensor, odd_even_tensor) |
| @@ -3,11 +3,58 @@ | |||
| 3 | from functools import wraps, partial | 3 | from functools import wraps, partial |
| 4 | 4 | ||
| 5 | import inspect | 5 | import inspect |
| 6 | -import torch | 6 | + |
| 7 | + | ||
| 8 | +def _get_optimizer_bucket_groups(model_chunk, optimizer_buckets): | ||
| 9 | + """Select complete DDP bucket groups owned by the current optimizer.""" | ||
| 10 | + optimizer_bucket_groups = [] | ||
| 11 | + for bucket_group in model_chunk.bucket_groups + model_chunk.expert_parallel_bucket_groups: | ||
| 12 | + num_owned_buckets = 0 | ||
| 13 | + for bucket in bucket_group.buckets: | ||
| 14 | + if bucket in optimizer_buckets: | ||
| 15 | + num_owned_buckets += 1 | ||
| 16 | + | ||
| 17 | + # Skip empty groups and groups owned by another optimizer. | ||
| 18 | + if num_owned_buckets == 0: | ||
| 19 | + continue | ||
| 20 | + if num_owned_buckets != len(bucket_group.buckets): | ||
| 21 | + raise RuntimeError("A parameter all-gather bucket group spans multiple distributed optimizers") | ||
| 22 | + | ||
| 23 | + optimizer_bucket_groups.append(bucket_group) | ||
| 24 | + | ||
| 25 | + return optimizer_bucket_groups | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +def start_param_sync_for_bucket_group_subset(self) -> None: | ||
| 29 | + """Sync only the DDP buckets owned by this distributed optimizer. | ||
| 30 | + | ||
| 31 | + Dense and expert optimizers share model chunks, but receive different | ||
| 32 | + buffers. Use bucket identity instead of the position in ChainedOptimizer | ||
| 33 | + so virtual pipeline chunks and grouped buffers keep their ownership. | ||
| 34 | + """ | ||
| 35 | + if self.is_stub_optimizer: | ||
| 36 | + return | ||
| 37 | + | ||
| 38 | + from megatron.core.optimizer.layer_wise_optimizer import _bucket_is_managed_by_layer_wise_optimizer | ||
| 39 | + | ||
| 40 | + # MCore buckets use object identity for equality and hashing. | ||
| 41 | + optimizer_buckets = set() | ||
| 42 | + for buffer in self.buffers: | ||
| 43 | + optimizer_buckets.update(buffer.buckets) | ||
| 44 | + | ||
| 45 | + for model_chunk in self.model_chunks: | ||
| 46 | + bucket_groups = _get_optimizer_bucket_groups(model_chunk, optimizer_buckets) | ||
| 47 | + for bucket_group in bucket_groups: | ||
| 48 | + if _bucket_is_managed_by_layer_wise_optimizer(bucket_group.buckets[0], default_for_untagged=False): | ||
| 49 | + continue | ||
| 50 | + # Keep MCore's post-all-gather processing, including quantized weights. | ||
| 51 | + model_chunk._start_bucket_group_param_sync(bucket_group, force_sync=False) | ||
| 7 | 52 | ||
| 8 | 53 | ||
| 9 | # fix duplicate all-gather | 54 | # fix duplicate all-gather |
| 10 | -def start_param_sync(self, *unused, force_sync: bool = False, force_dispatch: bool = False, dense_or_moe_group: str = None): | 55 | +def start_param_sync( |
| 56 | + self, *unused, force_sync: bool = False, force_dispatch: bool = False, dense_or_moe_group: str = None | ||
| 57 | +): | ||
| 11 | """ | 58 | """ |
| 12 | Initiates param sync (all-gather) communication operations for all model parameters. | 59 | Initiates param sync (all-gather) communication operations for all model parameters. |
| 13 | 60 | ||
| @@ -32,6 +79,8 @@ def start_param_sync(self, *unused, force_sync: bool = False, force_dispatch: bo | |||
| 32 | bucket_groups = self.bucket_groups | 79 | bucket_groups = self.bucket_groups |
| 33 | elif dense_or_moe_group == 'moe': | 80 | elif dense_or_moe_group == 'moe': |
| 34 | bucket_groups = self.expert_parallel_bucket_groups | 81 | bucket_groups = self.expert_parallel_bucket_groups |
| 82 | + else: | ||
| 83 | + raise ValueError(f'Unsupported dense_or_moe_group: {dense_or_moe_group!r}') | ||
| 35 | 84 | ||
| 36 | for bucket_group in bucket_groups: | 85 | for bucket_group in bucket_groups: |
| 37 | bucket_group.start_param_sync(force_sync=force_sync) | 86 | bucket_group.start_param_sync(force_sync=force_sync) |
| @@ -57,13 +106,13 @@ def step_with_ready_grads_distrib_opti_wrapper(func): | |||
| 57 | model_chunk.start_param_sync = model_chunk.start_param_sync.func | 106 | model_chunk.start_param_sync = model_chunk.start_param_sync.func |
| 58 | 107 | ||
| 59 | return update_successful | 108 | return update_successful |
| 109 | + | ||
| 60 | return wrapper | 110 | return wrapper |
| 61 | 111 | ||
| 62 | 112 | ||
| 63 | def get_megatron_optimizer_wrapper(func): | 113 | def get_megatron_optimizer_wrapper(func): |
| 64 | @wraps(func) | 114 | @wraps(func) |
| 65 | def wrapper(*args, **kwargs): | 115 | def wrapper(*args, **kwargs): |
| 66 | - | ||
| 67 | chained_optimizer = func(*args, **kwargs) | 116 | chained_optimizer = func(*args, **kwargs) |
| 68 | 117 | ||
| 69 | if hasattr(chained_optimizer, 'chained_optimizers'): | 118 | if hasattr(chained_optimizer, 'chained_optimizers'): |
| @@ -73,7 +122,7 @@ def get_megatron_optimizer_wrapper(func): | |||
| 73 | model_chunks = args[1] | 122 | model_chunks = args[1] |
| 74 | else: | 123 | else: |
| 75 | return chained_optimizer | 124 | return chained_optimizer |
| 76 | - | 125 | + |
| 77 | for optimizer in chained_optimizer.chained_optimizers: | 126 | for optimizer in chained_optimizer.chained_optimizers: |
| 78 | optimizer.is_moe_param = 'dense' | 127 | optimizer.is_moe_param = 'dense' |
| 79 | 128 | ||
| @@ -90,7 +139,6 @@ def get_megatron_optimizer_wrapper(func): | |||
| 90 | ddp_config.use_custom_fsdp | 139 | ddp_config.use_custom_fsdp |
| 91 | and ddp_config.data_parallel_sharding_strategy == "optim_grads_params" | 140 | and ddp_config.data_parallel_sharding_strategy == "optim_grads_params" |
| 92 | ): | 141 | ): |
| 93 | - param_shard = param | ||
| 94 | param = param.orig_param | 142 | param = param.orig_param |
| 95 | 143 | ||
| 96 | if not param.requires_grad: | 144 | if not param.requires_grad: |
| @@ -106,4 +154,5 @@ def get_megatron_optimizer_wrapper(func): | |||
| 106 | chained_optimizer.chained_optimizers[-1].is_moe_param = 'moe' | 154 | chained_optimizer.chained_optimizers[-1].is_moe_param = 'moe' |
| 107 | 155 | ||
| 108 | return chained_optimizer | 156 | return chained_optimizer |
| 157 | + | ||
| 109 | return wrapper | 158 | return wrapper |
| @@ -358,8 +358,9 @@ def reuse_fp32_param_init_wrapper(init_func): | |||
| 358 | return reuse_fp32_param_init | 358 | return reuse_fp32_param_init |
| 359 | 359 | ||
| 360 | 360 | ||
| 361 | -def _copy_model_params_to_main_params(): | 361 | +def _copy_model_params_to_main_params(state_dict=None): |
| 362 | - pass | 362 | + if state_dict is not None: |
| 363 | + raise NotImplementedError("Initialize main params from state dict is not supported with quant optimizer") | ||
| 363 | 364 | ||
| 364 | 365 | ||
| 365 | def init_and_reuse_storage_of_tensors(fp32_tensor, bf16_fp32_tensor, res_tensor, bf16_tensor, int32_tensor): | 366 | def init_and_reuse_storage_of_tensors(fp32_tensor, bf16_fp32_tensor, res_tensor, bf16_tensor, int32_tensor): |
| @@ -0,0 +1,124 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | + | ||
| 3 | +"""Own asynchronous forward sends while Megatron pseudo-deallocates its outputs.""" | ||
| 4 | + | ||
| 5 | +from contextvars import ContextVar | ||
| 6 | +from functools import wraps | ||
| 7 | + | ||
| 8 | +import torch | ||
| 9 | + | ||
| 10 | +from mindspeed.args_utils import get_full_args | ||
| 11 | + | ||
| 12 | +_ACTIVE_SENDS = ContextVar("mindspeed_deferred_p2p_sends", default=None) | ||
| 13 | +# A failed device/communication wait cannot establish safe reclamation. Keep the | ||
| 14 | +# affected storage alive until process exit, and propagate the failure to training. | ||
| 15 | +_FAILED_SENDS = [] | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +class _PendingSend: | ||
| 19 | + def __init__(self, tensor): | ||
| 20 | + # A Python reference to the original Tensor is insufficient: Megatron | ||
| 21 | + # replaces its .data. detach() gives us independent Tensor metadata while | ||
| 22 | + # retaining the original storage, without a payload copy or autograd graph. | ||
| 23 | + self.tensor = tensor.detach() | ||
| 24 | + self.work = None | ||
| 25 | + | ||
| 26 | + def finish(self): | ||
| 27 | + device = self.tensor.device | ||
| 28 | + if self.work is None: | ||
| 29 | + # Submission raised before returning a Work (possibly after enqueueing | ||
| 30 | + # a send). Only this exceptional path needs a device synchronization. | ||
| 31 | + torch.npu.synchronize(device) | ||
| 32 | + else: | ||
| 33 | + with torch.npu.device(device): | ||
| 34 | + stream = torch.npu.current_stream(device) | ||
| 35 | + if self.work.wait() is False: | ||
| 36 | + raise RuntimeError("Deferred P2P send did not complete successfully") | ||
| 37 | + # HCCL Work.wait() may only enqueue an event dependency on the | ||
| 38 | + # current stream. Protect the storage past the HOST return, even | ||
| 39 | + # when it was originally allocated on another stream. | ||
| 40 | + self.tensor.record_stream(stream) | ||
| 41 | + self.tensor = None | ||
| 42 | + self.work = None | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +class _DeferredSends: | ||
| 46 | + def __init__(self): | ||
| 47 | + self.pending = [] | ||
| 48 | + | ||
| 49 | + def begin(self, tensor): | ||
| 50 | + entry = _PendingSend(tensor) | ||
| 51 | + # Take ownership BEFORE native submission, including its exception path. | ||
| 52 | + self.pending.append(entry) | ||
| 53 | + return entry | ||
| 54 | + | ||
| 55 | + def retire_previous(self): | ||
| 56 | + # Submit the current send first, then wait for the previous one, restoring | ||
| 57 | + # the old interleaved schedule's ordering. Keep the current source alive. | ||
| 58 | + while len(self.pending) > 1: | ||
| 59 | + self.pending[0].finish() | ||
| 60 | + self.pending.pop(0) | ||
| 61 | + | ||
| 62 | + def close(self): | ||
| 63 | + try: | ||
| 64 | + while self.pending: | ||
| 65 | + self.pending[0].finish() | ||
| 66 | + self.pending.pop(0) | ||
| 67 | + except BaseException: | ||
| 68 | + _FAILED_SENDS.extend(self.pending) | ||
| 69 | + self.pending.clear() | ||
| 70 | + raise | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +def forward_backward_pipelining_with_interleaving_wrapper(schedule): | ||
| 74 | + """Drain owned sends on normal return, forward-only return and exceptions.""" | ||
| 75 | + | ||
| 76 | + @wraps(schedule) | ||
| 77 | + def wrapper(*args, **kwargs): | ||
| 78 | + # Patches are installed before full argument validation. Read its result | ||
| 79 | + # once per schedule invocation, rather than on every microbatch/send. | ||
| 80 | + if not getattr(get_full_args(), "defer_p2p_send_wait", False): | ||
| 81 | + return schedule(*args, **kwargs) | ||
| 82 | + sends = _DeferredSends() | ||
| 83 | + token = _ACTIVE_SENDS.set(sends) | ||
| 84 | + try: | ||
| 85 | + return schedule(*args, **kwargs) | ||
| 86 | + finally: | ||
| 87 | + try: | ||
| 88 | + sends.close() | ||
| 89 | + finally: | ||
| 90 | + _ACTIVE_SENDS.reset(token) | ||
| 91 | + | ||
| 92 | + return wrapper | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +def send_forward_recv_forward_wrapper(send_forward_recv_forward): | ||
| 96 | + """Transfer ownership of send_next from the schedule to its scoped manager.""" | ||
| 97 | + | ||
| 98 | + @wraps(send_forward_recv_forward) | ||
| 99 | + def wrapper(self, output_tensor, recv_prev, tensor_shape, overlap_p2p_comm=False): | ||
| 100 | + sends = _ACTIVE_SENDS.get() | ||
| 101 | + # Preserve short-circuit order before accessing optional tensor metadata. | ||
| 102 | + if ( | ||
| 103 | + sends is None # pylint: disable=too-many-boolean-expressions | ||
| 104 | + or not overlap_p2p_comm | ||
| 105 | + or output_tensor is None | ||
| 106 | + or not self.config.deallocate_pipeline_outputs | ||
| 107 | + or self.config.batch_p2p_comm | ||
| 108 | + or not isinstance(output_tensor, torch.Tensor) | ||
| 109 | + or output_tensor.device.type != "npu" | ||
| 110 | + ): | ||
| 111 | + return send_forward_recv_forward(self, output_tensor, recv_prev, tensor_shape, overlap_p2p_comm) | ||
| 112 | + entry = sends.begin(output_tensor) | ||
| 113 | + input_tensor, handles = send_forward_recv_forward(self, entry.tensor, recv_prev, tensor_shape, overlap_p2p_comm) | ||
| 114 | + if not isinstance(handles, dict) or handles.get("send_next") is None: | ||
| 115 | + raise RuntimeError("Deferred P2P send requires Megatron 0.18 send_next Work handles") | ||
| 116 | + entry.work = handles["send_next"] | ||
| 117 | + sends.retire_previous() | ||
| 118 | + # The schedule must still wait on all receives. Only the owned send is | ||
| 119 | + # removed, so Megatron's immediate pre-deallocation wait has no send Work. | ||
| 120 | + remaining_handles = dict(handles) | ||
| 121 | + del remaining_handles["send_next"] | ||
| 122 | + return input_tensor, remaining_handles | ||
| 123 | + | ||
| 124 | + return wrapper | ||
| @@ -44,6 +44,8 @@ try: | |||
| 44 | except ImportError: | 44 | except ImportError: |
| 45 | HAVE_FSDP2 = False | 45 | HAVE_FSDP2 = False |
| 46 | 46 | ||
| 47 | +from megatron_adaptor.patches.megatron.profile import profile_step | ||
| 48 | + | ||
| 47 | from mindspeed.args_utils import get_full_args as get_args | 49 | from mindspeed.args_utils import get_full_args as get_args |
| 48 | from mindspeed.core.pipeline_parallel.dualpipev.dualpipev_schedules import get_dualpipe_chunk | 50 | from mindspeed.core.pipeline_parallel.dualpipev.dualpipev_schedules import get_dualpipe_chunk |
| 49 | from mindspeed.core.pipeline_parallel.dualpipev.mtp_utils import model_provider_mtp | 51 | from mindspeed.core.pipeline_parallel.dualpipev.mtp_utils import model_provider_mtp |
| @@ -586,6 +588,10 @@ def train_step( | |||
| 586 | if args.empty_unused_memory_level >= 2: | 588 | if args.empty_unused_memory_level >= 2: |
| 587 | torch.cuda.empty_cache() | 589 | torch.cuda.empty_cache() |
| 588 | 590 | ||
| 591 | + # Full replacement of train_step shadows the profile feature's wrapper on | ||
| 592 | + # the same target; drive the profiler explicitly. | ||
| 593 | + profile_step() | ||
| 594 | + | ||
| 589 | dualpipevlaststage = mpu.is_pipeline_first_stage(ignore_virtual=True) | 595 | dualpipevlaststage = mpu.is_pipeline_first_stage(ignore_virtual=True) |
| 590 | if dualpipevlaststage: | 596 | if dualpipevlaststage: |
| 591 | # Average loss across microbatches. | 597 | # Average loss across microbatches. |
| @@ -1,6 +1,7 @@ | |||
| 1 | # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. | 1 | # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. |
| 2 | # Copyright (c) 2025, Huawei Technologies Co., Ltd. All rights reserved. | 2 | # Copyright (c) 2025, Huawei Technologies Co., Ltd. All rights reserved. |
| 3 | import logging | 3 | import logging |
| 4 | +from functools import wraps | ||
| 4 | 5 | ||
| 5 | import torch | 6 | import torch |
| 6 | 7 | ||
| @@ -204,6 +205,23 @@ def model_provider_mtp(pre_process=True, post_process=True, use_dualpipe_mtp=Fal | |||
| 204 | return model | 205 | return model |
| 205 | 206 | ||
| 206 | 207 | ||
| 208 | +def dualpipev_mtp_on_this_rank_wrapper(mtp_on_this_rank): | ||
| 209 | + """Place MTP on DualPipeV's first PP stage, where the return chunk ends.""" | ||
| 210 | + | ||
| 211 | + @wraps(mtp_on_this_rank) | ||
| 212 | + def wrapper(layout=None, mtp_num_layers=None, ignore_virtual=True, vp_stage=None): | ||
| 213 | + if getattr(get_args(), 'schedules_method', None) != 'dualpipev': | ||
| 214 | + return mtp_on_this_rank( | ||
| 215 | + layout=layout, mtp_num_layers=mtp_num_layers, ignore_virtual=ignore_virtual, vp_stage=vp_stage | ||
| 216 | + ) | ||
| 217 | + # The model provider supplies an MTP spec only to the return chunk. | ||
| 218 | + # GPTModel additionally checks this rank predicate in Megatron 0.18; | ||
| 219 | + # the native physical-last-rank check would discard that valid spec. | ||
| 220 | + return bool(mtp_num_layers) and mpu.is_pipeline_first_stage(ignore_virtual=True) | ||
| 221 | + | ||
| 222 | + return wrapper | ||
| 223 | + | ||
| 224 | + | ||
| 207 | def dualpipev_get_mtp_num_layers_to_build(config: TransformerConfig, vp_stage=None, pp_rank=None) -> int: | 225 | def dualpipev_get_mtp_num_layers_to_build(config: TransformerConfig, vp_stage=None, pp_rank=None) -> int: |
| 208 | """Get the number of MTP layers to build in dualpipeV.""" | 226 | """Get the number of MTP layers to build in dualpipeV.""" |
| 209 | # Currently, we only support put all of MTP layers on the last pipeline stage. | 227 | # Currently, we only support put all of MTP layers on the last pipeline stage. |
| @@ -360,8 +360,8 @@ def core_transformer_config_from_args_wrapper(fn): | |||
| 360 | """A decorator for transformer config.""" | 360 | """A decorator for transformer config.""" |
| 361 | 361 | ||
| 362 | @wraps(fn) | 362 | @wraps(fn) |
| 363 | - def wrapper(args): | 363 | + def wrapper(args, *positional, **kwargs): |
| 364 | - config = fn(args) | 364 | + config = fn(args, *positional, **kwargs) |
| 365 | if args.use_multiparameter_pipeline_model_parallel: | 365 | if args.use_multiparameter_pipeline_model_parallel: |
| 366 | config.deallocate_pipeline_outputs = False | 366 | config.deallocate_pipeline_outputs = False |
| 367 | return config | 367 | return config |
| @@ -1,4 +1,3 @@ | |||
| 1 | - | ||
| 2 | # Copyright (c) 2025, Huawei Technologies Co., Ltd. All rights reserved. | 1 | # Copyright (c) 2025, Huawei Technologies Co., Ltd. All rights reserved. |
| 3 | 2 | ||
| 4 | 3 | ||
| @@ -7,10 +6,9 @@ from functools import wraps | |||
| 7 | 6 | ||
| 8 | def core_transformer_config_from_args_wrapper(fn): | 7 | def core_transformer_config_from_args_wrapper(fn): |
| 9 | @wraps(fn) | 8 | @wraps(fn) |
| 10 | - def wrapper(args): | 9 | + def wrapper(args, *positional, **kwargs): |
| 11 | - config = fn(args) | 10 | + config = fn(args, *positional, **kwargs) |
| 12 | config.batch_p2p_comm = False | 11 | config.batch_p2p_comm = False |
| 13 | return config | 12 | return config |
| 14 | 13 | ||
| 15 | return wrapper | 14 | return wrapper |
| 16 | - | ||
| @@ -2,23 +2,13 @@ | |||
| 2 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | 2 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. |
| 3 | 3 | ||
| 4 | import copy | 4 | import copy |
| 5 | -import enum | ||
| 6 | import logging | 5 | import logging |
| 7 | import re | 6 | import re |
| 8 | from functools import lru_cache | 7 | from functools import lru_cache |
| 9 | from typing import Optional | 8 | from typing import Optional |
| 10 | 9 | ||
| 11 | from megatron.core import parallel_state | 10 | from megatron.core import parallel_state |
| 12 | - | 11 | +from megatron.core.transformer.enums import LayerType |
| 13 | - | ||
| 14 | -class LayerType(enum.Enum): | ||
| 15 | - """Layer type used by custom pipeline parallel layout.""" | ||
| 16 | - | ||
| 17 | - embedding = 1 | ||
| 18 | - loss = 2 | ||
| 19 | - encoder = 3 | ||
| 20 | - decoder = 4 | ||
| 21 | - mtp = 5 | ||
| 22 | 12 | ||
| 23 | 13 | ||
| 24 | logger = logging.getLogger(__name__) | 14 | logger = logging.getLogger(__name__) |
| @@ -1,42 +1,91 @@ | |||
| 1 | # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. | 1 | # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 2 | # Copyright (c) 2025, Songlin Yang, Jan Kautz, Ali Hatamizadeh. | 2 | # Copyright (c) 2025, Songlin Yang, Jan Kautz, Ali Hatamizadeh. |
| 3 | # Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved. | 3 | # Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved. |
| 4 | -"""MindSpeed GatedDeltaNet subclass. | 4 | +"""MindSpeed GatedDeltaNet subclass with a lazily selected backend. |
| 5 | - | ||
| 6 | -Inherits from Megatron-LM's ``GatedDeltaNet`` and overrides the three | ||
| 7 | -FLA-dependent paths with MindSpeed's own operators: | ||
| 8 | - | ||
| 9 | -* ``causal_conv1d`` → ``mindspeed.core.ssm.npu_causal_conv1d.causal_conv1d`` (F.conv1d) | ||
| 10 | -* ``chunk_gated_delta_rule`` → ``mindspeed.core.ssm.npu_chunk_gated_delta_rule`` (Triton pipeline) | ||
| 11 | -* ``l2norm`` → ``mindspeed.ops.triton.l2norm`` (Triton kernel + custom autograd) | ||
| 12 | 5 | ||
| 13 | All Megatron-main features — Context Parallel, THD packed sequences, | 6 | All Megatron-main features — Context Parallel, THD packed sequences, |
| 14 | selective recompute — are inherited unchanged. | 7 | selective recompute — are inherited unchanged. |
| 15 | """ | 8 | """ |
| 16 | 9 | ||
| 10 | +from functools import wraps | ||
| 11 | + | ||
| 17 | import torch | 12 | import torch |
| 18 | 13 | ||
| 19 | from megatron.core.jit import jit_fuser | 14 | from megatron.core.jit import jit_fuser |
| 15 | +import megatron.core.ssm.gated_delta_net as megatron_gdn | ||
| 20 | from megatron.core.ssm.gated_delta_net import GatedDeltaNet as _MegatronGatedDeltaNet | 16 | from megatron.core.ssm.gated_delta_net import GatedDeltaNet as _MegatronGatedDeltaNet |
| 21 | 17 | ||
| 22 | -from mindspeed.core.ssm.npu_chunk_gated_delta_rule import chunk_gated_delta_rule as _ms_chunk_gated_delta_rule | 18 | +from mindspeed.core.ssm.gdn_backend import load_gdn_operators |
| 23 | -from mindspeed.ops.triton.l2norm import l2norm as _ms_l2norm | 19 | + |
| 20 | + | ||
| 21 | +def gdn_transformer_config_post_init_wrapper(fn): | ||
| 22 | + """Bypass the variable-sequence MoE check for dense GDN configs only.""" | ||
| 23 | + | ||
| 24 | + @wraps(fn) | ||
| 25 | + def wrapper(self): | ||
| 26 | + is_dense_variable_length_gdn = ( | ||
| 27 | + getattr(self, "experimental_attention_variant", None) == "gated_delta_net" | ||
| 28 | + and getattr(self, "num_moe_experts", None) is None | ||
| 29 | + and getattr(self, "moe_token_dispatcher_type", None) == "allgather" | ||
| 30 | + and getattr(self, "variable_seq_lengths", False) | ||
| 31 | + ) | ||
| 32 | + if not is_dense_variable_length_gdn: | ||
| 33 | + return fn(self) | ||
| 34 | + | ||
| 35 | + original_variable_seq_lengths = self.variable_seq_lengths | ||
| 36 | + self.variable_seq_lengths = False | ||
| 37 | + try: | ||
| 38 | + return fn(self) | ||
| 39 | + finally: | ||
| 40 | + self.variable_seq_lengths = original_variable_seq_lengths | ||
| 41 | + | ||
| 42 | + return wrapper | ||
| 24 | 43 | ||
| 25 | 44 | ||
| 26 | class GatedDeltaNet(_MegatronGatedDeltaNet): | 45 | class GatedDeltaNet(_MegatronGatedDeltaNet): |
| 27 | """MindSpeed Gated Delta Net — inherits Megatron-main logic, overrides operators.""" | 46 | """MindSpeed Gated Delta Net — inherits Megatron-main logic, overrides operators.""" |
| 28 | 47 | ||
| 29 | def __init__(self, *args, cp_comm_type=None, **kwargs): | 48 | def __init__(self, *args, cp_comm_type=None, **kwargs): |
| 49 | + operators = load_gdn_operators() | ||
| 50 | + megatron_gdn.HAVE_FLA = True | ||
| 51 | + megatron_gdn.causal_conv1d = operators.causal_conv1d | ||
| 30 | super().__init__(*args, **kwargs) | 52 | super().__init__(*args, **kwargs) |
| 31 | - # Replace chunk_gated_delta_rule with MindSpeed's Triton version. | 53 | + self._gdn_l2norm = operators.l2norm |
| 32 | - # Megatron's __init__ sets self.gated_delta_rule = chunk_gated_delta_rule | ||
| 33 | - # (module-level name from the Megatron file). We overwrite it here. | ||
| 34 | if not self.config.deterministic_mode: | 54 | if not self.config.deterministic_mode: |
| 35 | - self.gated_delta_rule = _ms_chunk_gated_delta_rule | 55 | + self.gated_delta_rule = operators.chunk_gated_delta_rule |
| 56 | + | ||
| 57 | + def _resolve_cu_seqlens(self, cu_seqlens_padded, cu_seqlens_actual, total_seq_len, name, cp_size: int = 1): | ||
| 58 | + """Normalize MindSpeed endpoint metadata to Megatron's cu_seqlens contract.""" | ||
| 59 | + cu_seqlens = cu_seqlens_padded if cu_seqlens_padded is not None else cu_seqlens_actual | ||
| 60 | + cu_seqlens = cu_seqlens.reshape(-1) | ||
| 61 | + | ||
| 62 | + total_cu = cu_seqlens[-1].cpu().item() | ||
| 63 | + if cu_seqlens.numel() > 0 and int(cu_seqlens[0].item()) != 0 and total_cu == total_seq_len: | ||
| 64 | + cu_seqlens = torch.cat( | ||
| 65 | + [ | ||
| 66 | + torch.zeros(1, dtype=cu_seqlens.dtype, device=cu_seqlens.device), | ||
| 67 | + cu_seqlens, | ||
| 68 | + ] | ||
| 69 | + ) | ||
| 70 | + if total_cu != total_seq_len: | ||
| 71 | + raise ValueError( | ||
| 72 | + f"GDN: {name}[-1]={total_cu} does not match " | ||
| 73 | + f"total_sequence_length={total_seq_len}. " | ||
| 74 | + f"({cu_seqlens_padded=}, {cu_seqlens_actual=})." | ||
| 75 | + ) | ||
| 76 | + | ||
| 77 | + seq_lengths = cu_seqlens[1:] - cu_seqlens[:-1] | ||
| 78 | + if (seq_lengths % cp_size != 0).any(): | ||
| 79 | + raise ValueError( | ||
| 80 | + f"All per-sequence lengths in cu_seqlens must be divisible by cp_size={cp_size}, " | ||
| 81 | + f"but got lengths: {seq_lengths.tolist()}" | ||
| 82 | + ) | ||
| 83 | + | ||
| 84 | + return cu_seqlens | ||
| 36 | 85 | ||
| 37 | @jit_fuser | 86 | @jit_fuser |
| 38 | def _prepare_qkv_for_gated_delta_rule(self, qkv, gate, beta, alpha, batch, seq_len): | 87 | def _prepare_qkv_for_gated_delta_rule(self, qkv, gate, beta, alpha, batch, seq_len): |
| 39 | - """Override: use MindSpeed Triton l2norm instead of FLA l2norm.""" | 88 | + """Override: use the selected backend's l2norm operator instead of FLA's.""" |
| 40 | query_key, value = torch.split( | 89 | query_key, value = torch.split( |
| 41 | qkv, | 90 | qkv, |
| 42 | [2 * self.qk_dim_local_tp // self.cp_size, self.v_dim_local_tp // self.cp_size], | 91 | [2 * self.qk_dim_local_tp // self.cp_size, self.v_dim_local_tp // self.cp_size], |
| @@ -46,7 +95,7 @@ class GatedDeltaNet(_MegatronGatedDeltaNet): | |||
| 46 | value = value.reshape(batch, seq_len, -1, self.value_head_dim) | 95 | value = value.reshape(batch, seq_len, -1, self.value_head_dim) |
| 47 | 96 | ||
| 48 | if self.use_qk_l2norm: | 97 | if self.use_qk_l2norm: |
| 49 | - query_key = _ms_l2norm(query_key.contiguous()) | 98 | + query_key = self._gdn_l2norm(query_key.contiguous()) |
| 50 | 99 | ||
| 51 | split_size = self.qk_dim_local_tp // self.key_head_dim // self.cp_size | 100 | split_size = self.qk_dim_local_tp // self.key_head_dim // self.cp_size |
| 52 | query, key = torch.split(query_key, [split_size, split_size], dim=2) | 101 | query, key = torch.split(query_key, [split_size, split_size], dim=2) |
| @@ -0,0 +1,47 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | + | ||
| 3 | +"""Direct and atomic backend selection for Gated DeltaNet operators.""" | ||
| 4 | + | ||
| 5 | +from dataclasses import dataclass | ||
| 6 | +import logging | ||
| 7 | +from typing import Callable | ||
| 8 | + | ||
| 9 | + | ||
| 10 | +logger = logging.getLogger(__name__) | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +@dataclass(frozen=True) | ||
| 14 | +class GdnOperators: | ||
| 15 | + name: str | ||
| 16 | + causal_conv1d: Callable | ||
| 17 | + l2norm: Callable | ||
| 18 | + chunk_gated_delta_rule: Callable | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +def _load_fla_npu_operators(): | ||
| 22 | + from fla_npu.ops.triton import l2norm | ||
| 23 | + from mindspeed.core.ssm.npu_causal_conv1d import causal_conv1d | ||
| 24 | + from mindspeed.core.ssm.npu_chunk_gated_delta_rule import chunk_gated_delta_rule | ||
| 25 | + | ||
| 26 | + return GdnOperators("fla_npu", causal_conv1d, l2norm, chunk_gated_delta_rule) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def _load_mindspeed_operators(): | ||
| 30 | + from mindspeed.core.ssm.torch_causal_conv1d import causal_conv1d | ||
| 31 | + from mindspeed.core.ssm.triton_chunk_gated_delta_rule import chunk_gated_delta_rule | ||
| 32 | + from mindspeed.ops.triton.l2norm import l2norm | ||
| 33 | + | ||
| 34 | + return GdnOperators("mindspeed", causal_conv1d, l2norm, chunk_gated_delta_rule) | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def load_gdn_operators() -> GdnOperators: | ||
| 38 | + try: | ||
| 39 | + operators = _load_fla_npu_operators() | ||
| 40 | + except ImportError as error: | ||
| 41 | + logger.warning( | ||
| 42 | + "FLA-NPU GDN backend import failed; using MindSpeed backend: %s", | ||
| 43 | + error, | ||
| 44 | + ) | ||
| 45 | + operators = _load_mindspeed_operators() | ||
| 46 | + logger.info("MindSpeed GDN selected backend: %s", operators.name) | ||
| 47 | + return operators | ||
| @@ -1,69 +1,154 @@ | |||
| 1 | # Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved. | 1 | # Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved. |
| 2 | -"""MindSpeed causal_conv1d — F.conv1d with per-sequence unpack for packed sequences. | 2 | +"""FLA-NPU AscendC causal-convolution adapter for GatedDeltaNet.""" |
| 3 | - | ||
| 4 | -There is no Triton-accelerated causal_conv1d in MindSpeed. This module | ||
| 5 | -provides a ``causal_conv1d`` function matching the FLA signature so that | ||
| 6 | -MindSpeed's GatedDeltaNet subclass can import it directly. | ||
| 7 | -""" | ||
| 8 | 3 | ||
| 9 | import torch | 4 | import torch |
| 10 | -import torch.nn.functional as F | ||
| 11 | 5 | ||
| 12 | 6 | ||
| 13 | -def _unpack_sequence(x, cu_seqlens, dim): | 7 | +def _load_ascendc_ops(): |
| 14 | - """Split a packed tensor into per-sequence chunks along *dim*.""" | 8 | + """Load FLA-NPU's public AscendC bindings only when this backend is used.""" |
| 15 | - chunks = [] | 9 | + from fla_npu.ops.ascendc import npu_causal_conv1d, npu_causal_conv1d_bwd |
| 16 | - for i in range(cu_seqlens.shape[0] - 1): | 10 | + |
| 17 | - start, end = cu_seqlens[i].item(), cu_seqlens[i + 1].item() | 11 | + return npu_causal_conv1d, npu_causal_conv1d_bwd |
| 18 | - idx = [slice(None)] * x.dim() | ||
| 19 | - idx[dim] = slice(start, end) | ||
| 20 | - chunks.append(x[tuple(idx)]) | ||
| 21 | - return chunks | ||
| 22 | 12 | ||
| 23 | 13 | ||
| 24 | -def _conv1d_impl(x, weight_3d, bias): | 14 | +def _activation_mode(activation): |
| 25 | - """Single (non-packed) causal conv1d via F.conv1d (fp32 internally).""" | 15 | + if activation is None: |
| 26 | - seq_len = x.shape[1] | 16 | + return 0 |
| 27 | - x_t = x.float().transpose(1, 2).contiguous() | ||
| 28 | - out = F.conv1d( | ||
| 29 | - input=x_t, | ||
| 30 | - weight=weight_3d.float(), | ||
| 31 | - bias=bias.float() if bias is not None else None, | ||
| 32 | - stride=1, | ||
| 33 | - padding=weight_3d.shape[-1] - 1, | ||
| 34 | - groups=weight_3d.shape[0], | ||
| 35 | - ) | ||
| 36 | - out = out[..., :seq_len] | ||
| 37 | - return out.transpose(1, 2) | ||
| 38 | - | ||
| 39 | - | ||
| 40 | -def causal_conv1d(x, weight, bias=None, activation=None, initial_state=None, output_final_state=False, cu_seqlens=None): | ||
| 41 | - """Torch-native causal_conv1d with FLA-compatible signature. | ||
| 42 | - | ||
| 43 | - Args: | ||
| 44 | - x: ``[b, s, d]`` (bshd layout). | ||
| 45 | - weight: ``[d, w]``. | ||
| 46 | - bias: optional ``[d]``. | ||
| 47 | - activation: ``"silu"`` / ``"swish"`` or ``None``. | ||
| 48 | - initial_state: ignored. | ||
| 49 | - output_final_state: always returns ``None``. | ||
| 50 | - cu_seqlens: ``[num_seqs + 1]`` or ``None``. | ||
| 51 | - | ||
| 52 | - Returns: | ||
| 53 | - ``(y, None)`` where *y* is ``[b, s, d]``. | ||
| 54 | - """ | ||
| 55 | - weight_3d = weight.unsqueeze(1) | ||
| 56 | - | ||
| 57 | - if cu_seqlens is None: | ||
| 58 | - out = _conv1d_impl(x, weight_3d, bias) | ||
| 59 | - else: | ||
| 60 | - chunks = _unpack_sequence(x.float(), cu_seqlens, dim=1) | ||
| 61 | - out_chunks = [_conv1d_impl(c, weight_3d, bias) for c in chunks] | ||
| 62 | - out = torch.cat(out_chunks, dim=1) | ||
| 63 | - | ||
| 64 | if activation in ("silu", "swish"): | 17 | if activation in ("silu", "swish"): |
| 65 | - out = F.silu(out) | 18 | + return 1 |
| 66 | - elif activation is not None: | 19 | + raise ValueError(f"Unsupported activation: {activation}") |
| 67 | - raise ValueError(f"Unsupported activation: {activation}") | ||
| 68 | 20 | ||
| 69 | - return out.to(x.dtype), None | 21 | + |
| 22 | +def _query_start_loc(cu_seqlens): | ||
| 23 | + return [int(value) for value in cu_seqlens.detach().cpu().tolist()] | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +class _AscendCCausalConv1d(torch.autograd.Function): | ||
| 27 | + @staticmethod | ||
| 28 | + def forward(ctx, x, weight, bias, activation_mode, cu_seqlens): | ||
| 29 | + ascendc_forward, ascendc_backward = _load_ascendc_ops() | ||
| 30 | + op_weight = weight.transpose(0, 1).contiguous() | ||
| 31 | + query_start_loc = None | ||
| 32 | + is_packed = cu_seqlens is not None | ||
| 33 | + | ||
| 34 | + if is_packed: | ||
| 35 | + if x.ndim != 3 or x.shape[0] != 1: | ||
| 36 | + raise ValueError("Packed causal_conv1d expects [1, T, D] input") | ||
| 37 | + op_x = x.squeeze(0).contiguous() | ||
| 38 | + query_start_loc = _query_start_loc(cu_seqlens) | ||
| 39 | + num_sequences = len(query_start_loc) - 1 | ||
| 40 | + else: | ||
| 41 | + op_x = x.contiguous() | ||
| 42 | + num_sequences = x.shape[0] | ||
| 43 | + | ||
| 44 | + conv_states = torch.zeros( | ||
| 45 | + num_sequences, | ||
| 46 | + op_weight.shape[0] - 1, | ||
| 47 | + x.shape[-1], | ||
| 48 | + dtype=x.dtype, | ||
| 49 | + device=x.device, | ||
| 50 | + ) | ||
| 51 | + forward_kwargs = { | ||
| 52 | + "x": op_x, | ||
| 53 | + "weight": op_weight, | ||
| 54 | + "bias": bias, | ||
| 55 | + "conv_states": conv_states, | ||
| 56 | + "activation_mode": activation_mode, | ||
| 57 | + "pad_slot_id": -1, | ||
| 58 | + "run_mode": 0, | ||
| 59 | + "head_num": 0, | ||
| 60 | + } | ||
| 61 | + if is_packed: | ||
| 62 | + forward_kwargs.update( | ||
| 63 | + query_start_loc=query_start_loc, | ||
| 64 | + cache_indices=list(range(num_sequences)), | ||
| 65 | + initial_state_mode=[0] * num_sequences, | ||
| 66 | + ) | ||
| 67 | + y = ascendc_forward(**forward_kwargs) | ||
| 68 | + | ||
| 69 | + tensors = [x, op_weight] | ||
| 70 | + if bias is not None: | ||
| 71 | + tensors.append(bias) | ||
| 72 | + ctx.save_for_backward(*tensors) | ||
| 73 | + ctx.has_bias = bias is not None | ||
| 74 | + ctx.activation_mode = activation_mode | ||
| 75 | + ctx.query_start_loc = query_start_loc | ||
| 76 | + ctx.is_packed = is_packed | ||
| 77 | + ctx.ascendc_forward = ascendc_forward | ||
| 78 | + ctx.ascendc_backward = ascendc_backward | ||
| 79 | + return y.unsqueeze(0) if is_packed else y | ||
| 80 | + | ||
| 81 | + @staticmethod | ||
| 82 | + def backward(ctx, grad_output): | ||
| 83 | + saved = list(ctx.saved_tensors) | ||
| 84 | + x = saved.pop(0) | ||
| 85 | + op_weight = saved.pop(0) | ||
| 86 | + bias = saved.pop(0) if ctx.has_bias else None | ||
| 87 | + | ||
| 88 | + op_x = x.squeeze(0).contiguous() if ctx.is_packed else x.contiguous() | ||
| 89 | + op_grad = grad_output.squeeze(0).contiguous() if ctx.is_packed else grad_output.contiguous() | ||
| 90 | + preactivation = None | ||
| 91 | + if ctx.activation_mode != 0: | ||
| 92 | + num_sequences = len(ctx.query_start_loc) - 1 if ctx.is_packed else x.shape[0] | ||
| 93 | + conv_states = torch.zeros( | ||
| 94 | + num_sequences, | ||
| 95 | + op_weight.shape[0] - 1, | ||
| 96 | + x.shape[-1], | ||
| 97 | + dtype=x.dtype, | ||
| 98 | + device=x.device, | ||
| 99 | + ) | ||
| 100 | + forward_kwargs = { | ||
| 101 | + "x": op_x, | ||
| 102 | + "weight": op_weight, | ||
| 103 | + "bias": bias, | ||
| 104 | + "conv_states": conv_states, | ||
| 105 | + "activation_mode": 0, | ||
| 106 | + "pad_slot_id": -1, | ||
| 107 | + "run_mode": 0, | ||
| 108 | + "head_num": 0, | ||
| 109 | + } | ||
| 110 | + if ctx.is_packed: | ||
| 111 | + forward_kwargs.update( | ||
| 112 | + query_start_loc=ctx.query_start_loc, | ||
| 113 | + cache_indices=list(range(num_sequences)), | ||
| 114 | + initial_state_mode=[0] * num_sequences, | ||
| 115 | + ) | ||
| 116 | + preactivation = ctx.ascendc_forward(**forward_kwargs) | ||
| 117 | + | ||
| 118 | + dx, dw, db, _ = ctx.ascendc_backward( | ||
| 119 | + x=op_x, | ||
| 120 | + y=preactivation, | ||
| 121 | + weight=op_weight, | ||
| 122 | + dy=op_grad, | ||
| 123 | + initial_state=None, | ||
| 124 | + dht=None, | ||
| 125 | + query_start_loc=ctx.query_start_loc, | ||
| 126 | + activation=ctx.activation_mode, | ||
| 127 | + input_layout="TND" if ctx.is_packed else "BSH", | ||
| 128 | + ) | ||
| 129 | + if ctx.is_packed: | ||
| 130 | + dx = dx.unsqueeze(0) | ||
| 131 | + return dx, dw.transpose(0, 1).contiguous(), db if ctx.has_bias else None, None, None | ||
| 132 | + | ||
| 133 | + | ||
| 134 | +def causal_conv1d( | ||
| 135 | + x, | ||
| 136 | + weight, | ||
| 137 | + bias=None, | ||
| 138 | + activation=None, | ||
| 139 | + initial_state=None, | ||
| 140 | + output_final_state=False, | ||
| 141 | + cu_seqlens=None, | ||
| 142 | +): | ||
| 143 | + """Run AscendC causal convolution for fixed BSH or packed TND GDN input.""" | ||
| 144 | + if initial_state is not None or output_final_state: | ||
| 145 | + raise NotImplementedError("GDN causal_conv1d does not support convolution state") | ||
| 146 | + | ||
| 147 | + output = _AscendCCausalConv1d.apply( | ||
| 148 | + x, | ||
| 149 | + weight, | ||
| 150 | + bias, | ||
| 151 | + _activation_mode(activation), | ||
| 152 | + cu_seqlens, | ||
| 153 | + ) | ||
| 154 | + return output, None | ||
| @@ -1,33 +1,65 @@ | |||
| 1 | -# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang | 1 | +"""FLA-NPU AscendC/Triton GDR adapter for GatedDeltaNet. |
| 2 | -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. | ||
| 3 | -# Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved. | ||
| 4 | -"""MindSpeed chunk_gated_delta_rule — Triton-accelerated with torch fallback. | ||
| 5 | 2 | ||
| 6 | -Provides a ``chunk_gated_delta_rule`` function matching the FLA signature. | 3 | +The public API uses sequence-first ``[B, T, H, D]``. FLA-NPU cumsum retains |
| 7 | -The forward path dispatches to MindSpeed's 7-kernel Triton pipeline; the | 4 | +sequence-first gates, while KKT and AscendC tensor inputs use head-first |
| 8 | -backward path uses a custom ``torch.autograd.Function`` for efficient | 5 | +``[B, H, T, D]`` tensors. |
| 9 | -gradient computation. Falls back to Megatron-LM's built-in | ||
| 10 | -``torch_chunk_gated_delta_rule`` when Triton is unavailable or when an | ||
| 11 | -``initial_state`` is provided. | ||
| 12 | """ | 6 | """ |
| 13 | 7 | ||
| 14 | import warnings | 8 | import warnings |
| 15 | 9 | ||
| 16 | import torch | 10 | import torch |
| 17 | 11 | ||
| 18 | -from mindspeed.ops.triton.l2norm import l2norm_fwd, l2norm_bwd | 12 | +from fla_npu.ops.ascendc import ( |
| 19 | -from mindspeed.ops.triton.chunk_delta_h import chunk_gated_delta_rule_bwd_dhu, chunk_gated_delta_rule_fwd_h | 13 | + npu_chunk_bwd_dqkwg, |
| 20 | -from mindspeed.ops.triton.chunk_o import chunk_bwd_dqkwg, chunk_bwd_dv_local, chunk_fwd_o | 14 | + npu_chunk_bwd_dv_local, |
| 21 | -from mindspeed.ops.triton.chunk_scaled_dot_kkt import chunk_scaled_dot_kkt_fwd | 15 | + npu_chunk_fwd_o, |
| 22 | -from mindspeed.ops.triton.wy_fast import prepare_wy_repr_bwd, recompute_w_u_fwd | 16 | + npu_chunk_gated_delta_rule_bwd_dhu, |
| 23 | -from mindspeed.ops.triton.solve_tril import solve_tril | 17 | + npu_chunk_gated_delta_rule_fwd_h, |
| 24 | -from mindspeed.ops.triton.cumsum import chunk_local_cumsum | 18 | + npu_prepare_wy_repr_bwd_da, |
| 25 | -from mindspeed.ops.triton.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard | 19 | + npu_prepare_wy_repr_bwd_full, |
| 20 | + npu_recompute_w_u_fwd, | ||
| 21 | + npu_solve_tri, | ||
| 22 | +) | ||
| 23 | +from fla_npu.ops.triton import ( | ||
| 24 | + autocast_custom_bwd, | ||
| 25 | + autocast_custom_fwd, | ||
| 26 | + chunk_local_cumsum, | ||
| 27 | + chunk_scaled_dot_kkt_fwd, | ||
| 28 | + input_guard, | ||
| 29 | + l2norm_bwd, | ||
| 30 | + l2norm_fwd, | ||
| 31 | +) | ||
| 26 | 32 | ||
| 27 | 33 | ||
| 28 | -# ========================================================================= | 34 | +def _as_int_list(cu_seqlens): |
| 29 | -# Forward / backward pipelines | 35 | + return [int(value) for value in cu_seqlens.detach().cpu().tolist()] |
| 30 | -# ========================================================================= | 36 | + |
| 37 | + | ||
| 38 | +def _next_power_of_2(value): | ||
| 39 | + return 1 << (value - 1).bit_length() | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +def _chunk_index_pairs(cu_seqlens_list, chunk_size): | ||
| 43 | + pairs = [] | ||
| 44 | + for seq_idx, (start, end) in enumerate(zip(cu_seqlens_list, cu_seqlens_list[1:])): | ||
| 45 | + for chunk_idx in range((end - start + chunk_size - 1) // chunk_size): | ||
| 46 | + pairs.append((seq_idx, chunk_idx)) | ||
| 47 | + return pairs | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def _prepare_packed_metadata(cu_seqlens, g, chunk_size): | ||
| 51 | + if cu_seqlens is None: | ||
| 52 | + return None, None, None, None | ||
| 53 | + cu_seqlens = cu_seqlens.to(device=g.device, dtype=torch.int64) | ||
| 54 | + cu_list = _as_int_list(cu_seqlens) | ||
| 55 | + chunk_pairs = _chunk_index_pairs(cu_list, chunk_size) | ||
| 56 | + chunk_indices = [value for pair in chunk_pairs for value in pair] | ||
| 57 | + cumsum_block_t = _next_power_of_2((1 << 17) // (g.shape[-1] * chunk_size)) | ||
| 58 | + chunk_indices_out = {} | ||
| 59 | + for size in dict.fromkeys((chunk_size, cumsum_block_t)): | ||
| 60 | + pairs = chunk_pairs if size == chunk_size else _chunk_index_pairs(cu_list, size) | ||
| 61 | + chunk_indices_out[str(size)] = torch.tensor(pairs, device=cu_seqlens.device, dtype=torch.int64).reshape(-1, 2) | ||
| 62 | + return cu_seqlens, cu_list, chunk_indices, chunk_indices_out | ||
| 31 | 63 | ||
| 32 | 64 | ||
| 33 | def _chunk_gated_delta_rule_fwd( | 65 | def _chunk_gated_delta_rule_fwd( |
Mmindspeed/core/transformer/moe/moe_feature/fb_overlap/modules/weight_grad_store.py+36-9File content is under review, please try again later
Mmindspeed/core/transformer/moe/moe_feature/fb_overlap/overlap_funcs/fwd.py+5-4File content is under review, please try again later
Mmindspeed/core/transformer/moe/moe_feature/fb_overlap/overlap_funcs/fwdbwd.py+15-6File content is under review, please try again later
Mmindspeed/core/transformer/moe/moe_feature/fb_overlap/transformer_block.py+23-14File content is under review, please try again later
Mmindspeed/core/transformer/moe/moe_feature/fb_overlap/transformer_layer.py+40-27File content is under review, please try again later
Mmindspeed/core/transformer/moe/moe_feature/fb_overlap/vpp_schedules.py+52-29File content is under review, please try again later
Mmindspeed/core/transformer/moe/moe_feature/mc2moe/token_dispatcher.py+9-2File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep/__init__.py+1-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep/buffer_config.py+120-0File content is under review, please try again later
Rmindspeed/core/transformer/moe/moonep.py→mindspeed/core/transformer/moe/moe_feature/moonep/moonep.py+11-6File content is under review, please try again later
Rmindspeed/core/transformer/moe/moonep_contract.py→mindspeed/core/transformer/moe/moe_feature/moonep/moonep_contract.py+8-135File content is under review, please try again later
Rmindspeed/core/transformer/moe/moonep_executor.py→mindspeed/core/transformer/moe/moe_feature/moonep/moonep_executor.py+46-18File content is under review, please try again later
Rmindspeed/core/transformer/moe/moonep_runtime.py→mindspeed/core/transformer/moe/moe_feature/moonep/moonep_runtime.py+195-66File content is under review, please try again later
Rmindspeed/core/transformer/moe/virtual_expert_load_balancer.py→mindspeed/core/transformer/moe/moe_feature/moonep/virtual_expert_load_balancer.py+205-25File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/__init__.py+13-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/adaptor.py+207-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/async_capacity.py+183-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/async_types.py+23-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/modules/experts.py+161-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/modules/utils.py+246-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/moonep_native.py+277-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/overlap_funcs/bwd.py+222-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/overlap_funcs/fwd.py+242-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/overlap_funcs/fwdbwd.py+238-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/schedule_plan.py+361-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/session.py+500-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/transformer_block.py+228-0File content is under review, please try again later
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/transformer_layer.py+317-0File content is under review, please try again later
Mmindspeed/core/transformer/moe/moe_feature/overlap/moe_layer_overlap_all2all.py+5-2File content is under review, please try again later
Mmindspeed/core/transformer/moe/moe_npu_fast_ops.py+190-112File content is under review, please try again later
Mmindspeed/core/transformer_engine/step_recovery/patch.py+7-3File content is under review, please try again later
Mmindspeed/core/transformer_engine/transformer_engine.py+29-16File content is under review, please try again later
Mmindspeed/features_manager/functional/cache_get_batch_config.py+3-11File content is under review, please try again later
Mmindspeed/features_manager/fusions/fused_rope.py+8-1File content is under review, please try again later
Mmindspeed/features_manager/moe/fb_overlap.py+25-11File content is under review, please try again later
Mmindspeed/features_manager/moe/moe_npu_fast_ops.py+59-15File content is under review, please try again later
Amindspeed/features_manager/moe/moonep_fb_overlap.py+105-0File content is under review, please try again later
Mmindspeed/features_manager/npu_enhancement/npu_enhancement.py+35-12File content is under review, please try again later
Amindspeed/features_manager/transformer/multi_token_prediction.py+33-0File content is under review, please try again later
Mmindspeed/features_manager/transformer_engine/te_recipe.py+6-9File content is under review, please try again later
Mtests_extend/system_tests/deepseek/README.md+4-1File content is under review, please try again later
Atests_extend/system_tests/deepseek/pretrain_deepseek_v3_moonep.py+54-0File content is under review, please try again later
Atests_extend/system_tests/deepseek/pretrain_deepseek_v3_moonep_fb.py+73-0File content is under review, please try again later
Atests_extend/unit_tests/features/moe/test_moonep_1f1b_overlap.py+246-0File content is under review, please try again later
Atests_extend/unit_tests/features/moe/test_moonep_fb_lifecycle.py+60-0File content is under review, please try again later
Dtests_extend/unit_tests/features/moe/test_moonep_lplusb_contract.py+0-271File content is under review, please try again later
Atests_extend/unit_tests/features/moe/test_moonep_v10_adapter.py+70-0File content is under review, please try again later
Atests_extend/unit_tests/features/pipeline_parallel/test_dualpipev_mtp_placement.py+325-0File content is under review, please try again later
Mtests_extend/unit_tests/features/transformer_engine/step_recovery/test_step_recovery.py+6-21File content is under review, please try again later
Atests_extend/unit_tests/features/transformer_engine/test_hif8_recipe.py+94-0File content is under review, please try again later
Dtests_extend/unit_tests/features/transformer_engine/test_qat_scope.py+0-64File content is under review, please try again later
Atests_extend/unit_tests/mindspeed/test_fb_overlap_wgrad_backend.py+141-0File content is under review, please try again later
Atests_extend/unit_tests/mindspeed/test_gmm_weight_mode.py+174-0File content is under review, please try again later