Draft
[WIP]feat(moonep): 支持 MoonEP Forward/Backward overlap #8
&NewgateAdd on 15 days ago
[WIP]feat(moonep): 支持 MoonEP Forward/Backward overlap #8
Draft
&NewgateAdd on 15 days ago
Total: 63 files changed+6267-285
@@ -8,31 +8,31 @@
8 8 
9比如在模型中存在某个流程:9比如在模型中存在某个流程:
10 10 
11-* 前向:gelu激活函数模块->后续模块A11+* 前向:GELU激活函数模块->后续模块A
12 12 
13-+ 反向:后续模块A的反向(需要gelu输出的激活值)->gelu反向(与重计算绑定)13+* 反向:后续模块A的反向(需要GELU输出的激活值)->gelu反向(与重计算绑定)
14 14 
15-gelu激活函数会产生大量的数据,但本身计算量很小。此时进行激活函数的重计算可以在性能劣化极少的代价下,减少内存占用。 但在现有重计算框架下,如果对gelu激活函数模块做重计算,并不能节省gelu函数的输出。这是因为在反向时,模块A所需要的gelu输出的激活值,会早于gelu激活函数模块的重计算流程,所以前向必须保留激活函数的输出,导致激活函数的输出并不能节省下来。15+gelu激活函数会产生大量的数据,但本身计算量很小。此时进行激活函数的重计算可以在性能劣化极少的代价下,减少内存占用。但在现有重计算框架下,如果对gelu激活函数模块做重计算,并不能节省gelu函数的输出。这是因为在反向时,模块A所需要的gelu输出的激活值,会早于gelu激活函数模块的重计算流程,所以前向必须保留激活函数的输出,导致激活函数的输出并不能节省下来。
16 16 
17## 解决方案17## 解决方案
18 18 
19激活函数重计算重新实现了一套重计算框架,可以将重计算灵活地插入到反向计算之前的任意位置,即如下流程:19激活函数重计算重新实现了一套重计算框架,可以将重计算灵活地插入到反向计算之前的任意位置,即如下流程:
20 20 
21-反向(新框架):gelu函数重计算->后续模块A的反向21+反向(新框架):GELU函数重计算->后续模块A的反向
22 22 
23-此时,gelu函数的输出已经早于模块A的反向,在前向时就无须保留gelu函数的输出值。23+此时,GELU函数的输出已经早于模块A的反向,在前向时就无须保留GELU函数的输出值。
24 24 
25-相比之下,传统重计算对于一次计算过程能够节省输入的优化状态,但是仍旧需要保留输出的激活。25+相比之下,传统重计算对于一次计算过程能够节省输出的激活值,但是仍旧需要保留输出的激活直到重计算完成。
26 26 
27因此,设计了一种传入模块函数进行重计算的机制,在合适的时机,丢弃重计算模块输出的物理存储,保留逻辑视图。在反向时,在合适的时机,利用register_hook插入重计算流程。利用传入的函数重新进行计算,得到结果。27因此,设计了一种传入模块函数进行重计算的机制,在合适的时机,丢弃重计算模块输出的物理存储,保留逻辑视图。在反向时,在合适的时机,利用register_hook插入重计算流程。利用传入的函数重新进行计算,得到结果。
28 28 
29-### 图1 重计算与反向绑定29+图1 重计算与反向绑定
30 30 
31![现有框架](../figures/activation_function_a.png)31![现有框架](../figures/activation_function_a.png)
32 32 
33-比如gelu在MLP中的位置如图1所示。反向计算需要前向产生的a、b、c、d。其中b和c的shape为(batch, seq , 4hidden_size),gelu为激活函数,其计算较少,故可将tensor c释放掉,反向在4h->h反向前重新计算。33+比如GELU在MLP中的位置如图1所示。反向计算需要前向产生的a、b、c、d。其中b和c的shape为(batch, seq,4*hidden_size),GELU为激活函数,其计算较少,故可将tensor c释放掉,反向在4h->h反向前重新计算。
34 34 
35-#### 图2 灵活插入重计算35+图2 灵活插入重计算
36 36 
37![新框架](../figures/activation_function_b.png)37![新框架](../figures/activation_function_b.png)
38 38 
@@ -40,7 +40,7 @@ gelu激活函数会产生大量的数据,但本身计算量很小。此时进
40 40 
41## 使用场景41## 使用场景
42 42 
43-**后端限制:** 与 MoE Grouped GEMM、通信隐藏或低精度训练组合时,必须使用 `--transformer-impl transformer_engine`。43+**后端限制:** 与MoE Grouped GEMM、通信隐藏或低精度训练组合时,必须使用 `--transformer-impl transformer_engine`。
44 44 
45主要用于训练场景,用户内存不足或要节省内存时,可以开启激活函数重计算,节省激活函数的输出激活值。45主要用于训练场景,用户内存不足或要节省内存时,可以开启激活函数重计算,节省激活函数的输出激活值。
46 46 
@@ -48,42 +48,42 @@ gelu激活函数会产生大量的数据,但本身计算量很小。此时进
48 48 
49脚本中添加:`--recompute-activation-function` 可开启激活函数重计算。49脚本中添加:`--recompute-activation-function` 可开启激活函数重计算。
50 50 
51-添加:`--recompute-activation-function-num-layers ${num}` 可指定激活函数重计算的层数,取值为 0 到 num_layers 的整数。51+添加:`--recompute-activation-function-num-layers ${num}` 可指定激活函数重计算的层数,取值为0到num_layers的整数。
52 52 
53### 说明53### 说明
54 54 
55激活函数重计算可以与全重计算同时开启:55激活函数重计算可以与全重计算同时开启:
56 56 
57-* 同时开启时,仅支持 `--recompute-method 为 block`57+* 同时开启时,仅支持`--recompute-method`为`block`。
58 58 
59* 同时开启时,会按照指定的全重计算和激活函数重计算的层数做各自类型的重计算,即不会有一层既做全重计算又做激活函数重计算。59* 同时开启时,会按照指定的全重计算和激活函数重计算的层数做各自类型的重计算,即不会有一层既做全重计算又做激活函数重计算。
60 60 
61执行优先级是先计算全重计算层,后计算激活函数重计算层。在流水线并行未开启的情况下,全重计算层数和激活函数重计算层数之和应该等于总层数。61执行优先级是先计算全重计算层,后计算激活函数重计算层。在流水线并行未开启的情况下,全重计算层数和激活函数重计算层数之和应该等于总层数。
62 62 
63-* 与 MoE overlap 同用时,不支持 `--hybrid-layer-pattern`。63+* 与MoE overlap 同用时,不支持 `--hybrid-layer-pattern`。
64 64 
65## 使用效果65## 使用效果
66 66 
67启用激活函数重计算后,激活函数的输出激活值不用再保存,内存占用减少。同时由于激活函数计算量很小,训练性能只会略微下降。67启用激活函数重计算后,激活函数的输出激活值不用再保存,内存占用减少。同时由于激活函数计算量很小,训练性能只会略微下降。
68 68 
69-激活函数重计算在llama2-7B场景下,根据模型配置不同,收益也会发生改变。69+激活函数重计算在Llama-2-7b场景下,根据模型配置不同,收益也会发生改变。
70在不同参数场景下,激活函数重计算收益表现如下: 70在不同参数场景下,激活函数重计算收益表现如下:
71 71 
72| 模型参数 | 设备数 | 内存收益 |72| 模型参数 | 设备数 | 内存收益 |
73|-----------------------------------------------------------------------------|----------|-------------|73|-----------------------------------------------------------------------------|----------|-------------|
74-| seq-length=12288、micro-batch-size=2、TP=4、DP=2 | 8卡(单机) | 8.05G |74+| seq-length=12288、micro-batch-size=2、TP=4、DP=2 | 8卡(单机) | 8.05GB |
75-| seq-length=8096、micro-batch-size=2、TP=4、DP=2 | 8卡(单机) | 5.31G |75+| seq-length=8096、micro-batch-size=2、TP=4、DP=2 | 8卡(单机) | 5.31GB |
76-| seq-length=16384、micro-batch-size=2、TP=4、DP=2 | 8卡(单机) | 12.49G |76+| seq-length=16384、micro-batch-size=2、TP=4、DP=2 | 8卡(单机) | 12.49GB |
77-| seq-length=12288、micro-batch-size=1、TP=4、DP=2 | 8卡(单机) | 4.04G |77+| seq-length=12288、micro-batch-size=1、TP=4、DP=2 | 8卡(单机) | 4.04GB |
78-| seq-length=12288、micro-batch-size=2、TP=8、DP=1 | 8卡(单机) | 4.02G |78+| seq-length=12288、micro-batch-size=2、TP=8、DP=1 | 8卡(单机) | 4.02GB |
79 79 
80## 扩展使用80## 扩展使用
81 81 
82-本特性引入的 CheckpointWithoutOutput 类可以自定义对任何模块进行重计算,并且在合适的时机进行重计算恢复。82+本特性引入的CheckpointWithoutOutput类可以自定义对任何模块进行重计算,并且在合适的时机进行重计算恢复。
83 83 
84-此处提供一个示例,可以灵活使用 CheckpointWithoutOutput 来对自定义的函数进行重计算:84+此处提供一个示例,可以灵活使用CheckpointWithoutOutput来对自定义的函数进行重计算:
85 85 
86-(注意:如要使用register_hook,需要确保张量有梯度)86+(注意:如要使用register_hook,需要确保张量有梯度。)
87 87 
88```python88```python
89from mindspeed.core.tensor_parallel.random import CheckpointWithoutOutput89from mindspeed.core.tensor_parallel.random import CheckpointWithoutOutput
@@ -13,17 +13,17 @@
13在前向与反向计算结束后,将进行独立的通信阶段,包括梯度的reduce-scatter、权重计算以及权重的all-gather,如下图所示。获取更新后的权重后,系统将进入下一轮的前向计算阶段。13在前向与反向计算结束后,将进行独立的通信阶段,包括梯度的reduce-scatter、权重计算以及权重的all-gather,如下图所示。获取更新后的权重后,系统将进入下一轮的前向计算阶段。
14<p align="center"> <img src="../figures/async_ddp_param_gather_a.png" height="350px" width="880px"></p>14<p align="center"> <img src="../figures/async_ddp_param_gather_a.png" height="350px" width="880px"></p>
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`
22 22 
23-在打开`--use-distributed-optimizer`和`--overlap-grad-reduce`的基础上进一步打开`--overlap-param-gather`,运行流程如下图所示,对权重的all-gather过程与下一轮的前向计算并行,从而节省了单独的all-gather过程。23+在打开`--use-distributed-optimizer`和`--overlap-grad-reduce`的基础上进一步打开`--overlap-param-gather`,运行流程如下图所示,将权重的all-gather过程与下一轮的前向计算并行,从而节省了单独的all-gather过程。
24<p align="center"> <img src="../figures/async_ddp_param_gather_c.png" height="350px" width="880px"></p>24<p align="center"> <img src="../figures/async_ddp_param_gather_c.png" height="350px" width="880px"></p>
25 25 
26-以上流程对比发现,打开--overlap-param-gather后,通信与计算完全并行,极大提高了计算-通信并行效率,进而提升了模型训练效率。26+以上流程对比发现,打开`--overlap-param-gather`后,通信与计算完全并行,极大提高了计算-通信并行效率,进而提升了模型训练效率。
27 27 
28## 使用场景28## 使用场景
29 29 
@@ -16,7 +16,7 @@ Bucket机制:设立一个临时存储区(Bucket),用于暂存反向传
16 16 
17## 使用场景17## 使用场景
18 18 
19-* 模型开启数据并行和分布式优化器(--use-distributed-optimizer)。19+* 模型开启数据并行和分布式优化器(`--use-distributed-optimizer`)。
20* 需要高效利用集群资源进行大规模深度学习模型训练的环境。20* 需要高效利用集群资源进行大规模深度学习模型训练的环境。
21* 需要快速迭代模型参数、缩短实验周期的研究和开发工作。21* 需要快速迭代模型参数、缩短实验周期的研究和开发工作。
22 22 
@@ -42,7 +42,7 @@ DP 大于 1,模型权重、梯度和优化器状态占用较多显存,希望
42 --transformer-impl transformer_engine42 --transformer-impl transformer_engine
43 ```43 ```
44 44 
45-4. 安装包含 DTensor FusedAdam 修复的 TransformerEngineNPU 版本,例如包含提交 [5c85c0d](https://gitcode.com/GuoHaifeng1999/TransformerEngineNPU/commit/5c85c0df3e9c1887a4aa5a000f96b2f01d9fb031) 的版本,并确认训练环境实际导入该安装包。旧版 TENPU 会拒绝 FSDP 提供的 DTensor 参数;仅调整检查点格式不能解决优化器类型错误。45+4. 安装包含 DTensor FusedAdam 修复的 TransformerEngineNPU 版本,例如包含提交 [5c85c0d](https://gitcode.com/Ascend/TransformerEngineNPU/commit/5c85c0d) 的版本,并确认训练环境实际导入该安装包。旧版 TENPU 会拒绝 FSDP 提供的 DTensor 参数;仅调整检查点格式不能解决优化器类型错误。
46 46 
47## 支持范围与验证状态47## 支持范围与验证状态
48 48 
@@ -6,11 +6,13 @@
6 6 
7## 解决方案7## 解决方案
8 8 
9-数据并行 (Data Parallelism,DP) 策略通过将数据集划分为多个批次(Batch),并将其均匀分配至各个计算设备,使得每台设备仅负责处理特定批次的数据。9+数据并行(Data Parallelism,DP)策略通过将数据集划分为多个批次(Batch),并将其均匀分配至各个计算设备,使得每台设备仅负责处理特定批次的数据。
10 10 
11此方案的实施需满足以下两点关键要素:11此方案的实施需满足以下两点关键要素:
12-每一台计算设备上部署的模型结构与参数保持完全一致。12+ 
13-各设备处理的数据批次互不相同,确保训练过程的并行性和效率。13+* 每一台计算设备上部署的模型结构与参数保持完全一致。
14+* 各设备处理的数据批次互不相同,确保训练过程的并行性和效率。
15+ 
14该方案的整体思路如下:16该方案的整体思路如下:
15 17 
16* 模型复制:在每个计算设备上存储完整的模型副本。18* 模型复制:在每个计算设备上存储完整的模型副本。
@@ -26,7 +28,7 @@
26 28 
27## 使用方法29## 使用方法
28 30 
29-数据并行的启用与参数配置主要依赖于以下指标:31+数据并行的启用与参数配置主要依赖于以下参数:
30 32 
31* NPU数量(World Size):参与并行训练的所有NPU数量。33* NPU数量(World Size):参与并行训练的所有NPU数量。
32* 模型并行数(Tensor Model Parallel Size):模型权重的并行分割数。34* 模型并行数(Tensor Model Parallel Size):模型权重的并行分割数。
@@ -42,4 +44,4 @@
42 44 
43## 使用效果45## 使用效果
44 46 
45-数据并行根据其他并行策略的设置自行计算。数据并行处理方式能够显著缩短训练周期,尤其是在处理高维特征和大规模数据集时,能够提高硬件资源的利用率。数据并行架构具备良好的横向扩展性,能够随着计算资源的增加而线性提升性能,易于在不同规模的集群环境中部署与调整,满足不同阶段的计算需求。47+数据并行数根据其他并行策略的设置自行计算,因此数据并行训练能够显著缩短训练周期,尤其是在处理高维特征和大规模数据集时,能够提高硬件资源的利用率。数据并行架构具备良好的横向扩展性,能够随着计算资源的增加而线性提升性能,易于在不同规模的集群环境中部署与调整,满足不同阶段的计算需求。
@@ -1,8 +1,8 @@
1-# Megatron 分布式优化器1+# Megatron分布式优化器
2 2 
3## 背景与挑战3## 背景与挑战
4 4 
5-在数据并行(Data Parallelism,DP)框架下,各计算设备在梯度聚合(All-Reduce)前独立执行任务,实现高效并行处理。然而,All-Reduce操作后,所有设备基于相同的梯度、参数及优化器状态执行一致的更新流程,这不仅导致了计算资源的冗余,也增加了存储负担,影响整体效率。5+在数据并行(Data Parallelism,DP)框架下,各计算设备在梯度聚合(All-Reduce)前独立执行任务,实现高效并行处理。然而,All-Reduce操作后,所有设备基于相同的梯度、参数及优化器状态执行一致的更新流程,这不仅导致了计算资源的冗余,也增加了内存负担,影响整体效率。
6 6 
7## 解决思路7## 解决思路
8 8 
@@ -2,25 +2,25 @@
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 
9## 解决方案9## 解决方案
10 10 
11在DualPipe的基础之上,一种改进流水排布DualPipeV被提出[2](https://zhuanlan.zhihu.com/p/26915547331)。它在流水上从PP维度截取DualPipe的一半,同时将模型在PP切分的基础上进行进一步地切分,流水呈V字形排布。它解决了DualPipe冗余参数的问题,算法启动规模也只需要DualPipe的一半。11在DualPipe的基础之上,一种改进流水排布DualPipeV被提出[2](https://zhuanlan.zhihu.com/p/26915547331)。它在流水上从PP维度截取DualPipe的一半,同时将模型在PP切分的基础上进行进一步地切分,流水呈V字形排布。它解决了DualPipe冗余参数的问题,算法启动规模也只需要DualPipe的一半。
12 12 
13-下图以PP4,10个microbatch为例展示DualPipeV流水排布。13+下图以PP4、10个microbatch为例展示DualPipeV流水排布。
14![dualpipev](../figures/dualpipev.png)14![dualpipev](../figures/dualpipev.png)
15-图中0~9和10~19代表同一个microbatch在同一张卡上的两个stage。绿色部分代表不同microbatch的前反向并行,开启跨micro batch前反向通信掩盖后,All2All通信和P2P通信都可以被没有依赖关系的计算掩盖,该特性的详细介绍参见[MoE跨microbatch前反向通信掩盖](megatron_moe/megatron-moe-fb-overlap.md)。15+图中0~9和10~19代表同一个microbatch在同一张卡上的两个stage。绿色部分代表不同microbatch的前反向并行,开启跨microbatch前反向通信掩盖后,All2All通信和P2P通信都可以被没有依赖关系的计算掩盖,该特性的详细介绍参见[MoE跨microbatch前反向通信掩盖](megatron_moe/megatron-moe-fb-overlap.md)。
16 16 
17在warmup阶段,MindSpeed实现了尽可能多的P2P通信掩盖。在cooldown阶段,DualPipeV实现中PP尾卡会连续计算PP_size个反向stage,在对应的dw计算完成之前,激活值并不会完全释放,这会导致在某些重计算或其他内存特性场景下,cooldown阶段的峰值内存被大大拉高。因此MindSpeed实现中默认取消了cooldown阶段的dw分离,以较小的性能代价降低了重计算场景下内存峰值。同时也给出了dw分离的参数选项,开启dw分离时的流水如下图所示。17在warmup阶段,MindSpeed实现了尽可能多的P2P通信掩盖。在cooldown阶段,DualPipeV实现中PP尾卡会连续计算PP_size个反向stage,在对应的dw计算完成之前,激活值并不会完全释放,这会导致在某些重计算或其他内存特性场景下,cooldown阶段的峰值内存被大大拉高。因此MindSpeed实现中默认取消了cooldown阶段的dw分离,以较小的性能代价降低了重计算场景下内存峰值。同时也给出了dw分离的参数选项,开启dw分离时的流水如下图所示。
18-![dualpipev_dw_detach](../figures/dualpipev_dw_detach.png)。18+![dualpipev_dw_detach](../figures/dualpipev_dw_detach.png)
19 19 
20-下图展示了在DeepseekV3 671B模型上采用PP8 TP2 EP32 DualPipeV策略采集的PP通信组profiling。20+下图展示了在DeepSeekV3 671B模型上采用PP8 TP2 EP32 DualPipeV策略采集的PP通信组profiling。
21![dualpipev_profiling](../figures/dualpipev_profiling.png)21![dualpipev_profiling](../figures/dualpipev_profiling.png)
22 22 
23-下表展示了不同流水排布中bubble对比。23+下表展示了不同流水排布中空泡对比。
24<table>24<table>
25 <thead>25 <thead>
26 <tr>26 <tr>
@@ -48,24 +48,24 @@ DualPipe流水不仅可以创造跨microbatch计算通信并行的条件,实
48 48 
49**后端限制:** 开启 `--moe-fb-overlap` 时,必须设置 `--transformer-impl transformer_engine`。49**后端限制:** 开启 `--moe-fb-overlap` 时,必须设置 `--transformer-impl transformer_engine`。
50 50 
51-在Moe场景,All2All通信过长而影响性能时,可以采用DualPipeV和MoE跨microbatch前反向通信掩盖的组合特性来提升性能。51+在MoE场景,All2All通信过长而影响性能时,可以采用DualPipeV和MoE跨microbatch前反向通信掩盖的组合特性来提升性能。
52 52 
53## 使用方法53## 使用方法
54 54 
55-在启动脚本中添加 `--schedules-method dualpipev --untie-embeddings-and-output-weights` 开启 DualPipeV 流水排布。55+在启动脚本中添加 `--schedules-method dualpipev --untie-embeddings-and-output-weights` 开启DualPipeV流水排布。
56 56 
57在启动脚本中额外添加`--moe-fb-overlap`来开启MoE跨microbatch前反向通信掩盖。57在启动脚本中额外添加`--moe-fb-overlap`来开启MoE跨microbatch前反向通信掩盖。
58 58 
59在启动脚本中额外添加`--dualpipev-dw-detach`来开启cooldown阶段的dw分离。59在启动脚本中额外添加`--dualpipev-dw-detach`来开启cooldown阶段的dw分离。
60 60 
61-要求 PP 大于 1,模型层数至少为 `2 * PP`,每个 PP 组的 microbatch 数至少为 `2 * PP - 1`。61+要求PP大于1,模型层数至少为 `2 * PP`,每个 PP 组的 microbatch 数至少为 `2 * PP - 1`。
62 62 
63## 使用效果63## 使用效果
64 64 
65在开启DualPipeV和MoE跨microbatch前反向通信掩盖后可以对MoE的All2All通信进行掩盖,获得性能提升。但在某些场景(例如MoE中严重负载不均衡)时,开启DualPipeV可能会加剧PP负载不均,造成性能劣化,因此性能变化需要按场景具体分析。65在开启DualPipeV和MoE跨microbatch前反向通信掩盖后可以对MoE的All2All通信进行掩盖,获得性能提升。但在某些场景(例如MoE中严重负载不均衡)时,开启DualPipeV可能会加剧PP负载不均,造成性能劣化,因此性能变化需要按场景具体分析。
66 66 
67-开启DualPipeV可能会造成内存峰值上升,原因是DualPipeV中output head会被分配到PP rank0,这会同时带来静态内存和动态内存的上升。但在某些场景(例如设置模型后N层为空层时)中,由于尾stage在PP rank0,DualPipeV开启后峰值内存会降低。因此开启DualPipeV之后的内存变化需要具体分析。67+开启DualPipeV可能会造成内存峰值上升,原因是DualPipeV中output head会被分配到PP rank0,这会同时带来静态内存和动态内存的上升。但在某些场景(例如设置模型后N层为空层时)中,由于尾stage在PP rank0,DualPipeV开启后峰值内存会降低。因此开启DualPipeV之后的内存变化需要具体分析。
68 68 
69## 使用约束69## 使用约束
70 70 
71-不支持与 FSDP、`--overlap-grad-reduce`、CP、VPP 或 `--pipeline-model-parallel-layout` 同时使用。71+不支持与FSDP、`--overlap-grad-reduce`、CP、VPP或 `--pipeline-model-parallel-layout` 同时使用。
@@ -1,8 +1,8 @@
1# 特性总览1# 特性总览
2 2 
3-本手册汇总了MindSpeed Core相关特性,具体分类如下所示。3+本手册汇总了MindSpeed Core相关特性,具体分类如下所示:
4 4 
5-**表 1** 特性列表5+**表 1** 特性列表
6 6 
7<table>7<table>
8 <thead>8 <thead>
@@ -66,7 +66,7 @@
66 <td><a href="../features/kvallgather-context-parallel.md">KVAllGather长序列并行</a></td>66 <td><a href="../features/kvallgather-context-parallel.md">KVAllGather长序列并行</a></td>
67 </tr>67 </tr>
68 <tr>68 <tr>
69- <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>
70 </tr>70 </tr>
71 <tr>71 <tr>
72 <td rowspan="10">内存优化特性</td>72 <td rowspan="10">内存优化特性</td>
@@ -85,7 +85,7 @@
85 <td><a href="../features/norm-recompute.md">Ascend Norm重计算</a></td>85 <td><a href="../features/norm-recompute.md">Ascend Norm重计算</a></td>
86 </tr>86 </tr>
87 <tr>87 <tr>
88- <td><a href="../features/hccl-group-buffer-set.md">Ascend Hccl Buffer自适应</a></td>88+ <td><a href="../features/hccl-group-buffer-set.md">Ascend HCCL Buffer自适应</a></td>
89 </tr>89 </tr>
90 <tr>90 <tr>
91 <td><a href="../features/swap-optimizer.md">Ascend Swap Optimizer</a></td>91 <td><a href="../features/swap-optimizer.md">Ascend Swap Optimizer</a></td>
@@ -113,7 +113,7 @@
113 <td><a href="../features/flash-attention.md">Ascend Flash Attention</a></td>113 <td><a href="../features/flash-attention.md">Ascend Flash Attention</a></td>
114 </tr>114 </tr>
115 <tr>115 <tr>
116- <td><a href="../features/moe-token-permute-and-unpermute.md">Ascend Moe Token Permute and Unpermute 融合算子</a></td>116+ <td><a href="../features/moe-token-permute-and-unpermute.md">Ascend MoE Token Permute and Unpermute 融合算子</a></td>
117 </tr>117 </tr>
118 <tr>118 <tr>
119 <td><a href="../features/npu_matmul_add.md">Ascend npu_matmul_add_fp32 梯度累加融合算子</a></td>119 <td><a href="../features/npu_matmul_add.md">Ascend npu_matmul_add_fp32 梯度累加融合算子</a></td>
@@ -20,7 +20,7 @@ Tips: 以上操作默认开启,生成的AttnMask全部为下三角形状,可
20 20 
21[2] 非PP首尾节点的AttnMask为None,无法使能FA加速。21[2] 非PP首尾节点的AttnMask为None,无法使能FA加速。
22 22 
23-[3] AttnMask生成、拷贝及广播操作,在每个micro_step都会跟随get_batch重复。23+[3] AttnMask生成、拷贝及广播操作,在每个micro_step都会跟随`get_batch`重复。
24 24 
25[4] 长序列下,生成的AttnMask占用显存过大。25[4] 长序列下,生成的AttnMask占用显存过大。
26 26 
@@ -34,7 +34,7 @@ Tips: 以上操作默认开启,生成的AttnMask全部为下三角形状,可
34 34 
35## 使用场景35## 使用场景
36 36 
37-**后端限制:** 本文 mask 缓存接口仅用于 `--transformer-impl local`。37+**后端限制:** 本文AttnMask缓存接口仅用于 `--transformer-impl local`。
38 38 
39| 配置 | 支持范围 |39| 配置 | 支持范围 |
40| --- | --- |40| --- | --- |
@@ -43,7 +43,7 @@ Tips: 以上操作默认开启,生成的AttnMask全部为下三角形状,可
43| `--use-flash-attn --sparse-mode 0` | 默认模式,根据传入的 mask 计算。 |43| `--use-flash-attn --sparse-mode 0` | 默认模式,根据传入的 mask 计算。 |
44| `--use-flash-attn --sparse-mode 2` | 左上对齐的因果压缩 mask。 |44| `--use-flash-attn --sparse-mode 2` | 左上对齐的因果压缩 mask。 |
45 45 
46-CP>1 需使用 `--transformer-impl transformer_engine`,与 EOD Reset 组合时仅支持 `p2p/all_gather + causal`,具体约束见 [EOD Reset](eod-reset.md)。`attention-mask-type` 与 `sparse-mode` 是不同参数,TENPU 内部使用的算子模式不等同于启动参数的可选范围。46+CP>1需使用 `--transformer-impl transformer_engine`,与 EOD Reset 组合时仅支持 `p2p/all_gather + causal`,具体约束见 [EOD Reset](eod-reset.md)。`attention-mask-type` 与 `sparse-mode` 是不同参数,TENPU 内部使用的算子模式不等同于启动参数的可选范围。
47 47 
48本地 DotProductAttention 路径在 causal 且传入 mask 为 None 时生成并缓存 mask;FA 默认生成 [2048,2048] 的压缩 mask,`multi_head_latent_attention` 配置使用完整序列长度。非 FA 使用完整 mask。48本地 DotProductAttention 路径在 causal 且传入 mask 为 None 时生成并缓存 mask;FA 默认生成 [2048,2048] 的压缩 mask,`multi_head_latent_attention` 配置使用完整序列长度。非 FA 使用完整 mask。
49 49 
@@ -57,7 +57,7 @@ CP>1 需使用 `--transformer-impl transformer_engine`,与 EOD Reset 组合时
57 57 
58[4] 提供 `mindspeed/core/transformer/flash_attention/generate_mask/generate_mask.py` 中的 `set_attention_mask`、`get_attention_mask`、`generate_attention_mask` 三个额外接口,实现正常流程外的设置、获取和生成功能。58[4] 提供 `mindspeed/core/transformer/flash_attention/generate_mask/generate_mask.py` 中的 `set_attention_mask`、`get_attention_mask`、`generate_attention_mask` 三个额外接口,实现正常流程外的设置、获取和生成功能。
59 59 
60-[5] 本地 DotProductAttention 通过 `mindspeed/core/transformer/flash_attention/generate_mask/adaptor.py` 中的 `dot_product_attention_forward_wrapper` 在首次需要时生成 mask;CP 注意力由 TENPU 处理。60+[5] 本地DotProductAttention 通过 `mindspeed/core/transformer/flash_attention/generate_mask/adaptor.py` 中的 `dot_product_attention_forward_wrapper` 在首次需要时生成 mask;CP 注意力由 TENPU 处理。
61 61 
62## 使用效果62## 使用效果
63 63 
@@ -65,4 +65,4 @@ CP>1 需使用 `--transformer-impl transformer_engine`,与 EOD Reset 组合时
65 65 
66## 注意事项66## 注意事项
67 67 
68-自动生成的 FA mask 为因果 mask;设置 `general` 不会自动生成任意自定义 mask。`set_attention_mask` 仅用于设置本地缓存,不改变 CP/EOD 或 `--sparse-mode` 的支持限制。68+自动生成的FA mask 为因果 mask;设置 `general` 不会自动生成任意自定义 mask。`set_attention_mask` 仅用于设置本地缓存,不改变 CP/EOD 或 `--sparse-mode` 的支持限制。
@@ -1,8 +1,8 @@
1-# Hccl Group Buffer Set1+# HCCL Group Buffer Set
2 2 
3## 背景与挑战3## 背景与挑战
4 4 
5-当前MindSpeed的通信域Buffer,只能通过环境变量HCCL_BUFFSIZE进行统一设置(默认为200M),但往往不同通信域所需的Buffer大小不能一概而论,具体请参见《CANN 环境变量参考》中的“[HCCL_BUFFSIZE](https://www.hiascend.com/document/detail/zh/canncommercial/81RC1/apiref/envvar/envref_07_0080.html)”章节。5+当前MindSpeed的通信域缓冲区,只能通过环境变量HCCL_BUFFSIZE进行统一设置(默认为200MB),但往往不同通信域所需的Buffer大小不能一概而论,具体请参见《CANN 环境变量参考》中的“[HCCL_BUFFSIZE](https://www.hiascend.com/document/detail/zh/canncommercial/81RC1/apiref/envvar/envref_07_0080.html)”章节。
6 6 
7## 解决方案7## 解决方案
8 8 
@@ -19,20 +19,20 @@
19`--hccl-group-buffer-adaptive`19`--hccl-group-buffer-adaptive`
20**注意:**20**注意:**
21 * 开启该特性后,会自适应设置tp、cp、pp相关通信组大小。21 * 开启该特性后,会自适应设置tp、cp、pp相关通信组大小。
22- * 对于ep相关的通信组(例如exp、tp_exp、tp),用户可自行根据当前模型MoE负载不均衡的程度指定系数--hccl-ep-group-buffer-adaptive-factor,从而得到合适的通信域 Buffer,该系数代表当前负载不均衡的程度。 例如,设置--hccl-ep-group-buffer-adaptive-factor大小为1,代表的是负载均衡情况下需要开启的buffer大小;设置为n,代表当前缓冲区大小是负载均衡情况下的n倍,n配置过大有可能会导致OOM。22+ * 对于ep相关的通信组(例如exp、tp_exp、tp),用户可自行根据当前模型MoE负载不均衡的程度指定系数--hccl-ep-group-buffer-adaptive-factor,从而得到合适的通信域缓冲区,该系数代表当前负载不均衡的程度。例如,设置--hccl-ep-group-buffer-adaptive-factor大小为1,代表的是负载均衡情况下需要开启的buffer大小;设置为n,代表当前缓冲区大小是负载均衡情况下的n倍,n配置过大有可能会导致OOM。
23 23 
24- * 自动配置目前支持的通信组如下:24+ * 自动配置目前支持的通信组如下:
25[ "cp", "mp", "mp_exp", "tp", "pp", "tp_cp", "tp_exp", "exp", "pp_new_stream", "cp2", "cp_ulysses", "cp_ring", "cp_ring_intra","cp_ring_intra_overlap"]25[ "cp", "mp", "mp_exp", "tp", "pp", "tp_cp", "tp_exp", "exp", "pp_new_stream", "cp2", "cp_ulysses", "cp_ring", "cp_ring_intra","cp_ring_intra_overlap"]
26 26 
27* 手动配置27* 手动配置
28`--hccl-group-buffer`28`--hccl-group-buffer`
29-**注意:**29+**注意:**
30- * 配置该参数并指定所需要设定的组以及大小(例如:`--hccl-group-buffer "dp:200;tp:300;ep:400"`,也支持逗号分隔),单位是 MB,值必须为正整数。30+ * 配置该参数并指定所需要设定的组以及大小(例如:`--hccl-group-buffer "dp:200;tp:300;ep:400"`,也支持逗号分隔),单位是MB,值必须为正整数。
31 * 手动配置目前支持的通信组如下:31 * 手动配置目前支持的通信组如下:
32["dp", "dp_cp", "cp", "mp", "mp_exp", "tp", "pp", "embd", "tp_dp_cp", "tp_dp", "tp_cp", "tp_exp", "tp_ep_mp", "exp", "ep", "dp_modulo_exp", "pp_new_stream", "cp2", "cp_ulysses", "cp_ring", "cp_ring_intra", "cp_ring_intra_overlap", "nd1_dim1", "ag_x_sd_rcv_overlap", "nd1_dim2", "ag_y_sd_rcv_overlap", "nd2_dim1", "nd2_dim2", "default_group", "ep_dp", "ep_tp", "hcp", "inter_dp_cp", "inter_ep_dp", "inner_dp", "intra_dist_opt_instance", "intra_dp_cp", "intra_ep_dp", "pos_embd", "tp_ep_pp"]32["dp", "dp_cp", "cp", "mp", "mp_exp", "tp", "pp", "embd", "tp_dp_cp", "tp_dp", "tp_cp", "tp_exp", "tp_ep_mp", "exp", "ep", "dp_modulo_exp", "pp_new_stream", "cp2", "cp_ulysses", "cp_ring", "cp_ring_intra", "cp_ring_intra_overlap", "nd1_dim1", "ag_x_sd_rcv_overlap", "nd1_dim2", "ag_y_sd_rcv_overlap", "nd2_dim1", "nd2_dim2", "default_group", "ep_dp", "ep_tp", "hcp", "inter_dp_cp", "inter_ep_dp", "inner_dp", "intra_dist_opt_instance", "intra_dp_cp", "intra_ep_dp", "pos_embd", "tp_ep_pp"]
33 33 
34- `--hccl-op-mode` 使用相同的 `组名:整数` 语法,值必须为正整数,例如 `--hccl-op-mode "tp:1,ep:1"`。34- `--hccl-op-mode` 使用相同的 `组名:整数` 语法,值必须为正整数,例如 `--hccl-op-mode "tp:1,ep:1"`。
35-- 配置可与 AI QoS 同时使用。35+- 配置可与AI QoS同时使用。
36 36 
37## 使用效果37## 使用效果
38 38 
@@ -40,4 +40,4 @@ LLaMA系列模型,开启自适应方案,性能不下降的同时可以节约
40 40 
41## 使用限制41## 使用限制
42 42 
43-本特性依赖 PTA:FrameworkPTAdapter 7.0.RC1.B020 (包含该版本)之后的版本43+本特性依赖PTA:FrameworkPTAdapter 7.0.RC1.B020(包含该版本)之后的版本。
@@ -2,7 +2,7 @@
2 2 
3## 背景与挑战3## 背景与挑战
4 4 
5-从生成性AI到科研模型,长序列训练正在变得非常重要。 在生成性AI领域,会话式AI、长文档摘要和视频生成等任务都需要在空间和时间层面对长上下文进行推理。 同样,章节和书籍级别的摘要(数万甚至数十万字)在会话式AI和摘要任务中也非常重要。现有的数据、张量和流水线等并行方法无法在序列维度进行切分。当序列维度(S)增长时,训练内存开销会以 $O$($S^2$) 的速度增长。因此需要针对长序列场景进行特定的优化解决长训练场景的训练需求。5+从生成式AI到科研模型,长序列训练正在变得非常重要。在生成性AI领域,会话式AI、长文档摘要和视频生成等任务都需要在空间和时间层面对长上下文进行推理。同样,章节和书籍级别的摘要(数万甚至数十万字)在会话式AI和摘要任务中也非常重要。现有的数据、张量和流水线等并行方法无法在序列维度进行切分。当序列维度(S)增长时,训练内存开销会以 $O$($S^2$) 的速度增长。因此需要针对长序列场景进行特定的优化以解决长序列训练场景的训练需求。
6 6 
7## 解决方案7## 解决方案
8 8 
@@ -10,13 +10,13 @@
10 10 
11更多关于KVAllGather长序列并行方案的细节请参见原文:11更多关于KVAllGather长序列并行方案的细节请参见原文:
12 12 
13-> Section 3.3.2 of "The Llama 3 Herd of Models" <https://arxiv.org/abs/2407.21783>13+> Section 3.3.2 of "The Llama 3 Herd of Models" [原文链接](https://arxiv.org/abs/2407.21783)
14 14 
15## 使用场景15## 使用场景
16 16 
17-**后端限制:** CP>1 必须设置 `--transformer-impl transformer_engine`。17+**后端限制:** CP>1必须设置 `--transformer-impl transformer_engine`。
18 18 
19-KVAllGather通过收集完整的key、value计算本地query对应的attention。支持的 mask 范围见下文注意事项。19+KVAllGather通过收集完整的key、value计算本地query对应的attention。支持的mask范围见下文注意事项。
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 
@@ -24,10 +24,10 @@ KVAllGather通过收集完整的key、value计算本地query对应的attention
24 24 
25## 使用方法25## 使用方法
26 26 
27-| 训练类型 | 支持的 mask 类型 |27+| 训练类型 | 支持的mask类型 |
28| --- | --- |28| --- | --- |
29| 普通训练 | causal |29| 普通训练 | causal |
30-| EOD Reset | causal,需满足 [EOD Reset 配置约束](eod-reset.md) |30+| EOD Reset | causal,需满足 [EOD Reset配置约束](eod-reset.md) |
31 31 
32`--cp-comm-type allgather` 与 `all_gather` 等价。32`--cp-comm-type allgather` 与 `all_gather` 等价。
33 33 
@@ -36,16 +36,16 @@ KVAllGather通过收集完整的key、value计算本地query对应的attention
36| 重要参数 | 参数说明 |36| 重要参数 | 参数说明 |
37|----------------------------------------------------|---------------------------------------------------------|37|----------------------------------------------------|---------------------------------------------------------|
38| --context-parallel-size [int] | 开启CP对应的数量,默认为1,根据用户需求配置。 |38| --context-parallel-size [int] | 开启CP对应的数量,默认为1,根据用户需求配置。 |
39-| --cp-comm-type <b>all_gather</b> | 长序列并行算法选项,设置为`all_gather`, 开启KVAllGather长序列并行。 |39+| --cp-comm-type <b>all_gather</b> | 长序列并行算法选项,设置为`all_gather`,开启KVAllGather长序列并行。 |
40| --seq-length [int] | 输入序列的长度。 |40| --seq-length [int] | 输入序列的长度。 |
41 41 
42## 使用效果42## 使用效果
43 43 
44-利用多个计算设备对输入序列进行并行切分,降低单设备的内存消耗,相比不开启序列并行单步耗时增加,相比重计算计算效率提升。44+利用多个计算设备对输入序列进行并行切分,可降低单设备的内存消耗;与不开启序列并行相比,单步耗时有所增加,但与重计算相比计算效率提升。
45 45 
46## 注意事项46## 注意事项
47 47 
481. 开启KVAllGather长序列并行时需要同时设置`--transformer-impl transformer_engine`,否则特性不支持。481. 开启KVAllGather长序列并行时需要同时设置`--transformer-impl transformer_engine`,否则特性不支持。
49-2. 普通训练和 EOD Reset 均仅支持 `--attention-mask-type causal`。49+2. 普通训练和EOD Reset均仅支持 `--attention-mask-type causal`。
50-3. 对于定长padding训练场景,采用负载均衡的序列切分方式,`--seq-length`要求能被 2 * context-parallel-size整除。 50+3. 对于定长padding训练场景,采用负载均衡的序列切分方式,`--seq-length`要求能被2*`--context-parallel-size`整除。
51-4. EOD Reset 需设置 `--variable-seq-lengths --micro-batch-size 1`,各层统一使用 `all_gather`;不使用 Ring 的逐文档在线 pad。序列长度仍需满足原生 CP 切分要求。51+4. EOD Reset需设置 `--variable-seq-lengths --micro-batch-size 1`,各层统一使用 `all_gather`;不使用Ring的逐文档在线pad。序列长度仍需满足原生CP切分要求。
@@ -6,7 +6,7 @@
6 6 
7## 解决方案7## 解决方案
8 8 
9-与传统 KV cache 不同,MLA 并不直接存储完整的 key 和 value 矩阵,而是通过一个压缩隐向量来表示 key 和 value,借助低秩压缩技术降低 KV cache。在训练中,query 也会进行低秩压缩以降低激活值内存。下图对比了 MLA 与 MHA、Grouped-Query Attention (GQA)、Multi-Query Attention(MQA)在工作机制上的区别。9+与传统 KV cache 不同,MLA 并不直接存储完整的 key 和 value 矩阵,而是通过一个压缩隐向量来表示 key 和 value,借助低秩压缩技术降低 KV cache。在训练中,query 也会进行低秩压缩以降低激活值内存。下图对比了 MLA 与 MHA、Grouped-Query Attention(GQA)、Multi-Query Attention(MQA)在工作机制上的区别。
10![multi-head-latent-attention.png](../figures/multi-head-latent-attention.png)10![multi-head-latent-attention.png](../figures/multi-head-latent-attention.png)
11 11 
12更多关于 MLA 的细节可参见原文:12更多关于 MLA 的细节可参见原文:
@@ -40,4 +40,4 @@ DSA 参数见 [DSA](deepseek-sparse-attention.md)。
40 40 
41## 使用效果41## 使用效果
42 42 
43-与传统 MHA 相比,MLA 可以显著降低 KV 缓存占用,同时又具有恢复 key 和 value 矩阵中全部信息的能力,特征表达能力优于其他 KV cache 方法(例如 GQA, MQA 等),保证了模型的性能。43+与传统 MHA 相比,MLA可以显著降低KV cache占用,同时又具有恢复 key 和 value 矩阵中全部信息的能力,特征表达能力优于其他 KV cache 方法(例如 GQA、MQA 等),保证了模型的性能。
@@ -21,7 +21,7 @@
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 
@@ -29,7 +29,7 @@
29 29 
30* 减少空泡现象:通过将计算密集型任务重新分配到流水线的不同阶段,减少了因某些阶段计算负载过高而导致的空闲时间,提高了整个系统的吞吐量。30* 减少空泡现象:通过将计算密集型任务重新分配到流水线的不同阶段,减少了因某些阶段计算负载过高而导致的空闲时间,提高了整个系统的吞吐量。
31 31 
32-+ 优化计算流程:确保计算和通信资源被更加充分地利用,避免了因同步障碍造成的闲置浪费,使得每个计算单元都能高效工作。32+* 优化计算流程:确保计算和通信资源被更加充分地利用,避免了因同步障碍造成的闲置浪费,使得每个计算单元都能高效工作。
33 33 
34根据实际测试结果,在类DeepSeekV2百亿参数级别的MoE模型中,由于终端层的对数几率层等导致的计算负载不均所引起的性能瓶颈,使用自定义空操作层可以获得超过10%的端到端训练性能提升。34根据实际测试结果,在类DeepSeekV2百亿参数级别的MoE模型中,由于终端层的对数几率层等导致的计算负载不均所引起的性能瓶颈,使用自定义空操作层可以获得超过10%的端到端训练性能提升。
35 35 
@@ -2,7 +2,7 @@
2 2 
3## 背景与挑战3## 背景与挑战
4 4 
5-大模型训练过程中,往往会面临的显存不足的问题。5+大模型训练过程中,往往会面临显存不足的问题。
6 6 
7## 解决方案7## 解决方案
8 8 
@@ -11,7 +11,7 @@
11 11 
12## 使用场景12## 使用场景
13 13 
14-主要用于训练场景,用户内存不足或要进一步节省内存时。14+主要用于训练场景,用户显存不足或要进一步节省显存时。
15 15 
16## 使用方法16## 使用方法
17 17 
@@ -26,7 +26,7 @@
26 * 同时开启时,仅支持--recompute-method设置为block。26 * 同时开启时,仅支持--recompute-method设置为block。
27 * 同时开启时,将按照指定的全重计算和Norm重计算的层数做各自类型的重计算,即不会有一层既做全重计算又做Norm重计算。27 * 同时开启时,将按照指定的全重计算和Norm重计算的层数做各自类型的重计算,即不会有一层既做全重计算又做Norm重计算。
28 28 
29-* 执行优先级是先计算全重计算层,后Norm重计算层。29+* 执行优先级是先计算全重计算层,后计算Norm重计算层。
30 30 
31## 使用效果31## 使用效果
32 32 
@@ -1,4 +1,4 @@
1-# 参数与梯度 Buffer 对齐1+# 参数与梯度Buffer对齐
2 2 
3在分布式优化器计算参数布局时,对参数存储起始位置进行字节对齐。3在分布式优化器计算参数布局时,对参数存储起始位置进行字节对齐。
4 4 
@@ -11,4 +11,4 @@
11--param-and-grad-buffer-pad 51211--param-and-grad-buffer-pad 512
12```12```
13 13 
14-`--param-and-grad-buffer-pad` 默认不设置,值必须大于 0;Ascend 推荐设置为 512。当前不支持与 `--use-layer-wise-distributed-optimizer` 组合使用。14+`--param-and-grad-buffer-pad` 默认不设置,值必须大于0;Ascend推荐设置为512。当前不支持与`--use-layer-wise-distributed-optimizer`组合使用。
Mdocs/zh/features/pipeline-model-parallel-layout.md+31-31File content is under review, please try again later
@@ -12,15 +12,15 @@
12 12 
13**后端限制:** FP8/FP4 重计算必须使用 `--transformer-impl transformer_engine`。13**后端限制:** FP8/FP4 重计算必须使用 `--transformer-impl transformer_engine`。
14 14 
15-在显存不够的情况下可以开启重计算特性,且分为以下两种方式:15+在内存不够的情况下可以开启重计算特性,且分为以下两种方式:
16 16 
17* 选择性重计算(推荐):专注于对Transformer架构内的core_attention组件进行重计算。该策略保留了那些占用较小内存空间但重计算成本较高的激活值,同时,对占用较大内存但重计算成本相对较低的激活值执行激活重计算。此方法在保证模型性能的同时,实现了内存使用的高效管理。17* 选择性重计算(推荐):专注于对Transformer架构内的core_attention组件进行重计算。该策略保留了那些占用较小内存空间但重计算成本较高的激活值,同时,对占用较大内存但重计算成本相对较低的激活值执行激活重计算。此方法在保证模型性能的同时,实现了内存使用的高效管理。
18 18 
19-- 完全重计算:适用于内存资源极为受限的极端环境。在这种模式下,除了保存输入数据外,所有激活值均在需要时重新计算,最大限度地减少了对内存的依赖。19+* 完全重计算:适用于内存资源极为受限的极端环境。在这种模式下,除了保存输入数据外,所有激活值均在需要时重新计算,最大限度地减少了对内存的依赖。
20 20 
21## 使用方法21## 使用方法
22 22 
23-+ 选择性重计算:23+* 选择性重计算:
24`--recompute-granularity selective #开启选择性重计算`。24`--recompute-granularity selective #开启选择性重计算`。
25 25 
26* 完全重计算:26* 完全重计算:
@@ -29,13 +29,13 @@
29 29 
30`--recompute-method`可配置参数uniform或block,任选其一:30`--recompute-method`可配置参数uniform或block,任选其一:
31 31 
32-* `--recompute-method uniform`:将Transformer层均匀划分组(每组大小`--recompute-num-layers`),按组存储输入和激活值。32+* `--recompute-method uniform`:将Transformer层均匀划分为组(每组大小`--recompute-num-layers`),按组存储输入和激活值。
33 33 
34-+ `--recompute-method block`:将前`--recompute-num-layers`个Transformer层重计算,剩余层不进行重计算。34+* `--recompute-method block`:将前`--recompute-num-layers`个Transformer层重计算,剩余层不进行重计算。
35 35 
36### 说明36### 说明
37 37 
38-+ 当脚本配置了`--recompute-method block`、`--recompute-granularity full`、`--num-layers-per-virtual-pipeline-stage N`参数时,用户可以通过`--recompute-num-layers N`参数来配置每个vpp stage做多少层重计算,参数`--enable-recompute-layers-per-pp-rank`可用于修改此情况下`--recompute-num-layers N`参数的语义,新的语义表示无视vpp,按每个pp stage来配置重计算层数。38+当脚本配置了`--recompute-method block`、`--recompute-granularity full`、`--num-layers-per-virtual-pipeline-stage N`参数时,用户可以通过`--recompute-num-layers N`参数来配置每个vpp stage做多少层重计算,参数`--enable-recompute-layers-per-pp-rank`可用于修改此情况下`--recompute-num-layers N`参数的语义,新的语义表示无视vpp,按每个PP stage来配置重计算层数。
39 39 
40## 使用影响40## 使用影响
41 41 
@@ -43,4 +43,4 @@
43 43 
44* 通过避免长时间保留大量中间计算结果,大幅降低了对内存的需求。44* 通过避免长时间保留大量中间计算结果,大幅降低了对内存的需求。
45 45 
46-+ 重计算激活值会带来额外的计算成本,降低性能。因此重计算的使用和配置需要综合考虑内存占用情况。46+* 重计算激活值会带来额外的计算成本,降低性能。因此重计算的使用和配置需要综合考虑内存占用情况。
@@ -10,17 +10,20 @@
10 10 
11具体算法步骤如下:11具体算法步骤如下:
12 12 
13-1. FP32 = BF16 + Residual;13+1. FP32 = BF16 + Residual。
14-2. 前向计算前:将FP32参数转换为BF16格式,并保存残差(Residual);14+2. 前向计算前:将FP32参数转换为BF16格式,并保存残差(Residual)。
15-3. 优化器更新前:基于BF16参数和之前保存的残差,恢复FP32参数至其原始状态,随后进行参数更新;15+3. 优化器更新前:基于BF16参数和之前保存的残差,恢复FP32参数至其原始状态,随后进行参数更新。
164. 数值变换模拟:利用int32加减运算来等价模拟原始逻辑中FP32与BF16之间的相互转换,遵循IEEE 754标准的向偶数舍入规则。164. 数值变换模拟:利用int32加减运算来等价模拟原始逻辑中FP32与BF16之间的相互转换,遵循IEEE 754标准的向偶数舍入规则。
17 17 
18-请参照下图了解参数副本复用的具体流程。18+请参照下图了解参数副本复用的具体流程:
19+ 
20+图1 参数副本复用流程图
21+ 
19<p align="center"> <img src="../figures/reuse_fp32_param_a.png" height="300px" width="750px"></p>22<p align="center"> <img src="../figures/reuse_fp32_param_a.png" height="300px" width="750px"></p>
20 23 
21数值变换的详细逻辑如下图所示:24数值变换的详细逻辑如下图所示:
22 25 
23-### 图2 数值变换的详细逻辑26+图2 数值变换的详细逻辑图
24 27 
25<p align="center"> <img src="../figures/reuse_fp32_param_b.png" height="400px" width="750px"></p>28<p align="center"> <img src="../figures/reuse_fp32_param_b.png" height="400px" width="750px"></p>
26 29 
@@ -35,10 +38,10 @@
35 38 
36## 使用效果39## 使用效果
37 40 
38-* 对于Float16OptimizerWithFloat16Params类型的优化器,整体可节省 sizeof(bfloat16) * 模型参数量 的静态内存空间,且在多个模型上的测试表明,性能损耗低于1%。41+* 对于Float16OptimizerWithFloat16Params类型的优化器,整体可节省 sizeof(bfloat16) * 模型参数量的静态内存空间,且在多个模型上的测试表明,性能损耗低于1%。
39* 对于启用了分布式优化器的训练任务,总体节省的静态内存空间为 sizeof(bfloat16) * 模型参数量 / DP,同样地,性能损耗在测试中也控制在1%以内。42* 对于启用了分布式优化器的训练任务,总体节省的静态内存空间为 sizeof(bfloat16) * 模型参数量 / DP,同样地,性能损耗在测试中也控制在1%以内。
40 43 
41## 使用约束44## 使用约束
42 45 
43-1. 需使用 BF16。46+1. 需使用BF16。
442. 断点续训场景下,不支持修改切分方式及卡数。472. 断点续训场景下,不支持修改切分方式及卡数。
@@ -1,12 +1,12 @@
1-# rms_norm融合优化1+# RMSNorm融合优化
2 2 
3## 背景与挑战3## 背景与挑战
4 4 
5-在诸如LLaMA、LLaMA2和Baichuan等大型语言模型(LLM)中,RMSNorm(Root Mean Square Norm)作为一种归一化技术被广泛应用。然而,由于PyTorch框架本身未直接提供RMSNorm运算符接口,模型中常以自定义形式实现RMSNorm,这在一定程度上影响了执行效率。5+在诸如LLaMA、LLaMA2和Baichuan等大语言模型(LLM)中,RMSNorm(Root Mean Square Norm)作为一种归一化技术被广泛应用。然而,由于PyTorch框架本身未直接提供RMSNorm算子接口,模型中常以自定义形式实现RMSNorm,这在一定程度上影响了执行效率。
6 6 
7## 解决方法7## 解决方法
8 8 
9-MindSpeed 针对上述情况,对RMSNorm操作进行了融合优化,将其集成到单个运算符中,有效减少了数据传输次数和临时存储需求。算子接口见[rms_norm](../ops/rms_norm.md)。9+MindSpeed针对上述情况,对RMSNorm算子进行了融合优化,将其集成到单个算子中,有效减少了数据传输次数和临时内存需求。算子接口见[rms_norm](../ops/rms_norm.md)。
10 10 
11## 使用场景11## 使用场景
12 12 
@@ -17,7 +17,7 @@ MindSpeed 针对上述情况,对RMSNorm操作进行了融合优化,将其集
17 17 
18启用RMSNorm融合优化,需在训练脚本中加入以下参数配置:18启用RMSNorm融合优化,需在训练脚本中加入以下参数配置:
19`--use-fused-rmsnorm`19`--use-fused-rmsnorm`
20-Mcore分支下该算子仅支持使能融合特性。20+需要注意的是,Mcore分支下该算子仅支持使能融合特性。
21 21 
22## 使用效果 22## 使用效果
23 23 
@@ -2,11 +2,11 @@
2 2 
3## 背景与挑战3## 背景与挑战
4 4 
5-RoPE (Rotary Positional Embedding,旋转式位置嵌入) 是一种位置编码技术,广泛应用于大型语言模型中,用于有效编码文本序列的位置信息。RoPE结合了绝对位置编码的稳定性与相对位置编码的灵活性,同时具备优秀的长度泛化能力。尽管RoPE已经在诸如LLaMA和GLM等多个前沿模型中得到采纳,但PyTorch框架目前尚未提供专门针对RoPE的实现与优化。因此,模型开发者通常需要通过自定义方式来实现RoPE,而这往往伴随着较高的计算和内存开销。5+RoPE(Rotary Positional Embedding,旋转式位置嵌入)是一种位置编码技术,广泛应用于大语言模型中,用于有效编码文本序列的位置信息。RoPE结合了绝对位置编码的稳定性与相对位置编码的灵活性,同时具备优秀的长度泛化能力。尽管RoPE已经在诸如LLaMA和GLM等多个前沿模型中得到采纳,但PyTorch框架目前尚未提供专门针对RoPE的实现与优化。因此,模型开发者通常需要通过自定义方式来实现RoPE,而这往往伴随着较高的计算和内存开销。
6 6 
7## 解决方案7## 解决方案
8 8 
9-为了解决上述问题,我们引入了针对Rotary Embedding的融合优化方案。通过将RoPE操作整合为单一算子,我们显著减少了数据传输次数和临时存储需求,进而优化了模型训练的性能。这一优化由MindSpeed通过调用torch_npu侧接口实现,有效提升了RoPE在模型中的执行效率。9+为了解决上述问题,我们引入了针对RoPE的融合优化方案。通过将RoPE操作整合为单一算子,我们显著减少了数据传输次数和临时存储需求,进而优化了模型训练的性能。这一优化由MindSpeed通过调用torch_npu侧接口实现,有效提升了RoPE在模型中的执行效率。
10 10 
11## 使用场景11## 使用场景
12 12 
@@ -17,9 +17,9 @@ RoPE (Rotary Positional Embedding,旋转式位置嵌入) 是一种位置编码
17## 使用方法17## 使用方法
18 18 
19* 确保模型配置中已设定以下参数:19* 确保模型配置中已设定以下参数:
20-`--position-embedding-type rope`20+`--position-embedding-type rope`
21 21 
22-* RoPE 融合默认开启,使用 `--no-rope-fusion` 关闭。非 RoPE 位置编码会关闭融合。EOD Reset 会关闭该融合。22+* RoPE融合默认开启,使用`--no-rope-fusion`关闭。非RoPE编码会关闭融合。EOD Reset会关闭该融合。
23 23 
24## 使用效果24## 使用效果
25 25 
@@ -8,11 +8,11 @@
8 8 
9序列并行(Sequence Parallelism,SP)策略在张量并行的基础上进一步提高计算效率,是一种通过将输入数据的序列维度进行切分的并行计算方式。9序列并行(Sequence Parallelism,SP)策略在张量并行的基础上进一步提高计算效率,是一种通过将输入数据的序列维度进行切分的并行计算方式。
10 10 
11-将 LayerNorm 以及 Dropout 等操作的输入按序列维度进行了切分,使得各个设备上面只需要做一部分的 Dropout 和 LayerNorm 等操作即可。11+将LayerNorm以及Dropout等操作的输入按序列维度进行了切分,使得各个设备上面只需要做一部分的Dropout和LayerNorm等操作即可。
12 12 
13-为了方便理解,以下图为例:假设输入$X$的大小为$ s \times b \times h $,按照序列维度切分$X=[X_1^s,X_2^s]$,经过LayerNorm操作后的结果为$Y=[Y_1^s,Y_2^s]$,随后进行张量模型并行。13+为了方便理解,以下图为例:假设输入$X$的大小为$ s \times b \times h $,按照序列维度切分$X=[X_1^s,X_2^s]$,经过LayerNorm操作后的结果为$Y=[Y_1^s,Y_2^s]$,随后进行张量并行。
14 14 
15-![image.png](../figures/sequence-parallel.png)15+![张量并行](../figures/sequence-parallel.png)
16 16 
17[原文链接](https://arxiv.org/pdf/2205.05198)17[原文链接](https://arxiv.org/pdf/2205.05198)
18 18 
@@ -27,7 +27,7 @@
27 27 
28序列并行依赖张量并行,因此启用序列并行,需在训练脚本中加入以下参数配置:28序列并行依赖张量并行,因此启用序列并行,需在训练脚本中加入以下参数配置:
29 29 
30-`--tensor-model-parallel-size N # 设置张量模型并行大小,N为单个并行组内的NPU数目`30+`--tensor-model-parallel-size N # 设置张量模型并行大小,N为单个并行组内的NPU数目`
31`--sequence-parallel # 开启序列并行`31`--sequence-parallel # 开启序列并行`
32 32 
33## 使用效果33## 使用效果
@@ -1,6 +1,6 @@
1-# Transformer 层输入卸载1+# Transformer层输入卸载
2 2 
3-通过卸载 Transformer 层输入,减少训练时保留激活占用的设备内存。3+通过卸载Transformer 层输入,减少训练时保留激活占用的设备内存。
4 4 
5## 使用方法5## 使用方法
6 6 
@@ -2,26 +2,26 @@
2 2 
3## 背景与挑战3## 背景与挑战
4 4 
5-在大模型训练中,通常会通过 BF16 格式进行前反向的计算,在梯度更新的时候使用 FP32 的格式,5+在大模型训练中,通常会通过BF16格式进行前反向的计算,在梯度更新的时候使用FP32的格式,
6-因此导致优化器中需要保存一份 FP32 的权重以及两个 FP32 的动量,显存占用为 `参数量 * 12` Bytes。6+因此导致优化器中需要保存一份FP32的权重以及两个FP32的动量,显存占用为 `参数量 * 12` 字节。
7-这部分显存在前反向阶段并不会被使用,且会推高显存峰值,导致模型训练 OOM。7+这部分显存在前反向阶段并不会被使用,且会推高显存峰值,导致模型训练OOM。
8-虽然可以通过分布式优化器等特性来减少这部分的显存占用,但无法完全消除,且减少比例过于依赖 DP 数。8+虽然可以通过分布式优化器等特性来减少这部分的显存占用,但无法完全消除,且减少比例过于依赖DP数。
9 9 
10## 解决思路10## 解决思路
11 11 
12本特性通过在前反向期间,卸载优化器状态到host侧内存,device侧仅保留逻辑视图,12本特性通过在前反向期间,卸载优化器状态到host侧内存,device侧仅保留逻辑视图,
13-在 step 更新阶段再加载回 device 侧,来降低显存峰值。13+在step更新阶段再加载回device侧,来降低显存峰值。
14 14 
15## 解决方案15## 解决方案
16 16 
171. 在优化器初始化 `shard_fp32_from_float16_groups` 的时候,会从模型权重(bf16)复制权重到优化器权重(fp32),171. 在优化器初始化 `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-![img.png](../figures/swap-optimizer.png)24+![执行流程](../figures/swap-optimizer.png)
25 25 
26## 使用场景26## 使用场景
27 27 
@@ -29,11 +29,11 @@
29 29 
30## 使用方法30## 使用方法
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 
38```bash38```bash
39export CPU_AFFINITY_CONF=1,lazy_bind:039export CPU_AFFINITY_CONF=1,lazy_bind:0
@@ -18,11 +18,11 @@
18 18 
19### b. 内存节省19### b. 内存节省
20 20 
21-对于不需要重计算的场景,只开启`--swap-attention`,可以在几乎不损耗性能的情况下,节省内存,以支持更大的模型的配置。21+对于不需要重计算的场景,只开启`--swap-attention`,可以在几乎不损耗性能的情况下,节省内存,以支持更大模型的配置。
22 22 
23## 使用方法23## 使用方法
24 24 
25-需要添加参数`--swap-attention`。使用前提是开启flash attention融合算子。25+需要添加参数`--swap-attention`。使用前提是开启Flash Attention融合算子。
26 26 
27可选参数`--swap-modules`:参数类型为string,默认值为"input_norm,self_attention,post_attention_norm",可根据模型自行配置module。27可选参数`--swap-modules`:参数类型为string,默认值为"input_norm,self_attention,post_attention_norm",可根据模型自行配置module。
28 28 
@@ -40,11 +40,11 @@
40 40 
41## 使用效果41## 使用效果
42 42 
43-与完全重计算相比,有性能收益;43+与完全重计算相比,有性能收益。
44-与不重计算相比,有内存收益;44+与不重计算相比,有内存收益。
45 45 
46## 注意事项46## 注意事项
47 47 
48-1. `--recompute-num-layers [int]`中的[int]层数指的是每一个pp stage的层数。[int]的取值应该小于等于num-layers/pipeline-model-parallel-size.48+1. `--recompute-num-layers [int]`中的[int]层数指的是每一个PP stage的层数。[int]的取值应该小于等于num-layers/pipeline-model-parallel-size。
49-2. 若出现性能波动,可能是跨NUMA内存访问引起,可尝试通过进程绑核缓解 `export CPU_AFFINITY_CONF=1,lazy_bind:0`49+2. 若出现性能波动,可能是跨NUMA内存访问引起,可尝试通过进程绑核缓解 `export CPU_AFFINITY_CONF=1,lazy_bind:0`。
503. 如需卸载层输入,使用独立的 [Transformer 层输入卸载](swap-layer-input.md) 开关 `--swap-layer-input`。503. 如需卸载层输入,使用独立的 [Transformer 层输入卸载](swap-layer-input.md) 开关 `--swap-layer-input`。
@@ -1,12 +1,12 @@
1-# swiglu融合优化1+# SwiGLU融合优化
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 
9-为应对这一挑战,MindSpeed对SwiGLU操作进行了融合优化,将其封装为一个高性能的融合算子,显著减少了数据在内存间的传输次数以及临时数据的存储需求。算子接口见[swiglu](../ops/swiglu.md)。9+为应对这一挑战,MindSpeed对SwiGLU操作进行了融合优化,将其封装为一个高性能的融合算子,显著减少了数据在内存间的传输次数以及临时数据的存储需求。算子接口见[SwiGLU](../ops/swiglu.md)。
10 10 
11## 使用场景11## 使用场景
12 12 
@@ -37,4 +37,4 @@
37 37 
38## 使用效果38## 使用效果
39 39 
40-通过张量并行策略,利用多台计算设备分担模型存储与计算负荷,不仅显著降低单设备的内存占用,有效缩短了模型训练周期。此外,由于进行了参数的切分,该策略可以解决模型某层参数量较大时,单一计算设备无法全部容纳的问题。40+通过张量并行策略,利用多台计算设备分担模型存储与计算负荷,不仅显著降低单设备的内存占用,还有效缩短了模型训练周期。此外,由于进行了参数的切分,该策略可以解决模型某层参数量较大时,单一计算设备无法全部容纳的问题。
@@ -3,9 +3,9 @@
3## 背景与挑战3## 背景与挑战
4 4 
5Transformer Engine (TE) 是一个专门用于加速基于 Transformer 架构的模型进行训练和推理的库。当前的多个第三方框架依赖该加速库提供的API进行推理及训练,MindSpeed需要对这些需求做出对等支持。<!-- codespell:ignore -->5Transformer Engine (TE) 是一个专门用于加速基于 Transformer 架构的模型进行训练和推理的库。当前的多个第三方框架依赖该加速库提供的API进行推理及训练,MindSpeed需要对这些需求做出对等支持。<!-- codespell:ignore -->
6-TE支持在昇腾NPU硬件平台使能8位浮点数(FP8)运算,以使用更低的内存提供更佳的性能表现。TE提供了一些Transformer结构的典型模块,以及低精度状态管理器等组件,可以无缝替换基于Megatron-LM构建的大模型,以实现低精度训练。6+TE支持在昇腾NPU硬件平台使能8位浮点数(FP8)运算,以使用更低的内存占用提供更佳的性能表现。TE提供了一些Transformer结构的典型模块,以及低精度状态管理器等组件,可以无缝替换基于Megatron-LM构建的大模型,以实现低精度训练。
7-TransformerEngineNPU 提供的 TE 模块可以替换 NVIDIA 提供的 TE 模块,从而更容易构建Transformer层的模块。TE从模块内部维护低精度训练所需要的缩放因子(scale factors)及其他低精度训练的状态值,从而帮助用户更容易地从混合精度训练迁移到低精度训练。7+TransformerEngineNPU 提供的 TE 模块可以替换 NVIDIA 提供的 TE 模块,从而更容易构建Transformer层的模块。TE在模块内部维护低精度训练所需要的缩放因子(scaling factors)及其他低精度训练的状态值,从而帮助用户更容易地从混合精度训练迁移到低精度训练。
8-此外,TransformerEngineNPU 提供的 TE 模块还包含了通算融合(Communication Over Computation)的实现,将原本应通信计算串行执行的任务,拆分成更细粒度的子任务,从而将计算和通信相互掩盖以提升效率提高模型吞吐。8+此外,TransformerEngineNPU 提供的 TE 模块还包含了通算融合(Communication Over Computation)的实现,将原本应通信与计算串行执行的任务,拆分成更细粒度的子任务,从而将计算和通信相互掩盖以提升效率提高模型吞吐。
9 9 
10## 解决方法10## 解决方法
11 11 
@@ -18,15 +18,15 @@ TransformerEngineNPU 提供昇腾 NPU 上的 TE 接口,MindSpeed 提供 HiF8 /
18 18 
19![FP8 Training Diagram](../figures/fp8.png)19![FP8 Training Diagram](../figures/fp8.png)
20低精度训练流程中主要是将前向传播 (Fprop)、激活反向传播 (Dgrad) 和权重反向传播 (Wgrad)中的GEMM,量化为FP8的精度执行运算。20低精度训练流程中主要是将前向传播 (Fprop)、激活反向传播 (Dgrad) 和权重反向传播 (Wgrad)中的GEMM,量化为FP8的精度执行运算。
21-整网训练流程仍然是以BF16/FP16的AMP混合精度训练流程,但在特定的计算算子以FP8的精度进行计算,主要是Linear层中的Matmul计算,包括Fprop、Dgrad和Wgrad21+整网训练流程仍然是以BF16/FP16的AMP混合精度训练流程为主,但在特定的计算算子以FP8的精度进行计算,主要是Linear层中的Matmul计算,包括Fprop、Dgrad和Wgrad。
22-在高精度量化为低精度tensor的过程中,存在着不同的scaling策略:22+在高精度量化为低精度tensor的过程中,存在着不同的scaling策略:
23 23 
24- Delayed Scaling:根据历史amax值计算scaling factor,然后使用scaling factor对tensor进行量化。24- Delayed Scaling:根据历史amax值计算scaling factor,然后使用scaling factor对tensor进行量化。
25- Tensorwise Scaling:在线策略,实时计算amax并应用scaling factor对tensor进行量化。25- Tensorwise Scaling:在线策略,实时计算amax并应用scaling factor对tensor进行量化。
26- Blockwise Scaling:对tensor进行分块,然后分别计算amax并应用scaling factor对tensor进行量化。26- Blockwise Scaling:对tensor进行分块,然后分别计算amax并应用scaling factor对tensor进行量化。
27- MX Scaling: 通过块级共享scale与低位宽元素组合,将浮点向量转化为MX块,实现动态量化。27- MX Scaling: 通过块级共享scale与低位宽元素组合,将浮点向量转化为MX块,实现动态量化。
28 28 
29-支持的低精度的数据格式有:29+支持的低精度的数据格式有:
30 30 
31- E4M3: 1个符号位,4个指数位,3个尾数位,表示范围为-448到+448。31- E4M3: 1个符号位,4个指数位,3个尾数位,表示范围为-448到+448。
32- E5M2: 1个符号位,5个指数位,2个尾数位,表示范围为-57344到+57344。32- E5M2: 1个符号位,5个指数位,2个尾数位,表示范围为-57344到+57344。
@@ -54,13 +54,13 @@ TransformerEngineNPU 提供昇腾 NPU 上的 TE 接口,MindSpeed 提供 HiF8 /
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(`--fp8-format hif8 --fp8-recipe delayed` 同样走 FP8 GMM);其他 recipe(含 blockwise)回退 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-format hif8` 选择:使用 `--fp8-recipe delayed`(按 delayed 调度,单个外层量化上下文);`tensorwise` 为逐张量 current scaling。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。
63-- 使用transformer_engine时需同时开启`--use-flash-attn`63+- 使用transformer_engine时需同时开启`--use-flash-attn`。
64 64 
65## 参数组合限制65## 参数组合限制
66 66 
@@ -8,7 +8,7 @@
8 8 
9* 内存限制:随着序列长度的增加,系统所需的内存资源也会成倍增长,导致内存不足。9* 内存限制:随着序列长度的增加,系统所需的内存资源也会成倍增长,导致内存不足。
10 10 
11-+ 计算效率:长序列的处理往往需要大量的计算资源,而传统的并行方法可能无法充分利用这些资源,导致计算效率低下。11+* 计算效率:长序列的处理往往需要大量的计算资源,而传统的并行方法可能无法充分利用这些资源,导致计算效率低下。
12 12 
13* 通信开销:在分布式系统中,长序列的处理可能涉及到多个节点之间的通信,而传统的并行方法可能产生较大的通信开销,影响整体性能。13* 通信开销:在分布式系统中,长序列的处理可能涉及到多个节点之间的通信,而传统的并行方法可能产生较大的通信开销,影响整体性能。
14 14 
@@ -16,12 +16,12 @@ Ulysses长序列并行是一种针对上述挑战设计的创新方案,它能
16 16 
17## 解决方案17## 解决方案
18 18 
19-支持 Ulysses长序列并行方案,以此解决序列维度扩展问题。19+支持Ulysses长序列并行方案,以此解决序列维度扩展问题。
20 20 
21### 解决思路21### 解决思路
22 22 
23首先,Ulysses将各个样本在序列维度上分割给参与的计算设备。然后,在attention计算之前,对已分割的查询(Q)、键(K)和值(V)执行all-to-all通信操作,以便每个计算设备接收完整的序列,但仅用于attention-heads的非重叠子集。这使得参与的计算设备可以并行计算不同的注意力头。最后,Ulysses还可以使用另一个all-to-all在注意力头上收集结果,同时重新在序列维度上进行分区。23首先,Ulysses将各个样本在序列维度上分割给参与的计算设备。然后,在attention计算之前,对已分割的查询(Q)、键(K)和值(V)执行all-to-all通信操作,以便每个计算设备接收完整的序列,但仅用于attention-heads的非重叠子集。这使得参与的计算设备可以并行计算不同的注意力头。最后,Ulysses还可以使用另一个all-to-all在注意力头上收集结果,同时重新在序列维度上进行分区。
24-具体细节参考文献[DeepSpeed Ulysses: System Optimizations for Enabling Training of Extreme Long Sequence Transformer Models](https://arxiv.org/pdf/2309.14509),执行流程如下图所示:24+具体细节参考文献[DeepSpeed Ulysses: System Optimizations for Enabling Training of Extreme Long Sequence Transformer Models](https://arxiv.org/pdf/2309.14509),执行流程如下图所示:
25 25 
26#### 图1 Ulysses切分原理26#### 图1 Ulysses切分原理
27 27 
@@ -29,7 +29,7 @@ Ulysses长序列并行是一种针对上述挑战设计的创新方案,它能
29 29 
30## 使用场景30## 使用场景
31 31 
32-**后端限制:** CP>1 必须设置 `--transformer-impl transformer_engine`。32+**后端限制:** CP>1必须设置 `--transformer-impl transformer_engine`。
33 33 
34num-attention-heads要能够被tensor-model-parallel-size * context-parallel-size整除。34num-attention-heads要能够被tensor-model-parallel-size * context-parallel-size整除。
35 35 
@@ -48,7 +48,7 @@ num-attention-heads要能够被tensor-model-parallel-size * context-parallel-siz
48| 普通训练 | causal、general |48| 普通训练 | causal、general |
49| EOD Reset | 不支持 |49| EOD Reset | 不支持 |
50 50 
51-CP>1 时设置 `--transformer-impl transformer_engine`;Ulysses 不支持 EOD Reset。51+CP>1时设置 `--transformer-impl transformer_engine`;Ulysses 不支持 EOD Reset。
52 52 
53使用 `--cp-comm-type` 选择通信方式。53使用 `--cp-comm-type` 选择通信方式。
54 54 
@@ -67,8 +67,8 @@ CP>1 时设置 `--transformer-impl transformer_engine`;Ulysses 不支持 EOD R
67 <tr>67 <tr>
68 <td>--cp-comm-type <b>a2a</b></td>68 <td>--cp-comm-type <b>a2a</b></td>
69 <td>69 <td>
70- 设置为 a2a 开启Ulysses长序列并行。<br>70+ 设置为a2a开启Ulysses长序列并行。<br>
71- cp-comm-type 的默认值为 p2p;a2a+p2p 对应混合长序列并行。71+ cp-comm-type的默认值为p2p;a2a+p2p 对应混合长序列并行。
72 </td>72 </td>
73 </tr>73 </tr>
74 </tbody>74 </tbody>
@@ -81,4 +81,4 @@ CP>1 时设置 `--transformer-impl transformer_engine`;Ulysses 不支持 EOD R
81## 鸣谢81## 鸣谢
82 82 
831.GitHub项目地址:831.GitHub项目地址:
84-<https://github.com/microsoft/DeepSpeed/tree/master/blogs/deepspeed-ulysses>84+[DeepSpeed Ulysses 官方博客](https://github.com/microsoft/DeepSpeed/tree/master/blogs/deepspeed-ulysses)
@@ -2,11 +2,11 @@
2 2 
3## 背景与挑战3## 背景与挑战
4 4 
5-在大集群训练中,PP的增大会对前些个stage造成较大的显存压力;同时我们观察到,在增大梯度累积的情况下,优化器部分的一二阶动量显存swap的开销可忽略不计,因此可通过将优化器部分的显存swap到cpu上来节省整网显存,而当前分布式优化器逻辑复杂,并且与各种通信并行(如overlap-grad-reduce/overlap-param-gather等)相互耦合,因此实现一套Swap优化器显存的系统较为复杂。5+在大集群训练中,PP的增大会对前几个stage造成较大的显存压力;同时我们观察到,在增大梯度累积的情况下,优化器部分的一二阶动量显存swap的开销可忽略不计,因此可通过将优化器部分的显存swap到CPU上来节省整网显存,而当前分布式优化器逻辑复杂,并且与各种通信并行(如overlap-grad-reduce/overlap-param-gather等)相互耦合,因此实现一套Swap优化器显存的系统较为复杂。
6 6 
7## 解决方案7## 解决方案
8 8 
9-为避免引入复杂的Swap系统工程,和多流带来的额外显存与性能开销,借助昇腾驱动的虚拟内存原生能力,可以实现申请一个实际内存在Host侧,但内存地址可被映射在device上的张量,并且该张量可参与绝大多数NPU算子计算(除涉及随路计算的算子),基于此我们可以通过修改一行代码来实现优化器动量的Swap功能:9+为避免引入复杂的Swap系统工程,和多流带来的额外显存与性能开销,借助昇腾驱动的虚拟内存原生能力,可以实现申请一个实际内存在Host侧,但内存地址可被映射在Device上的张量,并且该张量可参与绝大多数NPU算子计算(除涉及随路计算的算子),基于此我们可以通过修改一行代码来实现优化器动量的Swap功能:
10 10 
11```python11```python
12 12 
@@ -27,14 +27,14 @@ state['exp_avg_sq'] = torch_npu.empty_with_swapped_memory(p.size(), device=p.dev
27 27 
28如下为图示对比说明:28如下为图示对比说明:
29 29 
30-![Alt text](../figures/virtual-optimizer.png)30+![与Swap对比图](../figures/virtual-optimizer.png)
31 31 
32**优势分析**:32**优势分析**:
33 33 
34- 虚拟内存能够节省两次UB与HBM的搬运时长,直接从硬件执行访问。34- 虚拟内存能够节省两次UB与HBM的搬运时长,直接从硬件执行访问。
35- 基于虚拟内存的搬运可以利用算子本身的流水机制(MTE2/MTE3/Vector),与计算产生指令级的并行掩盖,避免引入额外的流同步性能与内存的开销(如Swap引入的多流)。35- 基于虚拟内存的搬运可以利用算子本身的流水机制(MTE2/MTE3/Vector),与计算产生指令级的并行掩盖,避免引入额外的流同步性能与内存的开销(如Swap引入的多流)。
36 36 
37-**劣势说明**:申请的Host虚拟内存无法实现随路计算(没有硬件随路计算单元) 37+**劣势说明**:申请的Host虚拟内存无法实现随路计算(没有硬件随路计算单元)。
38 38 
39## 使用方法39## 使用方法
40 40 
@@ -42,9 +42,9 @@ state['exp_avg_sq'] = torch_npu.empty_with_swapped_memory(p.size(), device=p.dev
42 42 
431. 希望Swap掉所有的一二阶动量,则可以采用`--virtual-optimizer all`指定。431. 希望Swap掉所有的一二阶动量,则可以采用`--virtual-optimizer all`指定。
442. 希望每一个PP Stage Swap同样大小的显存(如我希望每个Stage swap掉2GB的显存),则可以采用`--virtual-optimizer 2.0`指定。442. 希望每一个PP Stage Swap同样大小的显存(如我希望每个Stage swap掉2GB的显存),则可以采用`--virtual-optimizer 2.0`指定。
45-3. 希望每一个PP Stage Swap不同的显存(假设有四个PP Stage,我分别希望Swap掉 6 5 4 3GB的显存),则可以采用`--virtual-optimizer 6 5 4 3`指定。45+3. 希望每一个PP Stage Swap不同的显存(假设有四个PP Stage,我分别希望Swap掉6GB 5GB 4GB 3GB的显存),则可以采用`--virtual-optimizer 6 5 4 3`指定。
46 46 
47-推荐配置47+推荐配置:
48 48 
49```bash49```bash
50export CPU_AFFINITY_CONF=1,lazy_bind:050export CPU_AFFINITY_CONF=1,lazy_bind:0
@@ -109,4 +109,4 @@ exp_avg_cpu = exp_avg_swap.cpu()
109print(f"exp_avg_cpu: {exp_avg_cpu}")109print(f"exp_avg_cpu: {exp_avg_cpu}")
110```110```
111 111 
112-- 该特性的环境依赖最新Driver(25.0.RC1) / CANN(8.1.RC1) / PTA(2025年Q2商发)112+- 该特性的环境依赖最新Driver(25.0.RC1) / CANN(8.1.RC1) / PTA(2025年Q2商发)。
@@ -10,20 +10,22 @@
10 10 
11虚拟流水线并行(Virtual Pipeline Parallelism,VPP)的核心在于,在不增加设备数量的前提下,将模型进一步细分为更多阶段,以增加通信量为代价,换取更低的空泡比率。在设备数量不变的情况下,分出更多的流水线阶段,以更多的通信量,换取空泡比率降低。11虚拟流水线并行(Virtual Pipeline Parallelism,VPP)的核心在于,在不增加设备数量的前提下,将模型进一步细分为更多阶段,以增加通信量为代价,换取更低的空泡比率。在设备数量不变的情况下,分出更多的流水线阶段,以更多的通信量,换取空泡比率降低。
12 12 
13-### 图1 虚拟流水线并行示意图13+图1 虚拟流水线并行示意图
14 14 
15-![alt text](../figures/virtual-pipeline.PNG)15+![虚拟流水线并行阶段划分示意图](../figures/virtual-pipeline.PNG)
16 16 
17[原文链接](https://dl.acm.org/doi/10.1145/3458817.3476209)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 
21+```text
21 Device 0: [1, 2] [9, 10]22 Device 0: [1, 2] [9, 10]
22 Device 1: [3, 4] [11, 12]23 Device 1: [3, 4] [11, 12]
23 Device 2: [5, 6] [13, 14]24 Device 2: [5, 6] [13, 14]
24 Device 3: [7, 8] [15, 16]25 Device 3: [7, 8] [15, 16]
26+```
25 27 
26-前向的顺序为 Device 0 -> Device 1 -> Device 2 -> Device 3 -> Device 0 -> Device 1 -> Device 2 -> Device 328+前向的顺序为 Device 0 -> Device 1 -> Device 2 -> Device 3 -> Device 0 -> Device 1 -> Device 2 -> Device 3。
27 29 
28## 使用场景30## 使用场景
29 31 
@@ -38,7 +40,7 @@
38 40 
39### 注意41### 注意
40 42 
41-若 `N * PP == num_layers`,应移除 `--num-layers-per-virtual-pipeline-stage`;VPP size 为 1 时退化为普通 PP,并关闭 `overlap-p2p-comm`。43+若`N * PP == num_layers`,应移除`--num-layers-per-virtual-pipeline-stage`;VPP大小为1时退化为普通PP,并关闭`--overlap-p2p-communication`。
42 44 
431. Megatron虚拟流水线并行(VPP)对权重的分割模式具有直接影响。在保存或加载权重文件时,务必保持VPP配置参数的一致性,以确保模型权重的准确加载和系统的稳定运行。451. Megatron虚拟流水线并行(VPP)对权重的分割模式具有直接影响。在保存或加载权重文件时,务必保持VPP配置参数的一致性,以确保模型权重的准确加载和系统的稳定运行。
44 46 
@@ -84,6 +84,12 @@ class NoopLayerGraph:
84 self.is_moe_layer = False84 self.is_moe_layer = False
85 self.layer = layer85 self.layer = layer
86 86 
87+ def set_output_boundary(self, detached_output):
88+ self.unperm2_graph = (self.unperm2_graph[0], detached_output)
89+ 
90+ def get_output_boundary(self):
91+ return self.unperm2_graph[1]
92+ 
87 def record_layer_inputs(self, *args):93 def record_layer_inputs(self, *args):
88 self.layer_inputs = args94 self.layer_inputs = args
89 95 
@@ -145,6 +151,12 @@ class LayerGraph:
145 self.act_ckpt_manager = None151 self.act_ckpt_manager = None
146 self.remote_hot_act_ckpt_manager = None152 self.remote_hot_act_ckpt_manager = None
147 153 
154+ def set_output_boundary(self, detached_output):
155+ self.unperm2_graph = (self.unperm2_graph[0], detached_output)
156+ 
157+ def get_output_boundary(self):
158+ return self.unperm2_graph[1]
159+ 
148 def record_layer_inputs(self, *args):160 def record_layer_inputs(self, *args):
149 self.layer_inputs = args161 self.layer_inputs = args
150 162 
@@ -106,7 +106,9 @@ def forward_backward_no_pipelining(
106 model_graph[-1].mlp_mhc_post_graph[1].grad106 model_graph[-1].mlp_mhc_post_graph[1].grad
107 ) # get final_layernorm input_tensor.grad107 ) # get final_layernorm input_tensor.grad
108 else:108 else:
109- output_tensor_grad = model_graph[-1].unperm2_graph[1].grad # get final_layernorm input_tensor.grad109+ output_tensor_grad = (
110+ model_graph[-1].get_output_boundary().grad
111+ ) # get final_layernorm input_tensor.grad
110 112 
111 # prepare FBOverlap kwargs for next forward_step113 # prepare FBOverlap kwargs for next forward_step
112 fb_overlap_kwargs = {114 fb_overlap_kwargs = {
@@ -144,7 +146,7 @@ def forward_backward_no_pipelining(
144 if getattr(args, 'enable_mhc', False):146 if getattr(args, 'enable_mhc', False):
145 output_tensor_grad = model_graph[-1].mlp_mhc_post_graph[1].grad # get final_layernorm input_tensor.grad147 output_tensor_grad = model_graph[-1].mlp_mhc_post_graph[1].grad # get final_layernorm input_tensor.grad
146 else:148 else:
147- output_tensor_grad = model_graph[-1].unperm2_graph[1].grad # get final_layernorm input_tensor.grad149+ output_tensor_grad = model_graph[-1].get_output_boundary().grad # get final_layernorm input_tensor.grad
148 150 
149 backward_step(input_tensor, output_tensor, output_tensor_grad, config, model_graph)151 backward_step(input_tensor, output_tensor, output_tensor_grad, config, model_graph)
150 152 
@@ -263,7 +263,7 @@ def transformer_block_forward(
263 if getattr(args, 'enable_mhc', False):263 if getattr(args, 'enable_mhc', False):
264 layer_graphs[-1].mlp_mhc_post_graph = (layer_graphs[-1].mlp_mhc_post_graph[0], detached_hidden_states)264 layer_graphs[-1].mlp_mhc_post_graph = (layer_graphs[-1].mlp_mhc_post_graph[0], detached_hidden_states)
265 else:265 else:
266- layer_graphs[-1].unperm2_graph = (layer_graphs[-1].unperm2_graph[0], detached_hidden_states)266+ layer_graphs[-1].set_output_boundary(detached_hidden_states)
267 hidden_states = self.final_layernorm(detached_hidden_states)267 hidden_states = self.final_layernorm(detached_hidden_states)
268 268 
269 if torch.is_grad_enabled() or get_args().schedules_method == 'dualpipev':269 if torch.is_grad_enabled() or get_args().schedules_method == 'dualpipev':
@@ -293,8 +293,10 @@ def transformer_block_forward_backward_overlaping(
293 pp_comm_params: P2PCommParams = None,293 pp_comm_params: P2PCommParams = None,
294 bwd_pp_comm_params: P2PCommParams = None,294 bwd_pp_comm_params: P2PCommParams = None,
295 input_ids: Tensor = None,295 input_ids: Tensor = None,
296+ layer_backward=None,
296):297):
297 args = get_args()298 args = get_args()
299+ layer_backward = transformer_layer_backward if layer_backward is None else layer_backward
298 if bwd_block_graphs is None:300 if bwd_block_graphs is None:
299 return transformer_block_forward(301 return transformer_block_forward(
300 self,302 self,
@@ -427,7 +429,7 @@ def transformer_block_forward_backward_overlaping(
427 429 
428 while bwd_block_graphs:430 while bwd_block_graphs:
429 bwd_layer_graph = bwd_block_graphs.pop(-1)431 bwd_layer_graph = bwd_block_graphs.pop(-1)
430- bwd_layer_output_grad = transformer_layer_backward(bwd_layer_output_grad, bwd_layer_graph)432+ bwd_layer_output_grad = layer_backward(bwd_layer_output_grad, bwd_layer_graph)
431 433 
432 # Final layer norm.434 # Final layer norm.
433 if fwd_block.post_process and fwd_block.post_layer_norm and fwd_block.final_layernorm is not None:435 if fwd_block.post_process and fwd_block.post_layer_norm and fwd_block.final_layernorm is not None:
@@ -438,7 +440,7 @@ def transformer_block_forward_backward_overlaping(
438 detached_hidden_states,440 detached_hidden_states,
439 )441 )
440 else:442 else:
441- fwd_layer_graphs[-1].unperm2_graph = (fwd_layer_graphs[-1].unperm2_graph[0], detached_hidden_states)443+ fwd_layer_graphs[-1].set_output_boundary(detached_hidden_states)
442 444 
443 fwd_hidden_states = fwd_block.final_layernorm(detached_hidden_states)445 fwd_hidden_states = fwd_block.final_layernorm(detached_hidden_states)
444 446 
@@ -466,11 +468,17 @@ def transformer_block_forward_backward_overlaping(
466 return fwd_hidden_states468 return fwd_hidden_states
467 469 
468 470 
469-def transformer_block_backward(block_output_grad, layer_graphs: List[LayerGraph]):471+def transformer_block_backward(
472+ block_output_grad,
473+ layer_graphs: List[LayerGraph],
474+ *,
475+ layer_backward=None,
476+):
477+ layer_backward = transformer_layer_backward if layer_backward is None else layer_backward
470 # should call backward first for final_layernorm and postprocess grad478 # should call backward first for final_layernorm and postprocess grad
471 layer_output_grad = block_output_grad479 layer_output_grad = block_output_grad
472 while len(layer_graphs) > 0:480 while len(layer_graphs) > 0:
473 layer_graph = layer_graphs.pop(-1)481 layer_graph = layer_graphs.pop(-1)
474- layer_output_grad = transformer_layer_backward(layer_output_grad, layer_graph)482+ layer_output_grad = layer_backward(layer_output_grad, layer_graph)
475 483 
476 return layer_output_grad484 return layer_output_grad
@@ -156,10 +156,7 @@ def transformer_layer_backward(
156 layer_graph.mlp_mhc_post_graph[1],156 layer_graph.mlp_mhc_post_graph[1],
157 )157 )
158 else:158 else:
159- restored_layer_graph.unperm2_graph = (159+ restored_layer_graph.set_output_boundary(layer_graph.get_output_boundary())
160- restored_layer_graph.unperm2_graph[0],
161- layer_graph.unperm2_graph[1],
162- )
163 layer_graph = restored_layer_graph160 layer_graph = restored_layer_graph
164 if isinstance(layer_graph, NoopLayerGraph):161 if isinstance(layer_graph, NoopLayerGraph):
165 return transformer_layer_backward_noop(layer_output_grad, layer_graph)162 return transformer_layer_backward_noop(layer_output_grad, layer_graph)
@@ -47,6 +47,31 @@ LOSS_BACKWARD_SCALE = torch.tensor(1.0)
47Shape = Union[List[int], torch.Size]47Shape = Union[List[int], torch.Size]
48 48 
49 49 
50+def get_interleaved_coordinates(iteration, pipeline_size, chunks, *, forward=True):
51+ """The existing regular-layout outer's chunk and logical microbatch IDs."""
52+ chunk = (iteration % (pipeline_size * chunks)) // pipeline_size
53+ if not forward:
54+ chunk = chunks - chunk - 1
55+ microbatch = (iteration // (pipeline_size * chunks)) * pipeline_size + iteration % pipeline_size
56+ return chunk, microbatch
57+ 
58+ 
59+def get_interleaved_warmup_base(pp_rank, num_microbatches, pipeline_size, chunks):
60+ """Regular FB training warmup before the caller's extra overlap F."""
61+ total = num_microbatches * chunks
62+ if num_microbatches == pipeline_size:
63+ return total
64+ return min(total, (pipeline_size - pp_rank - 1) * 2 + (chunks - 1) * pipeline_size)
65+ 
66+ 
67+def get_layout_warmup(pp_rank, num_microbatches, pipeline_size, chunks, group_size, *, forward_only=False):
68+ """The custom-layout FB warmup, including its extra overlap forward."""
69+ total = num_microbatches * chunks
70+ if forward_only or num_microbatches == pipeline_size:
71+ return total
72+ return min(total, (pipeline_size - pp_rank - 1) * 2 + (chunks - 1) * group_size + 1)
73+ 
74+ 
50def has_pipeline_model_parallel_layout(config):75def has_pipeline_model_parallel_layout(config):
51 """Return whether custom pipeline layout is active for this model config."""76 """Return whether custom pipeline layout is active for this model config."""
52 if getattr(config, 'pipeline_model_parallel_layout', None) is not None:77 if getattr(config, 'pipeline_model_parallel_layout', None) is not None:
@@ -430,20 +455,15 @@ def forward_backward_pipelining_with_interleaving(
430 all_warmup_microbatches = False455 all_warmup_microbatches = False
431 456 
432 if use_pipeline_model_parallel_layout:457 if use_pipeline_model_parallel_layout:
433- if forward_only:458+ num_warmup_microbatches = get_layout_warmup(
434- num_warmup_microbatches = total_num_microbatches459+ pipeline_parallel_rank,
435- else:460+ num_microbatches,
436- if num_microbatches == pipeline_parallel_size:461+ pipeline_parallel_size,
437- num_warmup_microbatches = total_num_microbatches462+ num_model_chunks,
438- else:463+ microbatch_group_size_per_vp_stage,
439- num_warmup_microbatches = (pipeline_parallel_size - pipeline_parallel_rank - 1) * 2464+ forward_only=forward_only,
440- num_warmup_microbatches += (num_model_chunks - 1) * microbatch_group_size_per_vp_stage465+ )
441- # Add one more warmup microbatch for fb overlap, same as Megatron dev466+ all_warmup_microbatches = num_warmup_microbatches == total_num_microbatches
442- # overlap_moe_expert_parallel_comm schedule.
443- num_warmup_microbatches += 1
444- if num_warmup_microbatches >= total_num_microbatches:
445- num_warmup_microbatches = total_num_microbatches
446- all_warmup_microbatches = True
447 else:467 else:
448 if forward_only:468 if forward_only:
449 num_warmup_microbatches = total_num_microbatches469 num_warmup_microbatches = total_num_microbatches
@@ -458,9 +478,9 @@ def forward_backward_pipelining_with_interleaving(
458 num_warmup_microbatches = total_num_microbatches478 num_warmup_microbatches = total_num_microbatches
459 all_warmup_microbatches = True479 all_warmup_microbatches = True
460 else:480 else:
461- num_warmup_microbatches = (pipeline_parallel_size - pipeline_parallel_rank - 1) * 2481+ num_warmup_microbatches = get_interleaved_warmup_base(
462- num_warmup_microbatches += (num_model_chunks - 1) * pipeline_parallel_size482+ pipeline_parallel_rank, num_microbatches, pipeline_parallel_size, num_model_chunks
463- num_warmup_microbatches = min(num_warmup_microbatches, total_num_microbatches)483+ )
464 # add one more warmup microbatches for 1f1b overlaping484 # add one more warmup microbatches for 1f1b overlaping
465 num_warmup_microbatches += 1485 num_warmup_microbatches += 1
466 num_microbatches_remaining = total_num_microbatches - num_warmup_microbatches486 num_microbatches_remaining = total_num_microbatches - num_warmup_microbatches
@@ -495,22 +515,14 @@ def forward_backward_pipelining_with_interleaving(
495 if not forward:515 if not forward:
496 model_chunk_id = num_model_chunks - model_chunk_id - 1516 model_chunk_id = num_model_chunks - model_chunk_id - 1
497 return model_chunk_id517 return model_chunk_id
498- microbatch_id_in_group = microbatch_id % (pipeline_parallel_size * num_model_chunks)518+ return get_interleaved_coordinates(microbatch_id, pipeline_parallel_size, num_model_chunks, forward=forward)[0]
499- model_chunk_id = microbatch_id_in_group // pipeline_parallel_size
500- if not forward:
501- model_chunk_id = num_model_chunks - model_chunk_id - 1
502- return model_chunk_id
503 519 
504 def get_microbatch_id_in_model_chunk(iteration_id, forward):520 def get_microbatch_id_in_model_chunk(iteration_id, forward):
505 """Helper method to get the microbatch_id within model chunk given the iteration number."""521 """Helper method to get the microbatch_id within model chunk given the iteration number."""
506 assert forward522 assert forward
507 if use_pipeline_model_parallel_layout:523 if use_pipeline_model_parallel_layout:
508 return microbatch_id_table[iteration_id]524 return microbatch_id_table[iteration_id]
509- iteration_group_id = iteration_id // (pipeline_parallel_size * num_model_chunks)525+ return get_interleaved_coordinates(iteration_id, pipeline_parallel_size, num_model_chunks, forward=forward)[1]
510- microbatch_id_in_model_chunk = (iteration_group_id * pipeline_parallel_size) + (
511- iteration_id % pipeline_parallel_size
512- )
513- return microbatch_id_in_model_chunk
514 526 
515 def num_released_microbatches(microbatch_id, model_chunk_id):527 def num_released_microbatches(microbatch_id, model_chunk_id):
516 if not use_pipeline_model_parallel_layout:528 if not use_pipeline_model_parallel_layout:
@@ -640,7 +652,7 @@ def forward_backward_pipelining_with_interleaving(
640 if getattr(config, 'enable_mhc', False):652 if getattr(config, 'enable_mhc', False):
641 logits_inputs.append(model_graph[-1].mlp_mhc_post_graph[1])653 logits_inputs.append(model_graph[-1].mlp_mhc_post_graph[1])
642 else:654 else:
643- logits_inputs.append(model_graph[-1].unperm2_graph[1])655+ logits_inputs.append(model_graph[-1].get_output_boundary())
644 model_graphs[model_chunk_id].append(model_graph)656 model_graphs[model_chunk_id].append(model_graph)
645 else:657 else:
646 output_tensor_ = output_tensor658 output_tensor_ = output_tensor
@@ -0,0 +1,20 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""MoonEP forward/backward overlap integration."""
16+ 
17+from .transformer_block import moonep_transformer_block_fb_overlap_init_wrapper
18+from .adaptor import get_forward_backward_func_moonep_wrapper
19+ 
20+__all__ = ['get_forward_backward_func_moonep_wrapper', 'moonep_transformer_block_fb_overlap_init_wrapper']
@@ -0,0 +1,266 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""Connect MoonEP steps to the original FB schedule selector."""
16+ 
17+from dataclasses import dataclass
18+from functools import partial, wraps
19+ 
20+import torch
21+ 
22+from megatron.core import parallel_state
23+from megatron.core.utils import get_attr_wrapped_model, get_model_config
24+ 
25+from ..fb_overlap.adaptor import get_forward_backward_func_vpp_overlap_wrapper
26+from . import session as fb_session
27+ 
28+ 
29+def wrap_moonep_forward_step(fn):
30+ """Adapt model kwargs for MoonEP without partial microbatch recompute."""
31+ 
32+ @wraps(fn)
33+ def wrapper(data_iterator, model, checkpoint_activations_microbatch=None, extra_block_kwargs=None):
34+ if checkpoint_activations_microbatch is not None:
35+ raise ValueError('MoonEP FB does not support partial activation checkpoints')
36+ if extra_block_kwargs is not None and extra_block_kwargs.get('checkpoint_activations_microbatch') is not None:
37+ raise ValueError('MoonEP FB does not support partial activation checkpoints')
38+ had_instance_forward = 'forward' in vars(model)
39+ orig_model_forward_func = model.forward
40+ try:
41+ model.forward = partial(orig_model_forward_func, extra_block_kwargs=extra_block_kwargs)
42+ return fn(data_iterator, model)
43+ finally:
44+ if had_instance_forward:
45+ model.forward = orig_model_forward_func
46+ else:
47+ vars(model).pop('forward', None)
48+ 
49+ return wrapper
50+ 
51+ 
52+_training_state = None
53+ 
54+ 
55+@dataclass
56+class _TrainingState:
57+ models: tuple
58+ config: object = None
59+ sequence_shard_factor: int = 1
60+ grad_finalizer_validated: bool = False
61+ 
62+ 
63+def _validate_optimizer(optimizer):
64+ """Require Megatron's synchronous parameter gathering; never invoke it here."""
65+ if not callable(getattr(optimizer, 'step', None)):
66+ raise TypeError('MoonEP training requires the original optimizer.step')
67+ config = getattr(optimizer, 'config', None)
68+ children = getattr(optimizer, 'chained_optimizers', (optimizer,))
69+ gather_configs = (config, *(getattr(child, 'ddp_config', None) for child in children))
70+ if any(
71+ getattr(cfg, name, False)
72+ for cfg in gather_configs
73+ for name in ('overlap_param_gather', 'overlap_param_gather_with_optimizer_step')
74+ ):
75+ raise TypeError('MoonEP FB requires synchronous optimizer parameter gathering')
76+ if getattr(config, 'use_distributed_optimizer', False):
77+ if any(getattr(child, '_defer_param_sync', False) for child in children):
78+ raise TypeError('ordinary MoonEP training requires optimizer parameter gathering without deferral')
79+ 
80+ 
81+def setup_wrapper(fn):
82+ # MA may pass the same callable back through another training-module alias.
83+ if getattr(fn, '_moonep_fb_setup_wrapped', False):
84+ return fn
85+ 
86+ @wraps(fn)
87+ def wrapper(*args, **kwargs):
88+ global _training_state
89+ result = fn(*args, **kwargs)
90+ 
91+ models = result[0] if isinstance(result, tuple) else getattr(result, 'model', None)
92+ optimizer = result[1] if isinstance(result, tuple) else getattr(result, 'optimizer', None)
93+ if models is None or optimizer is None:
94+ raise TypeError('MoonEP FB setup requires models and an optimizer from setup_model_and_optimizer')
95+ if _training_state is not None:
96+ raise RuntimeError('MoonEP FB training is already installed')
97+ models = tuple(models) if isinstance(models, (tuple, list)) else (models,)
98+ state = _TrainingState(models)
99+ try:
100+ _setup_training_resources(state, optimizer)
101+ except BaseException as exc:
102+ if fb_session._SESSION is not None:
103+ fb_session.poison_session(exc)
104+ raise
105+ 
106+ _training_state = state
107+ return result
108+ 
109+ wrapper._moonep_fb_setup_wrapped = True
110+ return wrapper
111+ 
112+ 
113+def _close_training():
114+ global _training_state
115+ fb_session.close_session()
116+ _training_state = None
117+ 
118+ 
119+def pretrain_wrapper(fn):
120+ if getattr(fn, '_moonep_fb_pretrain_wrapped', False):
121+ return fn
122+ 
123+ @wraps(fn)
124+ def wrapper(*args, **kwargs):
125+ result = fn(*args, **kwargs)
126+ if _training_state is not None:
127+ _close_training()
128+ return result
129+ 
130+ wrapper._moonep_fb_pretrain_wrapped = True
131+ return wrapper
132+ 
133+ 
134+def save_checkpoint_wrapper(fn):
135+ @wraps(fn)
136+ def wrapper(*args, **kwargs):
137+ fb_session.checkpoint_drain()
138+ return fn(*args, **kwargs)
139+ 
140+ return wrapper
141+ 
142+ 
143+def destroy_model_parallel_wrapper(fn):
144+ @wraps(fn)
145+ def wrapper(*args, **kwargs):
146+ _close_training()
147+ return fn(*args, **kwargs)
148+ 
149+ return wrapper
150+ 
151+ 
152+def _setup_training_resources(state, optimizer):
153+ """Unwrap Megatron models and delegate initialization to the session owner."""
154+ blocks = tuple(get_attr_wrapped_model(model, 'decoder') for model in state.models)
155+ block_config = blocks[0].config
156+ state.config = get_model_config(state.models[0])
157+ error = None
158+ try:
159+ _validate_optimizer(optimizer)
160+ if block_config.tensor_model_parallel_size != parallel_state.get_tensor_model_parallel_world_size():
161+ raise ValueError('MoonEP model TP size differs from initialized parallel state')
162+ state.sequence_shard_factor = block_config.tensor_model_parallel_size if block_config.sequence_parallel else 1
163+ except Exception as exc:
164+ error = exc
165+ fb_session.setup_training_resources(blocks if len(blocks) > 1 else blocks[0], _entry_error=error)
166+ 
167+ 
168+def _prepare_step_plan(arguments):
169+ """Extract schedule shapes and check the Megatron calling convention."""
170+ state = _training_state
171+ forward_only = arguments.get('forward_only', False)
172+ error, tokens = None, None
173+ try:
174+ if forward_only != (not torch.is_grad_enabled()):
175+ raise ValueError('MoonEP evaluation requires forward_only and no_grad together')
176+ # Megatron installs this callback after model setup; validate at the first training step.
177+ if not forward_only and not state.grad_finalizer_validated:
178+ if not callable(state.config.finalize_model_grads_func): # pylint: disable=no-member
179+ raise ValueError('ordinary training must install finalize_model_grads_func before the first schedule')
180+ state.grad_finalizer_validated = True
181+ seq, batch, microbatches = arguments['seq_length'], arguments['micro_batch_size'], arguments['num_microbatches']
182+ if any(type(value) is not int or value <= 0 for value in (seq, batch, microbatches)): # pylint: disable=unidiomatic-typecheck
183+ raise ValueError('MoonEP requires positive shapes and microbatch count')
184+ if arguments.get('decoder_seq_length') not in (None, seq):
185+ raise ValueError('MoonEP requires matching decoder length')
186+ if arguments.get('adjust_tensor_shapes_fn') is not None:
187+ raise ValueError('MoonEP outer loop excludes dynamic tensor shapes')
188+ if seq % state.sequence_shard_factor:
189+ raise ValueError('MoonEP requires divisible sequence length')
190+ tokens = seq * batch // state.sequence_shard_factor
191+ except Exception as exc:
192+ error = exc
193+ return fb_session.prepare_step_plan(
194+ num_microbatches=arguments.get('num_microbatches'),
195+ tokens=tokens,
196+ forward_only=forward_only,
197+ consumer_stream=torch.npu.current_stream(),
198+ seq_length=arguments.get('seq_length'),
199+ micro_batch_size=arguments.get('micro_batch_size'),
200+ eval_group_size=state.config.microbatch_group_size_per_vp_stage if forward_only else None, # pylint: disable=no-member
201+ _entry_error=error,
202+ )
203+ 
204+ 
205+def get_forward_backward_func_moonep_wrapper(fn):
206+ """Keep FB selection; prepare, execute and finish each MoonEP step."""
207+ get_fb_schedule = get_forward_backward_func_vpp_overlap_wrapper(fn)
208+ 
209+ @wraps(fn)
210+ def get_schedule(*args, **kwargs):
211+ schedule = get_fb_schedule(*args, **kwargs)
212+ 
213+ def forward_backward_moonep(**arguments):
214+ # 1. Prepare the plan and begin the session's execution scope.
215+ session = _prepare_moonep_step(arguments)
216+ try:
217+ # 2. Execute the original schedule with the installed Block/Layer patches.
218+ result = schedule(**arguments)
219+ 
220+ # 3. Check completion and finish the session's execution scope.
221+ if session is not None:
222+ fb_session.complete_moonep_step()
223+ return result
224+ except BaseException as exc:
225+ if session is not None:
226+ fb_session.poison_session(exc)
227+ raise
228+ 
229+ return forward_backward_moonep
230+ 
231+ return get_schedule
232+ 
233+ 
234+def _prepare_moonep_step(arguments):
235+ """Validate model identity, prepare/reuse work, adapt inputs and begin execution."""
236+ state = _training_state
237+ if state is None:
238+ raise RuntimeError('MoonEP training setup must finish before selecting schedule work')
239+ models = arguments['model']
240+ models = tuple(models) if isinstance(models, (list, tuple)) else (models,)
241+ if len(models) != len(state.models) or any(model is not saved for model, saved in zip(models, state.models)):
242+ raise ValueError('MoonEP schedule models differ from setup models')
243+ forward_only = arguments.get('forward_only', False)
244+ session = _prepare_step_plan(arguments)
245+ 
246+ # The FB training engine indexes one iterator per model chunk.
247+ if (
248+ not forward_only
249+ and parallel_state.get_pipeline_model_parallel_world_size() > 1
250+ and len(_training_state.models) == 1
251+ and not isinstance(arguments.get('data_iterator'), list)
252+ ):
253+ arguments['data_iterator'] = [arguments.get('data_iterator')]
254+ 
255+ if session is not None:
256+ fb_session.begin_moonep_step(forward_only=forward_only)
257+ return session
258+ 
259+ 
260+def build_moonep_fb_token_dispatcher():
261+ """Use the PR dispatcher/manager unchanged and mark its FB backend."""
262+ from ...moonep.moonep import build_moonep_flex_token_dispatcher
263+ 
264+ dispatcher = build_moonep_flex_token_dispatcher()
265+ dispatcher.fb_overlap_backend = 'moonep'
266+ return dispatcher
@@ -0,0 +1,214 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""Deterministic pre-init bank sizing from exact lease/final-use intervals.
16+ 
17+The FB schedule supplies intervals through each bank's final use. Setup owns
18+fixed physical pools; each schedule's interval demand must fit those pools.
19+"""
20+ 
21+from dataclasses import dataclass, field
22+import hashlib
23+import heapq
24+import json
25+ 
26+from .plan_types import BankKey
27+ 
28+ 
29+_DTYPE_BYTES = {"bf16": 2, "fp32": 4, "int32": 4}
30+ 
31+ 
32+@dataclass(frozen=True, slots=True)
33+class LeaseInterval:
34+ role: str
35+ generation: object
36+ start_ordinal: int
37+ end_ordinal: int
38+ shape: tuple[int, ...]
39+ dtype: str
40+ 
41+ 
42+@dataclass(frozen=True, slots=True)
43+class PoolSpec:
44+ count: int
45+ shape: tuple[int, ...]
46+ dtype: str
47+ 
48+ 
49+@dataclass(frozen=True, slots=True)
50+class CapacityPlan:
51+ pools: dict[str, PoolSpec]
52+ assignments: tuple[BankKey, ...]
53+ aliases: dict[str, str] = field(default_factory=dict)
54+ 
55+ @property
56+ def physical_pools(self):
57+ return {role: spec for role, spec in self.pools.items() if role not in self.aliases}
58+ 
59+ def physical_key(self, key):
60+ return BankKey(self.aliases.get(key.role, key.role), key.index)
61+ 
62+ def manifest(self, *, granularity, topology=None):
63+ if type(granularity) is not int or granularity <= 0: # pylint: disable=unidiomatic-typecheck
64+ raise ValueError("VMM granularity must be a positive integer")
65+ return {
66+ "schema": 2 if self.aliases else 1,
67+ "lane_count": 1,
68+ "granularity": granularity,
69+ **({"topology": dict(topology)} if topology is not None else {}),
70+ "banks": {
71+ role: {"count": spec.count, "shape": list(spec.shape), "dtype": spec.dtype}
72+ for role, spec in sorted(self.physical_pools.items())
73+ },
74+ **({"aliases": dict(self.aliases)} if self.aliases else {}),
75+ }
76+ 
77+ def physical_bytes(self, granularity):
78+ if type(granularity) is not int or granularity <= 0: # pylint: disable=unidiomatic-typecheck
79+ raise ValueError("VMM granularity must be a positive integer")
80+ total = 0
81+ for spec in self.physical_pools.values():
82+ logical = _DTYPE_BYTES[spec.dtype]
83+ for dimension in spec.shape:
84+ logical *= dimension
85+ total += spec.count * ((logical + granularity - 1) // granularity * granularity)
86+ return total
87+ 
88+ 
89+def derive_capacity(intervals, *, aliases=None):
90+ """Color half-open intervals, including explicitly shared physical pools.
91+ 
92+ Intervals ending at T release their bank before intervals beginning at T.
93+ Equal-start intervals retain caller work order, which is the Q0 schedule's
94+ semantic order. Shapes of one role may vary only within one rank; the
95+ physical bank uses the dimension-wise maximum shape.
96+ """
97+ intervals = tuple(intervals)
98+ aliases = dict(aliases or {})
99+ roles = {lease.role for lease in intervals if isinstance(lease, LeaseInterval)}
100+ if any(
101+ source not in roles or target not in roles or source == target or target in aliases
102+ for source, target in aliases.items()
103+ ):
104+ raise ValueError('bank aliases must name present roles and direct physical pools')
105+ grouped = {}
106+ for position, lease in enumerate(intervals):
107+ if not isinstance(lease, LeaseInterval):
108+ raise TypeError("expected LeaseInterval")
109+ if not isinstance(lease.role, str) or not lease.role:
110+ raise ValueError("lease role must be nonempty")
111+ if lease.generation is None or type(lease.start_ordinal) is not int or type(lease.end_ordinal) is not int: # pylint: disable=unidiomatic-typecheck
112+ raise ValueError("lease needs exact generation and integer boundaries")
113+ if lease.start_ordinal < 0 or lease.end_ordinal <= lease.start_ordinal:
114+ raise ValueError("final use must follow acquisition")
115+ if (
116+ not isinstance(lease.shape, tuple)
117+ or not lease.shape
118+ or any(type(dimension) is not int or dimension <= 0 for dimension in lease.shape) # pylint: disable=unidiomatic-typecheck
119+ ):
120+ raise ValueError("lease shape must contain positive integer dimensions")
121+ if lease.dtype not in _DTYPE_BYTES:
122+ raise ValueError("unsupported bank dtype")
123+ grouped.setdefault(aliases.get(lease.role, lease.role), []).append((position, lease))
124+ assignments = [None] * len(intervals)
125+ pools = {}
126+ for role, entries in grouped.items():
127+ dtype = entries[0][1].dtype
128+ rank = len(entries[0][1].shape)
129+ if any(lease.dtype != dtype or len(lease.shape) != rank for _, lease in entries):
130+ raise ValueError("one bank role needs one dtype and shape rank")
131+ shape = tuple(max(lease.shape[axis] for _, lease in entries) for axis in range(rank))
132+ active, free = [], []
133+ count = 0
134+ for position, lease in sorted(entries, key=lambda pair: (pair[1].start_ordinal, pair[0])):
135+ while active and active[0][0] <= lease.start_ordinal:
136+ _, available = heapq.heappop(active)
137+ heapq.heappush(free, available)
138+ if free:
139+ index = heapq.heappop(free)
140+ else:
141+ index = count
142+ count += 1
143+ assignments[position] = BankKey(lease.role, index)
144+ heapq.heappush(active, (lease.end_ordinal, index))
145+ pools[role] = PoolSpec(count, shape, dtype)
146+ for source, target in aliases.items():
147+ pools[source] = pools[target]
148+ return CapacityPlan(pools, tuple(assignments), aliases)
149+ 
150+ 
151+def manifest_digest(manifest):
152+ """Address-free digest; callers compare it before one-shot SHMEM init."""
153+ payload = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8")
154+ return hashlib.sha256(payload).hexdigest()
155+ 
156+ 
157+def local_token_capacity(tokens, *, tp_size=1, sequence_parallel=False):
158+ """Normalize the existing local token count for the sequence-parallel shard."""
159+ if type(tp_size) is not int or tp_size <= 0: # pylint: disable=unidiomatic-typecheck
160+ raise ValueError('MoonEP requires positive TP size')
161+ factor = tp_size if sequence_parallel else 1
162+ if type(tokens) is not int or tokens <= 0 or tokens % factor: # pylint: disable=unidiomatic-typecheck
163+ raise ValueError('MoonEP requires positive tokens divisible by the SP factor')
164+ return tokens // factor
165+ 
166+ 
167+def static_resource_capacity(layout, tokens, *, activation_zero_copy):
168+ """Allocate the supported FB upper bound without inventing microbatch work."""
169+ if type(tokens) is not int or tokens <= 0: # pylint: disable=unidiomatic-typecheck
170+ raise ValueError('positive token capacity required')
171+ if not layout['has_moe']:
172+ return CapacityPlan({}, ())
173+ local_experts = layout['local_experts']
174+ fc1, fc2 = layout['projection_shapes']
175+ pools = {
176+ role: PoolSpec(count, (local_experts, *shape), dtype)
177+ for role, count, shape, dtype in (
178+ ('fc1_weight', 2, fc1, 'bf16'),
179+ ('fc2_weight', 2, fc2, 'bf16'),
180+ ('fc1_grad', 1, fc1, 'fp32'),
181+ ('fc2_grad', 1, fc2, 'fp32'),
182+ )
183+ }
184+ aliases = {}
185+ if activation_zero_copy:
186+ shape = (tokens * layout['topk'], layout['hidden'])
187+ pools.update({role: PoolSpec(1, shape, 'bf16') for role in ('Z1', 'R1', 'Z4', 'Z3', 'Z2')})
188+ aliases['Z2'] = 'Z3'
189+ return CapacityPlan(pools, (), aliases)
190+ 
191+ 
192+def admit_plan_capacity(needed, available, *, activation_zero_copy):
193+ """Check demand against fixed backing and keep the resource's alias identity."""
194+ pools = dict(needed.pools)
195+ aliases = dict(available.aliases) if activation_zero_copy else {}
196+ for source, target in aliases.items():
197+ if source in pools and target not in pools:
198+ pools[target] = pools[source]
199+ for role, spec in pools.items():
200+ if role in ('Z1', 'Z2', 'Z3', 'Z4', 'R1') and not activation_zero_copy:
201+ continue
202+ physical = aliases.get(role, role)
203+ limit = available.physical_pools.get(physical)
204+ if (
205+ limit is None
206+ or spec.dtype != limit.dtype
207+ or spec.count > limit.count
208+ or len(spec.shape) != len(limit.shape)
209+ or any(value > maximum for value, maximum in zip(spec.shape, limit.shape))
210+ ):
211+ raise ValueError(f'MoonEP plan exceeds initialized capacity: {role}')
212+ return CapacityPlan(
213+ pools, needed.assignments, {source: target for source, target in aliases.items() if source in pools}
214+ )
@@ -0,0 +1,37 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""FB configuration extends the shared MoonEP argument contract."""
16+ 
17+from ...moonep import moonep_contract as common
18+ 
19+ 
20+def validate_recompute_config(config):
21+ """Reuse fixed original FB recompute without partial microbatch policies."""
22+ if getattr(config, 'num_microbatches_with_partial_activation_checkpoints', None) is not None:
23+ raise ValueError('MoonEP FB does not support partial activation checkpoints')
24+ granularity = getattr(config, 'recompute_granularity', None)
25+ if granularity is None:
26+ return
27+ method = getattr(config, 'recompute_method', None)
28+ layers = getattr(config, 'recompute_num_layers', None)
29+ if granularity != 'full' or method not in ('uniform', 'block') or type(layers) is not int or layers <= 0: # pylint: disable=unidiomatic-typecheck
30+ raise ValueError('MoonEP FB requires fixed full/uniform or full/block recompute')
31+ if method == 'uniform' and layers != 1:
32+ raise ValueError('MoonEP FB uniform recompute requires recompute_num_layers=1')
33+ 
34+ 
35+def validate_moonep_args(args):
36+ validate_recompute_config(args)
37+ common.validate_moonep_args(args, for_fb_overlap=True)
@@ -0,0 +1,15 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""MoonEP routed/shared expert computation and common graph helpers."""
@@ -0,0 +1,181 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""Thread-bound GMM ownership for FB, independent of synchronous transport."""
16+ 
17+from collections import deque
18+from contextlib import contextmanager
19+from threading import get_ident
20+ 
21+from ..release import observe_max
22+ 
23+ 
24+def prepare_backend():
25+ from mindspeed.ops.moonep_gmm import _standard_binding
26+ 
27+ backend = _standard_binding()
28+ for name in ('stream_handle', 'take_workspace_tensors', 'abort_submissions', 'begin_fb_backing', 'take_fb_backing'):
29+ if not callable(getattr(backend, 'moonep_standard_' + name, None)):
30+ raise RuntimeError('MoonEP FB requires the standard GMM workspace interface')
31+ return backend
32+ 
33+ 
34+def _same(left, right):
35+ return len(left) == len(right) and all(a is b for a, b in zip(left, right))
36+ 
37+ 
38+def bind_experts(session, experts):
39+ owner = experts._experts_ref()
40+ if owner is None:
41+ raise RuntimeError('MoonEP FB canonical expert module disappeared')
42+ groups = tuple((tuple(experts.weight_refs(proj)), tuple(experts.grad_targets(proj))) for proj in ('fc1', 'fc2'))
43+ session['compute_bindings'][id(experts)] = (experts, owner, experts.linears, groups)
44+ validate_bindings(session, experts)
45+ 
46+ 
47+def validate_bindings(session, experts):
48+ binding = session['compute_bindings'].get(id(experts))
49+ if binding is None or binding[0] is not experts:
50+ raise RuntimeError('MoonEP FB expert compute binding was not prepared')
51+ _, owner, linears, groups = binding
52+ if (
53+ experts._experts_ref() is not owner
54+ or owner.linear_fc1 is not linears[0]
55+ or owner.linear_fc2 is not linears[1]
56+ or not _same(experts.linears, linears)
57+ ):
58+ raise RuntimeError('MoonEP FB canonical expert module changed')
59+ for projection, linear, (weights, targets) in zip(('fc1', 'fc2'), linears, groups):
60+ if (
61+ not _same(experts.weight_refs(projection), weights)
62+ or not _same(experts.grad_targets(projection), targets)
63+ or any(
64+ linear._parameters.get('weight' + str(i)) is not p
65+ or not p.requires_grad
66+ or getattr(p, 'main_grad', None) is not g
67+ for i, (p, g) in enumerate(zip(weights, targets))
68+ )
69+ ):
70+ raise RuntimeError('MoonEP FB Parameter/main_grad binding identity changed')
71+ 
72+ 
73+def _stream(session):
74+ import torch
75+ 
76+ current, expected = torch.npu.current_stream(), session['q1']
77+ if (current.device, current.npu_stream) != (expected.device, expected.npu_stream):
78+ raise RuntimeError('MoonEP FB compute requires the fixed Q1 device and stream')
79+ return expected
80+ 
81+ 
82+def drain_submissions(session):
83+ stream = _stream(session)
84+ if int(session['compute_backend'].moonep_standard_stream_handle(True)) != stream.npu_stream:
85+ raise RuntimeError('MoonEP FB native compute stream differs from Q1')
86+ 
87+ 
88+def _fail(session, error, state, previous=None):
89+ from ..runtime import fail_stop
90+ 
91+ secondary = None
92+ backend = session.get('compute_backend')
93+ if backend is not None:
94+ try:
95+ backend.moonep_standard_abort_submissions()
96+ except BaseException as exc:
97+ secondary = exc
98+ # Retain Python/external owners too, including partial preparation and
99+ # failed end/abort. Never replace the original failure or reopen admission.
100+ fail_stop(error, session, state, previous, backend, secondary)
101+ 
102+ 
103+def check_idle(session):
104+ try:
105+ if session.get('compute_segment') is not None:
106+ raise RuntimeError('MoonEP FB compute segment is still active')
107+ backend = session.get('compute_backend')
108+ if backend is None:
109+ raise RuntimeError('MoonEP FB compute backend was not prepared')
110+ pending = session.get('deferred_compute')
111+ while pending:
112+ _reap_compute(pending, wait_oldest=True)
113+ backend.moonep_standard_stream_handle(False)
114+ except BaseException as error:
115+ _fail(session, error, session.get('compute_segment'))
116+ raise
117+ 
118+ 
119+def _reap_compute(pending, *, wait_oldest=False):
120+ while pending:
121+ event, _ = pending[0]
122+ if not event.query():
123+ if not wait_oldest:
124+ break
125+ event.synchronize()
126+ wait_oldest = False
127+ pending.popleft()
128+ 
129+ 
130+def require_segment(targets=None):
131+ from ..session import get_session
132+ 
133+ session = get_session(require_active=True)
134+ state = session.get('compute_segment')
135+ if state is None or state['thread'] != get_ident():
136+ raise RuntimeError('MoonEP FB compute requires this host thread to own its segment')
137+ _stream(session)
138+ experts = state['experts']
139+ validate_bindings(session, experts)
140+ if targets is not None and not any(_same(targets, experts.grad_targets(proj)) for proj in ('fc1', 'fc2')):
141+ raise RuntimeError('MoonEP FB wgrad task has foreign canonical targets')
142+ return state
143+ 
144+ 
145+@contextmanager
146+def segment(experts, *owners):
147+ from ..session import get_session
148+ 
149+ session = get_session(require_active=True)
150+ previous = session.get('compute_segment')
151+ state = dict(thread=get_ident(), experts=experts, owners=owners)
152+ try:
153+ if previous is not None:
154+ raise RuntimeError('MoonEP FB nested or unfinished compute segment')
155+ validate_bindings(session, experts)
156+ stream = _stream(session)
157+ backend = session['compute_backend']
158+ pending = session.setdefault('deferred_compute', deque())
159+ _reap_compute(pending, wait_oldest=len(pending) >= 2)
160+ # Publish roots before begin/flush, either of which can fail partially.
161+ session['compute_segment'] = state
162+ drain_submissions(session)
163+ state['workspaces'] = backend.moonep_standard_take_workspace_tensors()
164+ if state['workspaces']:
165+ raise RuntimeError('MoonEP FB found unretired GMM workspaces at segment entry')
166+ backend.moonep_standard_begin_fb_backing()
167+ yield
168+ require_segment()
169+ if session['compute_segment'] is not state:
170+ raise RuntimeError('MoonEP FB compute owner was replaced')
171+ drain_submissions(session)
172+ # Allocator-owned backing is tracked on Q1. Keep only foreign
173+ # backing until device completion, independent of the Python graph.
174+ state['backing'] = backend.moonep_standard_take_fb_backing()
175+ pending.append((stream.record_event(), state['backing']))
176+ observe_max(session, 'pending_compute_segments', len(pending))
177+ backend.moonep_standard_stream_handle(False)
178+ session['compute_segment'] = None
179+ except BaseException as error:
180+ _fail(session, error, state, previous)
181+ raise
@@ -0,0 +1,216 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""Expert Autograd tape and call-local delayed wgrad, without communication state."""
16+ 
17+from contextlib import contextmanager
18+from functools import lru_cache
19+from dataclasses import dataclass, field
20+ 
21+from ....moonep.virtual_expert_load_balancer import VirtualExpertPlan as BaseVirtualExpertPlan
22+from ..plan_types import GenerationKey
23+from . import compute
24+ 
25+ 
26+@dataclass(slots=True)
27+class FBVirtualExpertPlan(BaseVirtualExpertPlan):
28+ """Only FB identity and the call-local Autograd collector extend the PR plan."""
29+ 
30+ execution_key: GenerationKey | None = None
31+ exact_graph_ref: object = None
32+ # FB replays Dispatch from the original input; synchronous MoonEP now owns
33+ # a saved Z1 instead. Keep replay state local to this FB plan extension.
34+ replay_input_refs: tuple = ()
35+ replay_input_signatures: tuple = ()
36+ _expert_backward_call: tuple | None = field(default=None, init=False, repr=False, compare=False)
37+ 
38+ 
39+def forward_fc1(session, hidden, sources, slot, counts):
40+ from mindspeed.ops.moonep_gmm import npu_gmm_v5_out
41+ 
42+ shape = (hidden.shape[0], sources[0].shape[0])
43+ if session.get("step_plan", {}).get("backward_keys"):
44+ # F0 and F1 may both remain live when B0 starts.
45+ out = hidden.new_empty(shape)
46+ else:
47+ if session["fc1_out"] is None or tuple(session["fc1_out"].shape) != shape:
48+ session["fc1_out"] = hidden.new_empty(shape)
49+ out = session["fc1_out"]
50+ # Keep the original Parameters on the tape; native math receives only aliases.
51+ refs = tuple(weight.detach().t() for weight in (*sources, *tuple(slot)))
52+ npu_gmm_v5_out(hidden.detach(), refs, out.detach(), counts)
53+ return out
54+ 
55+ 
56+def expert_activation(fc1_out, experts):
57+ """SiTU is owned by the model module; ordinary TE SiLU is a scalar SwiGLU gate."""
58+ if getattr(experts, 'activation_kind', 'swiglu') == 'situ':
59+ return experts.activation(fc1_out)
60+ if getattr(experts, 'activation_kind', 'swiglu') != 'swiglu':
61+ raise ValueError('unsupported MoonEP expert activation protocol')
62+ import torch.nn.functional as F
63+ 
64+ gate, linear = fc1_out.chunk(2, dim=-1)
65+ return F.silu(gate) * linear
66+ 
67+ 
68+def forward_activate(fc1_out, probs, experts):
69+ activated = expert_activation(fc1_out, experts)
70+ weighted = (activated * probs.unsqueeze(-1)).to(activated.dtype)
71+ return activated, weighted
72+ 
73+ 
74+def forward_fc2(weighted, sources, slot, counts, out):
75+ from mindspeed.ops.moonep_gmm import npu_gmm_v5_out
76+ 
77+ refs = tuple(weight.detach().t() for weight in (*sources, *tuple(slot)))
78+ npu_gmm_v5_out(weighted.detach(), refs, out.detach(), counts)
79+ 
80+ 
81+@contextmanager
82+def expert_backward(expert_plan, *, weights=(), output=None):
83+ """Supply already ordered weights/dX bank; collect only this call's dW tasks."""
84+ # The Autograd worker and the schedule can run on different threads.
85+ if expert_plan._expert_backward_call is not None:
86+ raise RuntimeError('expert backward collector is already active for this plan')
87+ tasks = []
88+ expert_plan._expert_backward_call = (expert_plan, weights, output, tasks)
89+ try:
90+ yield tasks
91+ finally:
92+ expert_plan._expert_backward_call = None
93+ 
94+ 
95+def _backward_call(expert_plan):
96+ call = expert_plan._expert_backward_call
97+ if call is None or call[0] is not expert_plan:
98+ raise RuntimeError('expert backward requires this exact call and a local dW collector')
99+ return call
100+ 
101+ 
102+def run_wgrad_task(task, *, restored_input=None, remote_targets=(), scratch=None):
103+ """Consume one delayed task. Communication is owned by the calling schedule."""
104+ import torch
105+ 
106+ kind, x, dy, targets, groups, fusion = task
107+ x = restored_input if x is None else x
108+ if x is None:
109+ raise RuntimeError('FC1 wgrad requires the restored original expert input')
110+ with torch.no_grad():
111+ if kind == 'routed':
112+ from mindspeed.ops.moonep_gmm import npu_grouped_matmul_add_fp32_out
113+ 
114+ compute.require_segment(targets)
115+ if scratch is None:
116+ raise RuntimeError('routed wgrad requires session-owned FP32 scratch')
117+ targets = targets + tuple(remote_targets)
118+ shape = tuple(targets[0].shape)
119+ contribution = scratch[: len(targets) * shape[0] * shape[1]].view(len(targets), *shape)
120+ contribution.zero_()
121+ npu_grouped_matmul_add_fp32_out(dy.detach(), x.detach(), contribution.detach(), groups)
122+ for target, value in zip(targets, contribution.unbind(0)):
123+ target.add_(value)
124+ elif fusion:
125+ import fused_weight_gradient_mlp_cuda
126+ 
127+ if targets.dtype == torch.float32:
128+ fused_weight_gradient_mlp_cuda.wgrad_gemm_accum_fp32(x, dy, targets)
129+ else:
130+ fused_weight_gradient_mlp_cuda.wgrad_gemm_accum_fp16(x, dy, targets)
131+ else:
132+ targets.add_(dy.t().matmul(x))
133+ 
134+ 
135+@lru_cache(maxsize=1)
136+def _get_autograd_functions():
137+ import torch
138+ from .. import session as fb_session
139+ 
140+ class RoutedExperts(torch.autograd.Function):
141+ @staticmethod
142+ def forward(ctx, hidden, probs, expert_plan, experts, buffers):
143+ slots, out, before_output, after_input = buffers
144+ session = fb_session.get_session()
145+ weights = tuple(experts.weight_refs('fc1')) + tuple(experts.weight_refs('fc2'))
146+ counts = expert_plan.group_counts_2l
147+ owners = []
148+ with compute.segment(experts, ctx, hidden, probs, expert_plan, buffers, owners):
149+ fc1 = forward_fc1(session, hidden, experts.weight_refs('fc1'), slots[0], counts)
150+ owners.append(fc1)
151+ if after_input is not None:
152+ after_input(hidden)
153+ activated, weighted = forward_activate(fc1, probs, experts)
154+ owners.extend((activated, weighted))
155+ if before_output is not None:
156+ before_output()
157+ forward_fc2(weighted, experts.weight_refs('fc2'), slots[1], counts, out)
158+ ctx.expert_plan, ctx.experts = expert_plan, experts
159+ ctx.versions = tuple((w._version, w.data_ptr()) for w in weights)
160+ # Forward activation banks are released before B. Keep an owned
161+ # probability snapshot, never a view of their reusable storage.
162+ ctx.save_for_backward(fc1, weighted, probs.clone(), *weights)
163+ return out
164+ 
165+ @staticmethod
166+ @torch.autograd.function.once_differentiable
167+ def backward(ctx, dy):
168+ from mindspeed.ops.moonep_gmm import npu_gmm_v5_out
169+ from mindspeed.core.transformer.moe.moe_feature.fb_overlap.modules.utils import run_graph_backward
170+ 
171+ expert_plan, slots, out, tasks = _backward_call(ctx.expert_plan)
172+ if len(slots) != 2 or out is None:
173+ raise RuntimeError('routed backward requires prefetched weights and the current dX bank')
174+ fc1, weighted, probs, *weights = ctx.saved_tensors
175+ if tuple((w._version, w.data_ptr()) for w in weights) != ctx.versions:
176+ raise RuntimeError('expert Parameter changed between forward and backward')
177+ experts, counts = ctx.experts, expert_plan.group_counts_2l
178+ owners = []
179+ with compute.segment(experts, ctx, ctx.saved_tensors, dy, expert_plan, slots, out, tasks, owners):
180+ dweighted = torch.empty_like(weighted)
181+ owners.append(dweighted)
182+ fc2_refs = tuple(weight.detach() for weight in (*experts.weight_refs('fc2'), *tuple(slots[1])))
183+ npu_gmm_v5_out(dy.detach(), fc2_refs, dweighted.detach(), counts)
184+ with torch.enable_grad():
185+ leaf = fc1.detach().requires_grad_(True)
186+ activation = expert_activation(leaf, experts)
187+ owners.extend((leaf, activation))
188+ run_graph_backward(
189+ (activation, None),
190+ (dweighted * probs[:, None]).to(activation.dtype),
191+ keep_graph=True,
192+ keep_grad=True,
193+ )
194+ dfc1 = leaf.grad
195+ owners.append(dfc1)
196+ dprobs = (dweighted.float() * activation.detach().float()).sum(-1).to(probs.dtype)
197+ owners.append(dprobs)
198+ fc1_refs = tuple(weight.detach() for weight in (*experts.weight_refs('fc1'), *tuple(slots[0])))
199+ npu_gmm_v5_out(dfc1.detach(), fc1_refs, out.detach(), counts)
200+ tasks.extend(
201+ (
202+ ('routed', weighted, dy, experts.grad_targets('fc2'), expert_plan.prefix, False),
203+ ('routed', None, dfc1, experts.grad_targets('fc1'), expert_plan.prefix, False),
204+ )
205+ )
206+ return out, dprobs, None, None, None
207+ 
208+ return (RoutedExperts,)
209+ 
210+ 
211+def routed_forward(hidden, probs, expert_plan, experts, slots, out, *, before_output=None, after_input=None):
212+ # The bank is a backend output, not an Autograd input/edge. Do not mutate
213+ # the runtime's persistent Tensor wrapper when attaching its grad_fn.
214+ return _get_autograd_functions()[0].apply(
215+ hidden, probs, expert_plan, experts, (slots, out.detach(), before_output, after_input)
216+ )
@@ -0,0 +1,127 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""Shared expert computation and Autograd; dW uses the exact plan's collector."""
16+ 
17+from contextlib import nullcontext
18+from functools import lru_cache
19+ 
20+from .experts import _backward_call
21+ 
22+ 
23+@lru_cache(maxsize=1)
24+def _get_autograd_functions():
25+ import torch
26+ 
27+ class SharedFC1(torch.autograd.Function):
28+ @staticmethod
29+ def forward(ctx, hidden, weights, config, expert_plan, build_graph):
30+ fc1 = torch.nn.functional.linear(hidden, weights[0].detach())
31+ # Autograd disables grad inside Function.forward, so the caller
32+ # supplies its mode for the saved SwiGLU backward graph.
33+ with torch.enable_grad() if build_graph else nullcontext():
34+ leaf = fc1.detach().requires_grad_(True) if build_graph else fc1
35+ if getattr(config, 'bias_activation_fusion', False):
36+ from megatron.core.fusions.fused_bias_swiglu import bias_swiglu_impl
37+ 
38+ activation = bias_swiglu_impl(leaf, None, getattr(config, 'activation_func_fp8_input_store', False))
39+ else:
40+ gate, value = leaf.chunk(2, -1)
41+ activation = torch.nn.functional.silu(gate) * value
42+ if build_graph:
43+ ctx.save_for_backward(hidden, leaf, activation, *weights)
44+ ctx.versions = tuple((w._version, w.data_ptr()) for w in weights)
45+ ctx.config, ctx.expert_plan = config, expert_plan
46+ ctx.target = getattr(weights[0], 'main_grad', None)
47+ ctx.target_address = ctx.target.data_ptr() if ctx.target is not None else None
48+ return activation.detach()
49+ 
50+ @staticmethod
51+ @torch.autograd.function.once_differentiable
52+ def backward(ctx, dy):
53+ from mindspeed.core.transformer.moe.moe_feature.fb_overlap.modules.utils import run_graph_backward
54+ 
55+ hidden, leaf, activation, *weights = ctx.saved_tensors
56+ if tuple((w._version, w.data_ptr()) for w in weights) != ctx.versions:
57+ raise RuntimeError('shared Parameters changed before backward')
58+ if weights[0].main_grad is not ctx.target or ctx.target.data_ptr() != ctx.target_address:
59+ raise RuntimeError('shared FC1 main_grad changed before backward')
60+ run_graph_backward((activation, None), dy, keep_graph=True, keep_grad=True)
61+ dx = leaf.grad @ weights[0].detach()
62+ _backward_call(ctx.expert_plan)[3].append(
63+ (
64+ 'shared',
65+ hidden,
66+ leaf.grad,
67+ weights[0].main_grad,
68+ None,
69+ getattr(ctx.config, 'gradient_accumulation_fusion', False),
70+ )
71+ )
72+ return dx, None, None, None, None
73+ 
74+ class SharedFC2(torch.autograd.Function):
75+ @staticmethod
76+ def forward(ctx, hidden, weights, config, expert_plan):
77+ ctx.save_for_backward(hidden, *weights)
78+ ctx.config, ctx.expert_plan = config, expert_plan
79+ ctx.versions = tuple((w._version, w.data_ptr()) for w in weights)
80+ ctx.target = getattr(weights[1], 'main_grad', None)
81+ ctx.target_address = ctx.target.data_ptr() if ctx.target is not None else None
82+ return torch.nn.functional.linear(hidden, weights[1].detach())
83+ 
84+ @staticmethod
85+ @torch.autograd.function.once_differentiable
86+ def backward(ctx, dy):
87+ hidden, *weights = ctx.saved_tensors
88+ if tuple((w._version, w.data_ptr()) for w in weights) != ctx.versions:
89+ raise RuntimeError('shared Parameters changed before backward')
90+ if weights[1].main_grad is not ctx.target or ctx.target.data_ptr() != ctx.target_address:
91+ raise RuntimeError('shared FC2 main_grad changed before backward')
92+ dx = dy @ weights[1].detach()
93+ _backward_call(ctx.expert_plan)[3].append(
94+ (
95+ 'shared',
96+ hidden,
97+ dy,
98+ weights[1].main_grad,
99+ None,
100+ getattr(ctx.config, 'gradient_accumulation_fusion', False),
101+ )
102+ )
103+ return dx, None, None, None
104+ 
105+ return SharedFC1, SharedFC2
106+ 
107+ 
108+def shared_fc1(hidden, layer, expert_plan, weights):
109+ import torch
110+ 
111+ hidden = hidden.reshape(-1, hidden.shape[-1])
112+ if getattr(layer.config, 'sequence_parallel', False):
113+ from megatron.core.tensor_parallel.mappings import gather_from_sequence_parallel_region
114+ 
115+ hidden = gather_from_sequence_parallel_region(hidden, group=layer.mlp.shared_experts.tp_group)
116+ return _get_autograd_functions()[0].apply(
117+ hidden, weights, layer.mlp.shared_experts.config, expert_plan, torch.is_grad_enabled()
118+ )
119+ 
120+ 
121+def shared_fc2(hidden, layer, expert_plan, weights):
122+ output = _get_autograd_functions()[1].apply(hidden, weights, layer.mlp.shared_experts.config, expert_plan)
123+ if getattr(layer.config, 'sequence_parallel', False):
124+ from megatron.core.tensor_parallel.mappings import reduce_scatter_to_sequence_parallel_region
125+ 
126+ output = reduce_scatter_to_sequence_parallel_region(output, group=layer.mlp.shared_experts.tp_group)
127+ return output
@@ -0,0 +1,388 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""Shared helpers and saved graph segments for MoonEP FB overlap."""
16+ 
17+import weakref
18+ 
19+ 
20+def is_non_identity_norm(norm):
21+ """Keep Identity storage out of MoonEP's discard/recompute path."""
22+ from megatron.core.transformer.identity_op import IdentityOp
23+ from torch.nn import Identity
24+ 
25+ return not isinstance(norm, (Identity, IdentityOp))
26+ 
27+ 
28+def validate_forward_stream(stream):
29+ import torch
30+ 
31+ current = torch.npu.current_stream()
32+ if current.device != stream.device or current.npu_stream != stream.npu_stream:
33+ raise ValueError("MoonEP caller must use the fixed Q1 device and stream")
34+ 
35+ 
36+def validate_shared_experts(layer, *, backward=False):
37+ """Canonical shared-expert Parameters with matched TP/SP on Q1."""
38+ module = getattr(layer.mlp, 'shared_experts', None)
39+ width = getattr(getattr(layer, 'config', None), 'moe_shared_expert_intermediate_size', None)
40+ if module is None:
41+ if width:
42+ raise ValueError('MoonEP shared config requires a SharedExpertMLP module')
43+ return ()
44+ import torch
45+ import torch.nn.functional as F
46+ 
47+ config = module.config
48+ tp = getattr(config, 'tensor_model_parallel_size', 1)
49+ if (
50+ type(tp) is not int # pylint: disable=too-many-boolean-expressions,unidiomatic-typecheck
51+ or tp < 1
52+ or tp != getattr(layer.config, 'tensor_model_parallel_size', 1)
53+ or bool(getattr(config, 'sequence_parallel', False)) != bool(getattr(layer.config, 'sequence_parallel', False))
54+ or (tp > 1 and not getattr(config, 'sequence_parallel', False))
55+ or (tp > 1 and getattr(module, 'tp_group', None) is None)
56+ ):
57+ raise ValueError('MoonEP shared experts require matched TP/SP and the actual shared TP group')
58+ if (
59+ getattr(config, 'moe_shared_expert_overlap', False) # pylint: disable=too-many-boolean-expressions
60+ or getattr(config, 'add_bias_linear', False)
61+ or (not getattr(config, 'gated_linear_unit', False))
62+ or (getattr(config, 'activation_func', None) is not F.silu)
63+ or getattr(module, 'use_shared_expert_gate', False)
64+ or (getattr(module, 'gate_weight', None) is not None)
65+ or (getattr(config, 'glu_linear_offset', 0) != 0)
66+ or (getattr(config, 'activation_func_clamp_value', None) is not None)
67+ or (getattr(config, 'moe_mlp_glu_interleave_size', None) is not None)
68+ or getattr(config, 'fp8', None)
69+ or getattr(config, 'fp4', None)
70+ ):
71+ raise ValueError('MoonEP shared experts require bias-free SwiGLU without gate/legacy overlap/FP8')
72+ weights = (module.linear_fc1.weight, module.linear_fc2.weight)
73+ parameters = tuple(module.parameters())
74+ w1, w2 = weights
75+ if (
76+ len(parameters) != 2 # pylint: disable=too-many-boolean-expressions
77+ or any((not any((p is w for w in weights)) for p in parameters))
78+ or w1.ndim != 2
79+ or (w2.ndim != 2)
80+ or (w1.shape != (2 * w2.shape[1], w2.shape[0]))
81+ or (width and w2.shape[1] * tp != width)
82+ or any(
83+ (
84+ w.dtype not in (torch.bfloat16, torch.float32)
85+ or not w.is_contiguous()
86+ or w.device != w1.device
87+ or (w.dtype != w1.dtype)
88+ for w in weights
89+ )
90+ )
91+ ):
92+ raise ValueError('MoonEP shared experts have an unsupported Parameter schema/layout')
93+ if backward:
94+ for w in weights:
95+ target = getattr(w, 'main_grad', None)
96+ if (
97+ not w.requires_grad # pylint: disable=too-many-boolean-expressions
98+ or target is None
99+ or target.shape != w.shape
100+ or (target.dtype != torch.float32)
101+ or (target.device != w.device)
102+ or (not target.is_contiguous())
103+ ):
104+ raise ValueError('MoonEP shared experts require canonical contiguous FP32 main_grad')
105+ return weights
106+ 
107+ 
108+def validate_forward_inputs(hidden, probs, indices, counts, step_plan, global_experts):
109+ import torch
110+ 
111+ expected = (step_plan["input_shape"][0], step_plan["topk"])
112+ if (
113+ tuple(hidden.shape) != step_plan["input_shape"]
114+ or tuple(probs.shape) != expected
115+ or tuple(indices.shape) != expected
116+ or tuple(counts.shape) != (global_experts,)
117+ ):
118+ raise ValueError("MoonEP requires the frozen fixed-shape compact routing inputs")
119+ for tensor, dtype in (
120+ (hidden, torch.bfloat16),
121+ (probs, torch.float32),
122+ (indices, torch.int32),
123+ (counts, torch.int32),
124+ ):
125+ if tensor.dtype != dtype or not tensor.is_contiguous() or tensor.device != hidden.device:
126+ raise ValueError("MoonEP inputs must have the provider dtype/layout on one device")
127+ 
128+ 
129+def build_forward_group_counts(cu_seqlens, hidden, *, rank, local_experts, global_experts):
130+ return build_physical_counts(
131+ cu_seqlens,
132+ rank=rank,
133+ local_experts=local_experts,
134+ global_experts=global_experts,
135+ slots=local_experts,
136+ carrier_rows=int(hidden.shape[0]),
137+ )
138+ 
139+ 
140+def moonep_graph_key(graph):
141+ return graph.moonep_key if getattr(graph, 'backend', None) == 'a2a' else graph.key
142+ 
143+ 
144+def validate_overlap_parallel_config(config):
145+ """Common Dense/routed topology; sequence shards remain owned by FB linears."""
146+ tp, pp = (getattr(config, name, 1) for name in ('tensor_model_parallel_size', 'pipeline_model_parallel_size'))
147+ vpp = getattr(config, 'virtual_pipeline_model_parallel_size', None)
148+ vpp = 1 if vpp is None else vpp
149+ if (
150+ any(type(size) is not int or size < 1 for size in (tp, pp, vpp)) # pylint: disable=unidiomatic-typecheck
151+ or getattr(config, 'expert_tensor_parallel_size', 1) != 1
152+ or getattr(config, 'context_parallel_size', 1) != 1
153+ or (pp == 1 and vpp != 1)
154+ ):
155+ raise ValueError('MoonEP overlap requires positive TP/PP, regular VPP and ETP1/CP1')
156+ # TP1 normalization belongs to the original argument entrypoint. Consume
157+ # its actual config here; TP size does not determine whether SP is active.
158+ return tp, pp, vpp, bool(getattr(config, 'sequence_parallel', False))
159+ 
160+ 
161+def validate_dense_layer(layer):
162+ """Admit ordinary Dense FB math without constructing a native expert plan."""
163+ import torch
164+ 
165+ config, mlp = layer.config, layer.mlp
166+ validate_overlap_parallel_config(config)
167+ if (
168+ not isinstance(mlp, torch.nn.Module) # pylint: disable=too-many-boolean-expressions
169+ or hasattr(mlp, 'experts')
170+ or hasattr(mlp, 'hot_experts')
171+ or getattr(mlp, 'token_dispatcher', None) is not None
172+ or getattr(mlp, 'shared_experts', None) is not None
173+ or getattr(config, 'add_bias_linear', False)
174+ or getattr(config, 'fp8', None)
175+ or getattr(config, 'fp4', None)
176+ or getattr(layer, 'hidden_dropout', 0)
177+ or getattr(config, 'attention_dropout', 0)
178+ or getattr(layer, 'moonep_math_version', None) is not None
179+ ):
180+ raise ValueError('mixed Dense layer requires ordinary CP1 math without dropout')
181+ 
182+ 
183+def validate_forward_layer(layer):
184+ """Reject unsupported layer math before attention or native submission."""
185+ if getattr(layer, 'moonep_math_version', None) is not None:
186+ raise ValueError('Kimi/model-specific attention adapters are disabled in MoonEP overlap')
187+ import torch.nn.functional as F
188+ from ..config_validation import validate_recompute_config
189+ 
190+ config = layer.config
191+ validate_recompute_config(config)
192+ manager = getattr(getattr(layer.mlp, 'token_dispatcher', None), '_comm_manager', None)
193+ if manager is None and not hasattr(layer.mlp, 'experts') and not hasattr(layer.mlp, 'hot_experts'):
194+ return validate_dense_layer(layer)
195+ experts = getattr(manager, 'virtual_experts', None)
196+ if experts is None or experts.gtp_enabled:
197+ raise ValueError('MoonEP layer requires a bound standard manager')
198+ validate_overlap_parallel_config(config)
199+ if (
200+ getattr(config, 'moe_expert_capacity_factor', None) is not None # pylint: disable=too-many-boolean-expressions
201+ or getattr(config, 'moe_pad_expert_input_to_capacity', False)
202+ or getattr(config, 'moe_apply_probs_on_input', False)
203+ or getattr(config, 'moe_latent_size', None)
204+ or getattr(config, 'add_bias_linear', False)
205+ or (getattr(config, 'glu_linear_offset', 0) != 0)
206+ or (getattr(config, 'activation_func_clamp_value', None) is not None)
207+ or (getattr(config, 'moe_mlp_glu_interleave_size', None) is not None)
208+ or getattr(config, 'fp8', None)
209+ or getattr(config, 'fp4', None)
210+ or getattr(layer, 'hidden_dropout', 0)
211+ or getattr(config, 'hidden_dropout', 0)
212+ or getattr(config, 'attention_dropout', 0)
213+ or (getattr(config, 'moe_input_jitter_eps', None) is not None)
214+ or (not getattr(config, 'gated_linear_unit', False))
215+ or (getattr(config, 'activation_func', None) is not F.silu)
216+ ):
217+ raise ValueError(
218+ 'MoonEP routed layer requires bias-free SwiGLU with post-activation probabilities, no drop/latent/FP8'
219+ )
220+ if (
221+ getattr(config, 'moe_token_dispatcher_type', None) != 'flex'
222+ or getattr(config, 'moe_flex_dispatcher_backend', None) != 'moonep'
223+ ):
224+ raise ValueError('MoonEP routed layer requires the MoonEP Flex backend')
225+ return manager
226+ 
227+ 
228+def validate_layer_cotangent(output, grad):
229+ import torch
230+ 
231+ if (
232+ not isinstance(output, torch.Tensor) # pylint: disable=too-many-boolean-expressions
233+ or not output.requires_grad
234+ or not isinstance(grad, torch.Tensor)
235+ or grad.shape != output.shape
236+ or grad.dtype != output.dtype
237+ or grad.device != output.device
238+ ):
239+ raise ValueError('MoonEP backward requires a training graph and matching output cotangent')
240+ 
241+ 
242+def compact_router_outputs(probs, routing_map, *, tokens, topk, global_experts):
243+ import torch
244+ 
245+ if (
246+ routing_map.ndim != 2 # pylint: disable=too-many-boolean-expressions
247+ or probs.ndim != 2
248+ or routing_map.shape[0] != tokens
249+ or probs.shape != routing_map.shape
250+ or probs.device != routing_map.device
251+ or topk > global_experts
252+ ):
253+ raise ValueError("router output shape/device differs from frozen layout")
254+ if routing_map.dtype == torch.bool:
255+ if routing_map.shape[1] != global_experts:
256+ raise ValueError("dense router mask must be [tokens, global_experts]")
257+ _, indices = torch.topk(routing_map.to(torch.int32), topk, dim=-1, sorted=False)
258+ compact_probs = torch.gather(probs, 1, indices)
259+ elif routing_map.dtype in (torch.int32, torch.int64):
260+ if routing_map.shape[1] != topk:
261+ raise ValueError("compact router indices must be [tokens, topk]")
262+ indices, compact_probs = routing_map.to(torch.int64), probs
263+ else:
264+ raise TypeError("router must return bool dense mask or integer compact indices")
265+ counts = torch.zeros(global_experts, dtype=torch.int32, device=indices.device)
266+ flat = indices.reshape(-1)
267+ counts.scatter_add_(0, flat, torch.ones_like(flat, dtype=torch.int32))
268+ return (compact_probs.to(torch.float32).contiguous(), indices.to(torch.int32).contiguous(), counts)
269+ 
270+ 
271+class MoonEPLayerGraph:
272+ def __init__(self, saved_graph_and_graph_inputs, layer, layer_input, expert_plan, checkpointed=False):
273+ if expert_plan.provider_plan is None or expert_plan.execution_key is None:
274+ raise ValueError('MoonEP LayerGraph requires an exact provider plan and generation key')
275+ self.backend = 'moonep'
276+ if not checkpointed:
277+ (
278+ self.attn_graph,
279+ self.pre_mlp_layernorm_graph,
280+ self.router_graph,
281+ self.dispatch_graph,
282+ self.grouped_mlp_graph,
283+ self.combine_graph,
284+ self.mlp_bda_graph,
285+ self.shared_experts_graph,
286+ ) = saved_graph_and_graph_inputs
287+ else:
288+ self.mlp_bda_graph = (None, None)
289+ self.layer = layer
290+ self.layer_input = layer_input
291+ self.checkpointed = checkpointed
292+ if expert_plan.exact_graph_ref is not None:
293+ raise RuntimeError('MoonEP plan is already bound to an exact graph')
294+ self.expert_plan = expert_plan
295+ self.is_moe_layer = True
296+ expert_plan.exact_graph_ref = weakref.ref(self)
297+ 
298+ def validate_exact(self, manager, *, forward=False):
299+ expert_plan = self.expert_plan
300+ if (
301+ expert_plan.manager_cookie is not manager._cookie # pylint: disable=too-many-boolean-expressions
302+ or not expert_plan.admitted
303+ or expert_plan.retired
304+ or expert_plan.execution_key is None
305+ or expert_plan.exact_graph_ref is None
306+ or expert_plan.exact_graph_ref() is not self
307+ or (forward and manager._plan is not expert_plan)
308+ ):
309+ raise RuntimeError('MoonEP call received a foreign or retired exact plan')
310+ return expert_plan
311+ 
312+ @property
313+ def key(self):
314+ return self.expert_plan.execution_key
315+ 
316+ def set_output_boundary(self, detached_output):
317+ self.mlp_bda_graph = (self.mlp_bda_graph[0], detached_output)
318+ 
319+ def get_output_boundary(self):
320+ return self.mlp_bda_graph[1]
321+ 
322+ 
323+def clear_dispatch_padding(hidden, probs=None, *, cu_seqlens=None, padding_mask=None):
324+ """Zero framework-owned GMM padding after Dispatch and before its consumer.
325+ 
326+ Cache the device mask in FBVirtualExpertPlan for Z3/R1 redispatches, which do
327+ not return new cumulative counts. Async callers use their existing Q1 wait;
328+ no host read, collective or additional completion event is introduced.
329+ """
330+ import torch
331+ 
332+ with torch.no_grad():
333+ if padding_mask is None:
334+ if cu_seqlens is None:
335+ raise ValueError("Dispatch padding requires counts or its saved mask")
336+ rows = torch.arange(hidden.shape[0], dtype=torch.int32, device=hidden.device)
337+ padding_mask = rows >= cu_seqlens[-1]
338+ if hidden.device.type == 'npu':
339+ cu_seqlens.record_stream(torch.npu.current_stream())
340+ hidden.masked_fill_(padding_mask.unsqueeze(-1), 0)
341+ if probs is not None:
342+ probs.masked_fill_(padding_mask, 0)
343+ if hidden.device.type == 'npu':
344+ padding_mask.record_stream(torch.npu.current_stream())
345+ return padding_mask
346+ 
347+ 
348+def build_physical_counts(
349+ global_cu_seqlens,
350+ *,
351+ rank: int,
352+ local_experts: int,
353+ global_experts: int,
354+ slots: int,
355+ carrier_rows: int | None = None,
356+):
357+ """Return device counts ordered as this rank's L natives followed by B slots.
358+ 
359+ MoonEP uses a fixed-capacity carrier. A rank may receive fewer routed rows
360+ than that capacity, but grouped GMM must still partition every carrier row.
361+ Assign the framework-zeroed suffix to the final slot without a device-to-host
362+ synchronization. clear_dispatch_padding owns this zero-fill contract.
363+ Zero activation rows make this padding mathematically
364+ inert in forward, dgrad, and standard AddV2 wgrad.
365+ """
366+ import torch
367+ 
368+ if global_cu_seqlens.dtype != torch.int32 or global_cu_seqlens.ndim != 1:
369+ raise TypeError("global_cu_seqlens must be a one-dimensional INT32 tensor")
370+ if not global_cu_seqlens.is_contiguous():
371+ raise ValueError("global_cu_seqlens must be contiguous")
372+ if slots != local_experts:
373+ raise ValueError("MoonEP FB requires B == L")
374+ if global_cu_seqlens.numel() != global_experts + slots:
375+ raise ValueError("global_cu_seqlens must describe E native groups followed by B slots")
376+ prefix = torch.zeros(1, dtype=global_cu_seqlens.dtype, device=global_cu_seqlens.device)
377+ global_counts = torch.diff(torch.cat((prefix, global_cu_seqlens))).to(torch.int64)
378+ begin = int(rank) * int(local_experts)
379+ end = begin + int(local_experts)
380+ if begin < 0 or end > int(global_experts):
381+ raise ValueError("rank/local expert range is outside the global expert axis")
382+ physical_counts = torch.cat((global_counts[begin:end], global_counts[global_experts:])).contiguous()
383+ if carrier_rows is not None:
384+ carrier_rows = int(carrier_rows)
385+ if carrier_rows <= 0:
386+ raise ValueError("carrier_rows must be positive")
387+ physical_counts[-1].add_(carrier_rows - physical_counts.sum())
388+ return physical_counts
@@ -0,0 +1,461 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""Native event plumbing for call-local release records, without provider receipts.
16+ 
17+There is one frozen schedule cursor and one bank ownership map in the existing
18+runtime. Completion/final-use/release events stay in the active schedule's
19+local release records; no communication handles are retained by LayerGraph.
20+"""
21+ 
22+from .runtime import activation_alias as _activation_view, fail_stop
23+from dataclasses import dataclass
24+from threading import get_ident
25+ 
26+from .schedule_plan import (
27+ BACKWARD_RELEASE_ORDER,
28+ BACKWARD_SLOTS,
29+ FORWARD_RELEASE_ORDER,
30+ FORWARD_SLOTS,
31+ get_operation_ordinal,
32+)
33+from .release import observe_max
34+ 
35+ 
36+_KIND_BY_ROLE = {role: kind for kind, role in (*FORWARD_SLOTS, *BACKWARD_SLOTS)}
37+ 
38+ 
39+@dataclass
40+class ReleaseRecord:
41+ generation: tuple
42+ kind: str
43+ role: str
44+ bank_index: int
45+ release_ordinal: int
46+ event: object = None
47+ final_use_event: object = None
48+ barrier_event: object = None
49+ released: bool = False
50+ queued_on_q0: bool = False
51+ successor: tuple | None = None
52+ 
53+ 
54+def get_session(session=None):
55+ from . import session as fb_session
56+ 
57+ if session is None:
58+ return fb_session.get_session()
59+ if session is not fb_session._SESSION:
60+ raise RuntimeError('MoonEP native call received a stale or foreign session')
61+ if fb_session.runtime.process._FATAL_ERROR is not None:
62+ return fb_session.get_session() # Preserve canonical fail-stop admission.
63+ return session
64+ 
65+ 
66+def _validate_step(session, generation, ordinal, action, kind, next_ordinal):
67+ base = session['step_plan'].get('ordinal_base', 0)
68+ steps = session['step_plan']['q0_steps']
69+ if session['submit_thread'] != get_ident():
70+ raise RuntimeError('MoonEP requires one host submission thread')
71+ if type(ordinal) is not int or ordinal != next_ordinal: # pylint: disable=unidiomatic-typecheck
72+ raise ValueError('out-of-order Q0 ordinal')
73+ index = ordinal - base
74+ if not 0 <= index < len(steps):
75+ raise ValueError('Q0 step outside frozen work')
76+ expected = steps[index]
77+ if (expected[0], expected[1].value, expected[2]) != (action, kind, generation):
78+ raise ValueError('Q0 step differs from frozen rank-comparable schedule')
79+ 
80+ 
81+def claim_step(generation, ordinal, action, kind, *, _session=None):
82+ session = get_session(_session)
83+ _validate_step(session, generation, ordinal, action, kind, session['next_ordinal'])
84+ session['next_ordinal'] += 1
85+ if action == 'submit':
86+ session['outstanding_operations'] += 1
87+ 
88+ 
89+def claim_bank(role, index, generation, *, _session=None):
90+ from .plan_types import BankKey
91+ 
92+ session = get_session(_session)
93+ key = BankKey(role, index)
94+ spec = session['step_plan']['capacity'].pools.get(role)
95+ if spec is None or type(index) is not int or not 0 <= index < spec.count: # pylint: disable=unidiomatic-typecheck
96+ raise ValueError('bank outside frozen capacity')
97+ physical = session['resource_capacity'].physical_key(key)
98+ if physical in session['bank_owners']:
99+ previous = session.get('pending_bank_releases', {}).get(physical)
100+ if (
101+ previous is None
102+ or previous.successor is not None
103+ or session['bank_owners'][physical] != previous.generation
104+ ):
105+ raise RuntimeError('bank still has a live consumer')
106+ if role == 'Z2' and previous.role == 'Z3':
107+ previous.successor = generation
108+ session.setdefault('z2_write_waits', {})[(physical, generation)] = previous.barrier_event
109+ else:
110+ confirm_releases((previous,))
111+ session['bank_owners'][physical] = generation
112+ return key
113+ 
114+ 
115+def get_projection_binding(generation, role, index, *, _session=None):
116+ return get_session(_session)['projection_bindings'][(generation[3], role, index)]
117+ 
118+ 
119+def submit_dispatch(
120+ hidden,
121+ *,
122+ generation,
123+ ordinal,
124+ activation_role,
125+ bank_index,
126+ route_weights_sk=None,
127+ topk_experts_sk=None,
128+ tokens_per_expert=None,
129+ comm_plan=None,
130+):
131+ session = get_session()
132+ claim_step(generation, ordinal, 'submit', _KIND_BY_ROLE[activation_role], _session=session)
133+ zc = session['step_plan'].get('strict_zero_copy', False)
134+ kwargs = {}
135+ comm_buffers = None
136+ if zc:
137+ key = claim_bank(activation_role, bank_index, generation, _session=session)
138+ comm_buffers = session['comm_buffers'][key]
139+ # Keep the old private Dispatch's single post-completion fence.
140+ kwargs['inter_rank_sync'] = False
141+ session['buffer'].set_comm_buffers(comm_buffers)
142+ values = session['buffer'].dispatch(
143+ hidden,
144+ route_weights_sk,
145+ topk_experts_sk,
146+ tokens_per_expert,
147+ plan=comm_plan,
148+ async_finish=True,
149+ zero_copy=zc,
150+ router_weights_zero_copy=zc,
151+ **kwargs,
152+ )
153+ z, route, cu, comm_plan, event = values
154+ if zc:
155+ z = _activation_view(z)
156+ if route is not None:
157+ route = _activation_view(route)
158+ return event, z, route, cu, comm_plan
159+ 
160+ 
161+def acquire_activation(*, role, bank_index, generation, comm_plan):
162+ from .plan_types import BankKey
163+ import torch
164+ 
165+ session = get_session()
166+ key = BankKey(role, bank_index)
167+ if session['step_plan'].get('strict_zero_copy', False):
168+ key = claim_bank(role, bank_index, generation, _session=session)
169+ bank = session['comm_buffers'][key]
170+ return (
171+ key,
172+ _activation_view(bank.hidden, (int(comm_plan.NvS), bank.hidden.shape[1]), torch.bfloat16),
173+ _activation_view(bank.route, (int(comm_plan.NvS),), torch.float32),
174+ )
175+ hidden = torch.empty(
176+ int(comm_plan.NvS), session['step_plan']['input_shape'][1], dtype=torch.bfloat16, device=comm_plan.dst.device
177+ )
178+ route = torch.empty(int(comm_plan.NvS), dtype=torch.float32, device=hidden.device)
179+ return key, hidden, route
180+ 
181+ 
182+def submit_combine(comm_plan, bank_key, *, generation, ordinal, hidden_nvsh, route_weights_nvs=None, backward=False):
183+ session = get_session()
184+ claim_step(generation, ordinal, 'submit', _KIND_BY_ROLE['Z4' if backward else 'Z2'], _session=session)
185+ zc = session['step_plan'].get('strict_zero_copy', False)
186+ comm_buffers = None
187+ if zc:
188+ physical = session['resource_capacity'].physical_key(bank_key)
189+ if session['bank_owners'].get(physical) != generation:
190+ raise ValueError('combine does not own its activation bank')
191+ if (physical, generation) in session.get('z2_write_waits', {}):
192+ raise RuntimeError('combine requires the Z2 writer to have installed its release wait')
193+ comm_buffers = session['comm_buffers'][bank_key]
194+ session['buffer'].set_comm_buffers(comm_buffers)
195+ output, route, event = session['buffer'].combine(
196+ comm_plan, hidden_nvsh, route_weights_nvs, async_finish=True, zero_copy=zc, router_weights_zero_copy=zc
197+ )
198+ return event, output, route
199+ 
200+ 
201+def _validate_expert_refs(binding, refs):
202+ # The provider checks bound storage/layout on every submit. Only changed
203+ # references need the extra caller-side check (including main_grad aliases).
204+ refs = tuple(refs)
205+ if len(refs) != len(binding.expert_tensors) or any(
206+ ref is not bound for ref, bound in zip(refs, binding.expert_tensors)
207+ ):
208+ binding.validate_expert_tensors(refs)
209+ 
210+ 
211+def submit_prefetch(comm_plan, expert_weights, *, projection, bank_index, generation, ordinal):
212+ session = get_session()
213+ role = projection + '_weight'
214+ binding = get_projection_binding(generation, role, bank_index, _session=session)
215+ _validate_expert_refs(binding, expert_weights)
216+ claim_step(generation, ordinal, 'submit', _KIND_BY_ROLE[role], _session=session)
217+ claim_bank(role, bank_index, generation, _session=session)
218+ event = session['buffer'].prefetch_weight_from_ptrs(comm_plan, binding, async_finish=True)
219+ return event, binding.comm_buffer
220+ 
221+ 
222+def acquire_grad(*, projection, bank_index, generation):
223+ session = get_session()
224+ role = projection + '_grad'
225+ key = claim_bank(role, bank_index, generation, _session=session)
226+ return key, get_projection_binding(generation, role, bank_index, _session=session).comm_buffer
227+ 
228+ 
229+def submit_reduce(comm_plan, expert_grads, *, projection, grad_lease, generation, ordinal):
230+ session = get_session()
231+ role = projection + '_grad'
232+ if grad_lease.role != role or session['bank_owners'].get(grad_lease) != generation:
233+ raise ValueError('reduce does not own its projection slot')
234+ binding = get_projection_binding(generation, role, grad_lease.index, _session=session)
235+ _validate_expert_refs(binding, expert_grads)
236+ claim_step(generation, ordinal, 'submit', _KIND_BY_ROLE[role], _session=session)
237+ return session['buffer'].reduce_grad_to_ptrs(comm_plan, binding, async_finish=True)
238+ 
239+ 
240+def z2_write_dependency(bank_key, generation):
241+ session = get_session()
242+ physical = session['resource_capacity'].physical_key(bank_key)
243+ key = physical, generation
244+ reserved = session.get('z2_write_waits', {})
245+ if key not in reserved:
246+ return None
247+ 
248+ def install_wait():
249+ if session['bank_owners'].get(physical) != generation:
250+ raise RuntimeError('Z2 writer lost its reserved bank')
251+ # The caller invokes this on fixed Q1, immediately before FC2 writes.
252+ session['q1'].wait_event(reserved[key])
253+ del reserved[key]
254+ 
255+ return install_wait
256+ 
257+ 
258+def wait(event, *, required='peer_visible', consumer_stream):
259+ if required != 'peer_visible' or event is None or consumer_stream is not get_session()['q1']:
260+ raise ValueError('wait requires a native completion event on fixed Q1')
261+ consumer_stream.wait_event(event)
262+ 
263+ 
264+def record_final_use(record, *, consumer_stream):
265+ if consumer_stream is not get_session()['q1'] or record.event is None:
266+ raise ValueError('final use requires fixed Q1 and a completion event')
267+ if record.final_use_event is not None:
268+ raise RuntimeError('final use must be recorded exactly once')
269+ record.final_use_event = consumer_stream.record_event()
270+ 
271+ 
272+def _queue_release(session, record):
273+ if record.barrier_event is not None:
274+ return
275+ claim_step(record.generation, record.release_ordinal, 'release', record.kind)
276+ q0 = session['buffer'].comm_stream
277+ import torch_npu
278+ 
279+ with torch_npu.npu.stream(q0):
280+ q0.wait_event(record.final_use_event)
281+ session['buffer'].barrier_on_stream(q0)
282+ record.barrier_event = q0.record_event()
283+ record.queued_on_q0 = True
284+ 
285+ 
286+def _complete_release(session, record):
287+ """Commit metadata after the batch fences and all owner checks succeed."""
288+ from .plan_types import BankKey
289+ 
290+ if record.released:
291+ return
292+ if record.role.startswith(('fc1', 'fc2')) or session['step_plan'].get('strict_zero_copy', False):
293+ bank = session['resource_capacity'].physical_key(BankKey(record.role, record.bank_index))
294+ if record.successor is None:
295+ del session['bank_owners'][bank]
296+ pending_banks = session.get('pending_bank_releases', {})
297+ if pending_banks.get(bank) is record:
298+ del pending_banks[bank]
299+ session['outstanding_operations'] -= 1
300+ record.released = True
301+ 
302+ 
303+def _submit_releases(session, records):
304+ records = tuple(records)
305+ next_ordinal = session['next_ordinal']
306+ seen = set()
307+ # Validate the whole segment before enqueueing even its first barrier.
308+ for record in records:
309+ identity = id(record.event)
310+ if record.event is None or identity in seen or record.final_use_event is None:
311+ raise ValueError('batch needs unique events with recorded final use')
312+ seen.add(identity)
313+ if record.barrier_event is None:
314+ _validate_step(session, record.generation, record.release_ordinal, 'release', record.kind, next_ordinal)
315+ next_ordinal += 1
316+ pending = tuple(record for record in records if not record.released)
317+ fresh = all(record.barrier_event is None for record in pending)
318+ try:
319+ for record in pending:
320+ _queue_release(session, record)
321+ except BaseException as error:
322+ fail_stop(error, session, pending)
323+ raise
324+ return pending, fresh
325+ 
326+ 
327+def confirm_releases(records, *, block=True, fresh=False):
328+ from .plan_types import BankKey
329+ 
330+ session = get_session()
331+ pending = tuple(record for record in records if not record.released)
332+ if not pending:
333+ return True
334+ try:
335+ if any(record.barrier_event is None for record in pending):
336+ raise RuntimeError('MoonEP FB completion requires a submitted release')
337+ if fresh:
338+ fences = (pending[-1],)
339+ elif all(record.queued_on_q0 for record in pending):
340+ # All queued events share the fixed Q0. Ordinals are assigned in
341+ # actual submission order, including an earlier deferred Z3.
342+ fences = (max(pending, key=lambda record: record.release_ordinal),)
343+ else:
344+ fences = pending
345+ for record in fences:
346+ if block:
347+ record.barrier_event.synchronize()
348+ elif not record.barrier_event.query():
349+ return False
350+ for record in pending:
351+ if record.role.startswith(('fc1', 'fc2')) or session['step_plan'].get('strict_zero_copy', False):
352+ bank = session['resource_capacity'].physical_key(BankKey(record.role, record.bank_index))
353+ owner = record.generation if record.successor is None else record.successor
354+ if session['bank_owners'].get(bank) != owner:
355+ raise RuntimeError('bank ownership changed before release')
356+ for record in pending:
357+ _complete_release(session, record)
358+ return True
359+ except BaseException as error:
360+ # Keep the original error, backing and native events rooted. Submitted
361+ # collectives/ordinals cannot be rolled back or retried after failure.
362+ fail_stop(error, session, pending)
363+ raise
364+ 
365+ 
366+def release_batch(records):
367+ pending, fresh = _submit_releases(get_session(), records)
368+ confirm_releases(pending, fresh=fresh)
369+ 
370+ 
371+def defer_releases(records):
372+ from .plan_types import BankKey
373+ 
374+ session = get_session()
375+ pending, _ = _submit_releases(session, records)
376+ banks = session.setdefault('pending_bank_releases', {})
377+ try:
378+ for record in pending:
379+ if record.role.startswith(('fc1', 'fc2')) or session['step_plan'].get('strict_zero_copy', False):
380+ key = session['resource_capacity'].physical_key(BankKey(record.role, record.bank_index))
381+ if banks.get(key, record) is not record:
382+ raise RuntimeError('MoonEP FB already has a queued release for the bank')
383+ banks[key] = record
384+ observe_max(session, 'pending_bank_releases', len(banks))
385+ except BaseException as error:
386+ fail_stop(error, session, pending)
387+ raise
388+ return pending
389+ 
390+ 
391+def make_release_records(step_plan, key, banks, *, backward=False):
392+ slots = BACKWARD_SLOTS if backward else FORWARD_SLOTS
393+ generation = key.as_tuple()
394+ return tuple(
395+ ReleaseRecord(
396+ generation,
397+ kind,
398+ role,
399+ banks[position],
400+ get_operation_ordinal(step_plan, key, position, backward=backward, release=True),
401+ )
402+ for position, (kind, role) in enumerate(slots)
403+ )
404+ 
405+ 
406+def release_records(records, *, backward=False):
407+ order = BACKWARD_RELEASE_ORDER if backward else FORWARD_RELEASE_ORDER
408+ release_batch(tuple(records[position] for position in order if not records[position].released))
409+ 
410+ 
411+def defer_records(records, *, backward=False):
412+ order = BACKWARD_RELEASE_ORDER if backward else FORWARD_RELEASE_ORDER
413+ return defer_releases(tuple(records[position] for position in order if not records[position].released))
414+ 
415+ 
416+def validate_activation_alias(role, tensor, *, owner, generation, record):
417+ """Alias admission against the existing framework bank owner and manifest."""
418+ from .plan_types import BankKey
419+ 
420+ session = get_session()
421+ if (
422+ record is None # pylint: disable=too-many-boolean-expressions
423+ or generation is None
424+ or role not in ('Z1', 'Z2', 'Z3', 'Z4', 'R1')
425+ or record.role != role
426+ or record.generation != generation
427+ or record.released
428+ or record.kind != _KIND_BY_ROLE[role]
429+ or type(record.release_ordinal) is not int # pylint: disable=unidiomatic-typecheck
430+ ):
431+ raise ValueError('activation belongs to stale or foreign release work')
432+ steps = session['step_plan']['q0_steps']
433+ index = record.release_ordinal - session['step_plan'].get('ordinal_base', 0)
434+ if (
435+ not 0 <= index < len(steps)
436+ or steps[index] != ('release', record.kind, generation)
437+ or type(record.bank_index) is not int # pylint: disable=unidiomatic-typecheck
438+ or record.bank_index < 0
439+ ):
440+ raise ValueError('activation record differs from frozen release work')
441+ bank_key = BankKey(role, record.bank_index)
442+ if bank_key not in session['comm_buffers']:
443+ raise ValueError('activation bank is outside registered resources')
444+ bank = session['comm_buffers'][bank_key].hidden
445+ physical = session['resource_capacity'].physical_key(bank_key)
446+ if (
447+ session['bank_owners'].get(physical) != generation # pylint: disable=too-many-boolean-expressions
448+ or tensor.dtype != bank.dtype
449+ or tensor.device != bank.device
450+ or tensor.ndim != bank.ndim
451+ or not 0 < tensor.shape[0] <= bank.shape[0]
452+ or tuple(tensor.shape[1:]) != tuple(bank.shape[1:])
453+ or tuple(tensor.stride()) != tuple(bank.stride())
454+ or tensor.data_ptr() != bank.data_ptr()
455+ or tensor.storage_offset() != bank.storage_offset()
456+ ):
457+ raise ValueError('STRICT-ZC activation must alias its exact live bank')
458+ acquired = isinstance(owner, BankKey)
459+ if (acquired and owner != bank_key) or (not acquired and (owner is None or owner is not record.event)):
460+ raise ValueError('activation bank role differs from its exact owner')
461+ return bank_key
@@ -0,0 +1,15 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""MoonEP single-forward, single-backward and paired layer phases."""
@@ -0,0 +1,335 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd.
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+ 
15+"""Explicit MoonEP backward stages shared by single and paired schedules."""
16+ 
17+from types import SimpleNamespace
18+ 
19+from .. import moonep_native as native
20+from .. import session as fb_session
21+from ..modules.experts import expert_backward, run_wgrad_task
22+from ..modules import compute
23+from ..modules.utils import clear_dispatch_padding, validate_forward_stream
24+from ..schedule_plan import get_operation_ordinal
25+ 
26+ 
27+def run_prefix_backward(graph, token_grad):
28+ """Accumulate router, routed-input, shared and residual gradients exactly once."""
29+ from mindspeed.core.transformer.moe.moe_feature.fb_overlap.modules.utils import run_graph_backward
30+ 
31+ _, mlp_leaf = graph.pre_mlp_layernorm_graph
32+ # Keep the shared contribution separate until routed and router have been added.
33+ shared_dx, mlp_leaf.grad = mlp_leaf.grad, None
34+ run_graph_backward(graph.router_graph, token_grad.dp.view_as(graph.router_graph[0]), keep_graph=True)
35+ routed_dx = token_grad.dx.view_as(mlp_leaf)
36+ router_dx = mlp_leaf.grad
37+ # Combine returns a fresh token-major output; Q1 has waited for it.
38+ # Consume it in sync order. Norm backward frees this storage, so the
39+ # caller must not read token_grad.dx after this prefix.
40+ if router_dx is not None:
41+ routed_dx.add_(router_dx)
42+ if shared_dx is not None:
43+ routed_dx.add_(shared_dx)
44+ mlp_leaf.grad = routed_dx
45+ run_graph_backward(graph.pre_mlp_layernorm_graph, keep_graph=True)
46+ run_graph_backward(graph.attn_graph, keep_grad=True)
47+ 
48+ 
49+def prepare_backward_call(graph, output_grad, *, session=None):
50+ from ..modules.utils import validate_layer_cotangent
51+ 
52+ if session is None:
53+ session = fb_session.get_session()
54+ validate_forward_stream(session['q1'])
55+ if graph.checkpointed:
56+ raise ValueError('backward requires a replayed training graph')
57+ step_plan = session['step_plan']
58+ key, expert_plan = graph.key, graph.expert_plan
59+ manager, shared_weights = session['layer_resources'].get(key.layer_key, (None, ()))
60+ if (
61+ manager is None
62+ or session['layers'].get(key.layer_key) is not graph.layer
63+ or manager is not graph.layer.mlp.token_dispatcher._comm_manager
64+ ):
65+ raise ValueError('MoonEP backward received a foreign layer')
66+ graph.validate_exact(manager)
67+ validate_layer_cotangent(graph.mlp_bda_graph[0], output_grad)
68+ if expert_plan.backward_started:
69+ raise RuntimeError('duplicate exact expert backward')
70+ index = session['backward_completed']
71+ if index >= len(step_plan['backward_keys']) or key != step_plan['backward_keys'][index]:
72+ raise ValueError('backward graph differs from frozen work')
73+ expert_plan.backward_started = True
74+ banks = step_plan['backward_banks'][key]
75+ return SimpleNamespace(
76+ session=session,
77+ graph=graph,
78+ manager=manager,
79+ expert_plan=expert_plan,
80+ q1=session['q1'],
81+ generation=key.as_tuple(),
82+ banks=banks,
83+ shared_weights=shared_weights,
84+ ordinal=lambda position: get_operation_ordinal(step_plan, key, position, backward=True),
85+ records=native.make_release_records(step_plan, key, banks, backward=True),
86+ )
87+ 
88+ 
89+def run_mlp_bda_backward(call, output_grad):
90+ from mindspeed.core.transformer.moe.moe_feature.fb_overlap.modules.utils import run_graph_backward
91+ 
92+ graph = call.graph
93+ run_graph_backward(graph.mlp_bda_graph, output_grad, keep_graph=True, keep_grad=True)
94+ return graph.combine_graph[1].grad.reshape(call.session['step_plan']['input_shape'])
95+ 
96+ 
97+def submit_backward_combine(call, grad):
98+ event, expert_output_grad, _, _, _ = native.submit_dispatch(
99+ grad.contiguous(),
100+ comm_plan=call.expert_plan.provider_plan,
101+ generation=call.generation,
102+ ordinal=call.ordinal(0),
103+ activation_role='Z3',
104+ bank_index=call.banks[0],
105+ )
106+ call.records[0].event = event
107+ return SimpleNamespace(event=event, hidden=expert_output_grad)
108+ 
109+ 
110+def submit_backward_weight_prefetch(call):
111+ experts = call.manager.virtual_experts
112+ fc1_event, fc1_slots = native.submit_prefetch(
113+ call.expert_plan.provider_plan,
114+ experts.weight_refs('fc1'),
115+ projection='fc1',
116+ bank_index=call.banks[2],
117+ generation=call.generation,
118+ ordinal=call.ordinal(2),
119+ )
120+ fc2_event, fc2_slots = native.submit_prefetch(
121+ call.expert_plan.provider_plan,
122+ experts.weight_refs('fc2'),
123+ projection='fc2',
124+ bank_index=call.banks[1],
125+ generation=call.generation,
126+ ordinal=call.ordinal(1),
127+ )
128+ call.records[1].event, call.records[2].event = fc2_event, fc1_event
129+ return SimpleNamespace(fc1_event=fc1_event, fc2_event=fc2_event, slots=(fc1_slots, fc2_slots))
130+ 
131+ 
132+def submit_input_redispatch(call):
133+ # The routed source can alias the discarded norm output. Restore its
134+ # storage on Q1 before native redispatch or any shared/router backward.
135+ norm_checkpoint = getattr(call.graph, 'pre_mlp_norm_checkpoint', None)
136+ if norm_checkpoint is not None:
137+ norm_checkpoint.recompute(None)
138+ del call.graph.pre_mlp_norm_checkpoint
139+ expert_plan = call.expert_plan
140+ # Norm recompute may deliberately restore storage; retain the original
141+ # version check while reusing the PR's source pin/identity fields.
142+ if (
143+ len(expert_plan.replay_input_refs) != 1
144+ or len(expert_plan.replay_input_signatures) != 1
145+ or expert_plan.replay_input_refs[0]._version != expert_plan.replay_input_signatures[0][-1]
146+ ):
147+ raise RuntimeError('original routed input changed before redispatch')
148+ event, redispatched_input, _, _, _ = native.submit_dispatch(
149+ expert_plan.replay_input_refs[0],
150+ comm_plan=expert_plan.provider_plan,
151+ generation=call.generation,
152+ ordinal=call.ordinal(3),
153+ activation_role='R1',
154+ bank_index=call.banks[3],
155+ )
156+ call.records[3].event = event
157+ return SimpleNamespace(event=event, hidden=redispatched_input)
158+ 
159+ 
160+def run_shared_backward(call):
161+ from mindspeed.core.transformer.moe.moe_feature.fb_overlap.modules.utils import run_graph_backward
162+ 
163+ with expert_backward(call.expert_plan) as tasks:
164+ run_graph_backward(call.graph.shared_experts_graph, keep_graph=True, keep_grad=True)
165+ for task in tasks:
166+ run_wgrad_task(task)
167+ tasks.clear()
168+ 
169+ 
170+def run_routed_backward(call, expert_output_grad, weights):
171+ import torch
172+ 
173+ clear_dispatch_padding(expert_output_grad.hidden, padding_mask=call.expert_plan.padding_mask)
174+ fb_session.activation_edge(
175+ 'Z3',
176+ expert_output_grad.hidden,
177+ owner=expert_output_grad.event,
178+ generation=call.generation,
179+ record=call.records[0],
180+ )
181+ bank_key, expert_input_grad, route = native.acquire_activation(
182+ role='Z4', bank_index=call.banks[4], generation=call.generation, comm_plan=call.expert_plan.provider_plan
183+ )
184+ fb_session.activation_edge(
185+ 'Z4', expert_input_grad, owner=bank_key, generation=call.generation, record=call.records[4]
186+ )
187+ expert_input, expert_probs = call.graph.dispatch_graph[1]
188+ # Return the cotangents directly so AccumulateGrad cannot copy the Z4 bank.
189+ with expert_backward(call.expert_plan, weights=weights.slots, output=expert_input_grad) as tasks:
190+ dx, dp = torch.autograd.grad(
191+ call.graph.grouped_mlp_graph[0],
192+ (expert_input, expert_probs),
193+ grad_outputs=expert_output_grad.hidden,
194+ retain_graph=False,
195+ )
196+ if dx.data_ptr() != expert_input_grad.data_ptr():
197+ raise RuntimeError('routed dX must alias the current Z4 bank')
198+ route.copy_(dp.float())
199+ # The destination bank was admitted before backward, and dx aliasing was
200+ # checked above. route.copy_ cannot change its storage or ownership.
201+ for position in (2, 1):
202+ native.record_final_use(call.records[position], consumer_stream=call.q1)
203+ return SimpleNamespace(bank_key=bank_key, hidden=expert_input_grad, route=route), tasks
204+ 
205+ 
206+def submit_backward_dispatch(call, routed_grad):
207+ event, dx, dp = native.submit_combine(
208+ call.expert_plan.provider_plan,
209+ routed_grad.bank_key,
210+ hidden_nvsh=routed_grad.hidden,
211+ generation=call.generation,
212+ ordinal=call.ordinal(4),
213+ route_weights_nvs=routed_grad.route,
214+ backward=True,
215+ )
216+ call.records[4].event = event
217+ return SimpleNamespace(event=event, dx=dx, dp=dp)
218+ 
219+ 
220+def run_delayed_wgrad(call, expert_output_grad, redispatched_input, tasks):
221+ clear_dispatch_padding(redispatched_input.hidden, padding_mask=call.expert_plan.padding_mask)
222+ fb_session.activation_edge(
223+ 'R1',
224+ redispatched_input.hidden,
225+ owner=redispatched_input.event,
226+ generation=call.generation,
227+ record=call.records[3],
228+ )
229+ if len(tasks) != 2:
230+ raise RuntimeError('expert backward must queue exactly two local wgrad tasks')
231+ grad_bank_keys = []
232+ owners = (call, redispatched_input.hidden, expert_output_grad.hidden, tuple(tasks), grad_bank_keys)
233+ with compute.segment(call.manager.virtual_experts, *owners):
234+ for i, projection in enumerate(('fc2', 'fc1')):
235+ bank, remote = native.acquire_grad(
236+ projection=projection, bank_index=call.banks[5 + i], generation=call.generation
237+ )
238+ if hasattr(remote, 'zero_'):
239+ remote.zero_()
240+ else:
241+ for value in remote:
242+ value.zero_()
243+ run_wgrad_task(
244+ tasks[i],
245+ restored_input=redispatched_input.hidden,
246+ remote_targets=remote,
247+ scratch=call.session['wgrad_scratch'],
248+ )
249+ grad_bank_keys.append(bank)
250+ tasks.clear()
251+ for position in (0, 3):
252+ native.record_final_use(call.records[position], consumer_stream=call.q1)
253+ # Z3 still supplies FC2 dW above. Only after its Q1 final use and the
254+ # cross-rank Q0 release fence may the paired F reuse this storage as Z2.
255+ native.defer_releases((call.records[0],))
256+ if not call.session['step_plan'].get('strict_zero_copy', False):
257+ # Both dWs were submitted on Q1. Drop the private buffers without
258+ # changing R1's release ordinal or a shared bank.
259+ expert_output_grad.hidden = None
260+ redispatched_input.hidden = None
261+ return grad_bank_keys
262+ 
263+ 
264+def submit_grad_reduce(call, grad_bank_keys):
265+ experts = call.manager.virtual_experts
266+ for projection, position, bank in (('fc1', 6, grad_bank_keys[1]), ('fc2', 5, grad_bank_keys[0])):
267+ call.records[position].event = native.submit_reduce(
268+ call.expert_plan.provider_plan,
269+ experts.grad_targets(projection),
270+ projection=projection,
271+ grad_lease=bank,
272+ generation=call.generation,
273+ ordinal=call.ordinal(position),
274+ )
275+ return call.records[6], call.records[5]
276+ 
277+ 
278+def release_and_retire(call):
279+ import torch
280+ from mindspeed.core.transformer.moe.moe_feature.fb_overlap.modules.utils import run_graph_backward
281+ 
282+ native.record_final_use(call.records[4], consumer_stream=call.q1)
283+ releases = native.defer_records(call.records, backward=True)
284+ groups = tuple(
285+ tuple(p for p in params if p.requires_grad)
286+ for params in (call.shared_weights, call.manager.virtual_experts.source_parameters)
287+ )
288+ native.confirm_releases(releases)
289+ # DDP remains owned by the trainer; publish its real Parameter edges only
290+ # after local dW and native owner reductions have completed.
291+ for trainable in groups:
292+ for parameter in trainable:
293+ parameter.grad_added_to_main_grad = True
294+ if trainable:
295+ run_graph_backward(
296+ (trainable, None),
297+ tuple(torch.zeros_like(p) for p in trainable),
298+ keep_graph=True,
299+ keep_grad=True,
300+ )
301+ from mindspeed.core.transformer.moe.moonep.virtual_expert_load_balancer import _VirtualExperts
302+ 
303+ call.graph.validate_exact(call.manager)
304+ _VirtualExperts.retire(call.expert_plan)
305+ call.expert_plan.replay_input_refs = call.expert_plan.replay_input_signatures = ()
306+ call.session['backward_completed'] += 1
307+ return call.graph.layer_input.grad
308+ 
309+ 
310+def backward_moe(layer_output_grad, layer_graph):
311+ try:
312+ call = prepare_backward_call(layer_graph, layer_output_grad)
313+ grad = run_mlp_bda_backward(call, layer_output_grad)
314+ expert_output_grad = submit_backward_combine(call, grad)
315+ weights = submit_backward_weight_prefetch(call)
316+ redispatched_input = submit_input_redispatch(call)
317+ if layer_graph.shared_experts_graph is not None:
318+ run_shared_backward(call)
319+ native.wait(expert_output_grad.event, consumer_stream=call.q1)
320+ native.wait(weights.fc2_event, consumer_stream=call.q1)
321+ native.wait(weights.fc1_event, consumer_stream=call.q1)
322+ routed_grad, tasks = run_routed_backward(call, expert_output_grad, weights)
323+ token_grad = submit_backward_dispatch(call, routed_grad)
324+ native.wait(redispatched_input.event, consumer_stream=call.q1)
325+ grad_bank_keys = run_delayed_wgrad(call, expert_output_grad, redispatched_input, tasks)
326+ native.wait(token_grad.event, consumer_stream=call.q1)
327+ reductions = submit_grad_reduce(call, grad_bank_keys)
328+ run_prefix_backward(layer_graph, token_grad)
329+ for reduction in reductions:
330+ native.wait(reduction.event, consumer_stream=call.q1)
331+ native.record_final_use(reduction, consumer_stream=call.q1)
332+ return release_and_retire(call)
333+ except BaseException as error:
334+ fb_session.poison_session(error)
335+ raise