Draft
[WIP] auto overlap #3
jizeweiAdd on Sep 16
[WIP] auto overlap #3
Draft
Merged frommaster_dsv4_gt_overlap_refactorintomaster
Total: 26 files changed+7745-5
| @@ -0,0 +1,251 @@ | |||
| 1 | +# GraphTrainer NPU Auto Overlap | ||
| 2 | + | ||
| 3 | +NPU Auto Overlap 用于 TorchTitan GraphTrainer 的双 chunk MoE 通信掩盖自动调度。它在 NPU 上测量计算和通信耗时,再以依赖安全、跨 rank 一致为约束重排图,使双 chunk 的计算和通信互相掩盖。 | ||
| 4 | + | ||
| 5 | +该特性复用原生 EP overlap 的切图、process-group 隔离、结构校验和符号 shape 处理,将 `ep_overlap_schedule_pass` 的固定调度替换为基于实测 cost 的自动调度。使用时需要: | ||
| 6 | + | ||
| 7 | +1. 设置 `TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER=1`; | ||
| 8 | +2. 设置 `TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=0`; | ||
| 9 | +3. 开启 EP overlap,并选择对应的 Auto Overlap pipeline。 | ||
| 10 | + | ||
| 11 | +完整配置参考 [`deepseek_v4_flash_8p_cpt_4k_a3_auto_overlap.sh`](../../examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3_auto_overlap.sh)。 | ||
| 12 | + | ||
| 13 | +## 1. 整体流程 | ||
| 14 | + | ||
| 15 | +### 1.1 与原生 EP overlap 的关系 | ||
| 16 | + | ||
| 17 | +原生 EP overlap 将目标 MoE 区域切成两个 chunk,并以固定规则重排节点。NPU Auto Overlap 保留切图结果,等动态 shape 具体化后再根据 NPU 实测 cost 调度: | ||
| 18 | + | ||
| 19 | +```text | ||
| 20 | +原生 EP overlap | ||
| 21 | + chunk metadata -> EP chunk -> 固定调度 -> shape 具体化 -> 后续编译 | ||
| 22 | + | ||
| 23 | +NPU Auto Overlap | ||
| 24 | + chunk metadata -> EP chunk -> EP 结构校验 -> shape 具体化 -> 自动调度 -> 后续编译 | ||
| 25 | +``` | ||
| 26 | + | ||
| 27 | +启用时,pipeline 组合逻辑执行以下操作: | ||
| 28 | + | ||
| 29 | +1. 从完整的原生 GraphTrainer pipeline 开始。 | ||
| 30 | +2. 将原生 EP 调度 pass 替换为结构校验的 `ep_overlap_validate_pass`,不应用原生固定调度。 | ||
| 31 | +3. 在 EP chunk shape 具体化之后插入 NPU Auto Overlap pass。 | ||
| 32 | +4. 保持其他 pass 的内容和相对顺序不变。 | ||
| 33 | + | ||
| 34 | +如果必要的 EP pass 缺失、目标 pass 重复,或者当前正在加载预编译产物,则不改写 pipeline。 | ||
| 35 | + | ||
| 36 | +### 1.2 pass 流程 | ||
| 37 | + | ||
| 38 | +当前流程包含 1 次单算子建模和 2 轮整图校准: | ||
| 39 | + | ||
| 40 | +```text | ||
| 41 | +单计算/通信算子 benchmark | ||
| 42 | + -> 第 1 轮调度 | ||
| 43 | + -> 整图 benchmark | ||
| 44 | + -> 第 2 轮调度 | ||
| 45 | + -> 整图 benchmark | ||
| 46 | + -> 第 3 轮调度 | ||
| 47 | +``` | ||
| 48 | + | ||
| 49 | +第一次调度在原始 FX 图的 MoE 区域内逐算子 benchmark,获取初始 cost model 并执行自动调度。之后,每轮都执行上一轮排好的整图,通过 profiling 采集训练场景下通算并发时的算子耗时,校准 cost model,再次执行自动调度。 | ||
| 50 | + | ||
| 51 | +跨轮次保留三类信息: | ||
| 52 | + | ||
| 53 | +- 上一轮生成的图顺序,作为下一轮的输入; | ||
| 54 | +- 原始图节点的 canonical 顺序,作为各轮确定性排序和通信算子编号的稳定基准; | ||
| 55 | +- 最近一次可用的节点 cost,用于整图测量缺失时回退。 | ||
| 56 | + | ||
| 57 | +整图校准需要当前 traced graph、模型、batch 和训练上下文。runtime context 不可用时,只执行首次单算子 benchmark 和调度。 | ||
| 58 | + | ||
| 59 | +## 2. 单算子 Benchmark | ||
| 60 | + | ||
| 61 | +### 2.1 MoE 动态 shape 处理 | ||
| 62 | + | ||
| 63 | +原生 runtime estimator 可以从 FakeTensor metadata 为普通静态 shape 算子构造输入,但 MoE 的 routed-token 维度由当步路由结果决定,常以动态 shape 出现在 FX 图中。直接沿用原生物化逻辑通常有两种结果: | ||
| 64 | + | ||
| 65 | +- 动态维度无法物化,算子不能 benchmark; | ||
| 66 | +- 使用统一的符号 fallback 值,会使 dispatch、combine、GMM 和 permutation 的 workload 彼此不匹配。 | ||
| 67 | + | ||
| 68 | +Auto Overlap 采用负载均衡假设:保留可确定的总 token 数,并将 routed tokens 尽量均匀分配给 experts 和 EP ranks,使同一 chunk 内的通信和计算看到一致、合法的 workload。 | ||
| 69 | + | ||
| 70 | +### 2.2 计算算子 | ||
| 71 | + | ||
| 72 | +普通计算节点从 FakeTensor metadata 恢复 shape、stride、dtype、device 和非 tensor 参数,并生成相同布局的随机 tensor。只有纯函数、输入 metadata 完整且 tensor 值不决定算子合法性的节点才使用通用物化;包含 index、mask、offset 或 split 信息的整数/布尔 tensor 不会被任意随机化。 | ||
| 73 | + | ||
| 74 | +MoE 中两类动态算子使用专门输入构造: | ||
| 75 | + | ||
| 76 | +| 算子 | 合成 workload | | ||
| 77 | +| --- | --- | | ||
| 78 | +| Grouped MM | 从同 chunk 的 dispatch 推导 routed-token 总量,均匀生成每个 expert 的 token count 和累计 offset;覆盖 forward、dgrad 和 wgrad 形态 | | ||
| 79 | +| Permute / unpermute | 根据 routed-token 总量、top-k 和 expert 数构造均匀 routing;unpermute 使用匹配 NPU permute 返回语义的 inverse indices | | ||
| 80 | + | ||
| 81 | +只改变 shape、stride、view 或 alias 等 tensor metadata 的节点按零 cost 处理。无法安全物化或 benchmark 失败的计算节点也回退为零 cost,并打印告警;整图校准有机会在后续轮次补上真实测量。 | ||
| 82 | + | ||
| 83 | +计算算子通过 NPU profiler benchmark backend 多次执行并得到稳定耗时。cache key 包含算子、tensor shape/stride/dtype/device、非 tensor 参数以及动态 workload 假设,因此相同 workload 可以复用结果,不同布局或路由规模不会错误共享 cost。 | ||
| 84 | + | ||
| 85 | +### 2.3 通信算子 | ||
| 86 | + | ||
| 87 | +为每个通信 launch 找到对应 wait,并以 launch 到完成的耗时作为通信 cost。单算子通信 benchmark 优先使用 CANN profiler;当前 CANN 或 `torch_npu` 无法导出、关联 HCOM 活动时,回退到 NPU event 计时。 | ||
| 88 | + | ||
| 89 | +A2A 的输入在通信组内共同构造: | ||
| 90 | + | ||
| 91 | +1. 每个 rank 提供本地 routed-token 总量。 | ||
| 92 | +2. 通信组内交换这些总量,并将每行尽量均匀分给目标 ranks,形成兼容的 split matrix。 | ||
| 93 | +3. dispatch 使用该矩阵的本地发送行和接收列。 | ||
| 94 | +4. combine 反转与配对 dispatch 的输入、输出 splits,使其 workload 保持一致。 | ||
| 95 | + | ||
| 96 | +同一 chunk 的 dispatch token 总量也用于 GMM 和 permutation,避免各算子独立固化动态 shape 后得到互相矛盾的 workload。 | ||
| 97 | + | ||
| 98 | +CANN 路径会先按 workload 去重和查询缓存,再逐个测量缺失的通信签名。每次样本取通信组内最慢 rank,最后对多次样本取中位数,从而表示一次通信的全局完成时间。 | ||
| 99 | + | ||
| 100 | +### 2.4 单算子 cost 的跨 rank 对齐 | ||
| 101 | + | ||
| 102 | +首轮 benchmark 基于尚未调度的 MoE 区域,各 rank 具有相同的可 benchmark 节点数量和 canonical 顺序。因此计算、通信 cost 可以在每个 region 内按位置交换,并对各 rank 的值取中位数。 | ||
| 103 | + | ||
| 104 | +## 3. 整图 Benchmark | ||
| 105 | + | ||
| 106 | +### 3.1 为什么需要整图校准 | ||
| 107 | + | ||
| 108 | +单算子 benchmark 提供稳定、可启动调度的初始 cost,但它不能反映训练中算子的上下文和并发环境。 | ||
| 109 | + | ||
| 110 | +整图 benchmark 直接执行上一轮排好的 GraphTrainer 图,因而能够观察: | ||
| 111 | + | ||
| 112 | +- 计算、HCCL 通信和 copy 并发时的实际设备耗时; | ||
| 113 | +- 当前节点顺序、stream dependency 和资源竞争带来的影响; | ||
| 114 | +- 前一轮 schedule 改变后,各节点 cost 随执行上下文发生的变化。 | ||
| 115 | + | ||
| 116 | +这些 cost 不是单算子的硬件延迟,而是当前训练 schedule 中的设备侧测量,更适合用来校准下一轮调度。 | ||
| 117 | + | ||
| 118 | +### 3.2 校准执行 | ||
| 119 | + | ||
| 120 | +每轮校准复用模型和首个 batch,不额外消耗 dataloader 数据。执行前复制输入 tensor,执行后恢复模型 buffer 和 CPU/NPU RNG 状态;不修改 parameter 或 gradient。 | ||
| 121 | + | ||
| 122 | +在整图 profiling 采集前,各卡会对进行同步并 warmup ,之后再执行被测整图。 | ||
| 123 | + | ||
| 124 | +### 3.3 CANN cost 获取 | ||
| 125 | + | ||
| 126 | +整图 profiling 不向 FX 图插入逐节点 marker,而是: | ||
| 127 | + | ||
| 128 | +1. 按 FX 执行顺序匹配 CANN 中已有的 CPU dispatcher scope; | ||
| 129 | +2. 沿 `torch_to_npu` flow 找到该 scope 下发的设备任务; | ||
| 130 | +3. 计算节点保留 kernel 和 copy,过滤 host enqueue/dequeue 及设备控制事件; | ||
| 131 | +4. 通信节点使用对应 HCOM 活动的完成耗时。 | ||
| 132 | + | ||
| 133 | +### 3.4 cost 跨 rank 对齐 | ||
| 134 | + | ||
| 135 | +非均匀切分(例如切分 DeepSeekV4 的 MHC)可能使各 rank 的 FX 图存在差异,无法采用按节点位置顺序对齐。为此,每个本地节点使用不依赖本地编号的语义 key,信息包含: | ||
| 136 | + | ||
| 137 | +- 计算节点使用所在 MoE region、前向/反向、chunk、module scope、算子类型、输入/输出 tensor metadata,以及相同签名的出现次序; | ||
| 138 | +- 通信节点额外使用逻辑通信组序号、通信类型和 count/dispatch/combine 角色。 | ||
| 139 | + | ||
| 140 | +各 rank 交换“语义 key -> cost”映射。只有所有 ranks 都存在的 key 才采用本轮整图 cost,并取各 rank 的最小值;仅部分 ranks 测得的节点统一回退到上一轮,避免下一轮调度因 cost 来源不同而分叉。通信执行前还会校验每个逻辑通信组中的通信类型和数量,防止不一致的通信图进入校准执行。 | ||
| 141 | + | ||
| 142 | +## 4. 自动调度 | ||
| 143 | + | ||
| 144 | +### 4.1 调度范围与 cost model | ||
| 145 | + | ||
| 146 | +调度仅针对双 chunk MoE 区域。调度范围包括两个 chunk body,以及同一 MoE 内会影响 overlap 的共享计算,例如未归入任一 chunk 的权重转换。 | ||
| 147 | + | ||
| 148 | +当前调度模型基于以下假设: | ||
| 149 | + | ||
| 150 | +- 计算节点在一条有序计算时间线上执行; | ||
| 151 | +- MoE 区域内的 EP 通信共享一条有序通信资源; | ||
| 152 | +- 通信下发后,后续计算消耗其尚未覆盖的时间; | ||
| 153 | +- 执行 wait 时仍未覆盖的通信尾部计为暴露时间。 | ||
| 154 | + | ||
| 155 | +当前跨 rank cost 对齐和调度投票使用 WORLD,因此参与调度的图通信组必须覆盖全部 rank,多个 EP subgroup 或 PP stage 暂不支持。 | ||
| 156 | + | ||
| 157 | +模型估算的隐藏时间和暴露时间用于比较候选顺序,不等同于整图实测耗时。copy、AI Core 和 HCCL 之间更细粒度的资源竞争由整图校准间接反馈。 | ||
| 158 | + | ||
| 159 | +### 4.2 依赖与安全约束 | ||
| 160 | + | ||
| 161 | +调度前会完成以下处理: | ||
| 162 | + | ||
| 163 | +1. 收集调度区域内的通信 launch,并关联所有对应 wait。 | ||
| 164 | +2. 从完整 FX 图向调度区域投影依赖,保留“离开调度区域后又重新进入”的间接路径,避免局部合法顺序在全图形成环。 | ||
| 165 | +3. 补充动态 split-list host 协议无法由 tensor edge 完整表达的依赖。 | ||
| 166 | +4. 基于这些依赖维护可执行节点集合,并逐步生成新的 region 顺序。 | ||
| 167 | +5. 将多个调度区域的顺序约束合入全图;发生冲突时保留最大无环子集。 | ||
| 168 | +6. 完成稳定拓扑排序后,再校验通信顺序及其跨 rank 一致性。 | ||
| 169 | + | ||
| 170 | +### 4.3 Token-count D2H 优化 | ||
| 171 | + | ||
| 172 | +原始两个 chunk 各自包含一次异步 D2H 和一次同步 D2H: | ||
| 173 | + | ||
| 174 | +```text | ||
| 175 | +chunk 0: count0 -> D2H0 async -> D2H1 sync -> dispatch0 | ||
| 176 | +chunk 1: count1 -> D2H2 async -> D2H3 sync -> dispatch1 | ||
| 177 | +``` | ||
| 178 | + | ||
| 179 | +Auto Overlap 将四次 copy 按稳定顺序下发,只保留最后一次 host 同步: | ||
| 180 | + | ||
| 181 | +```text | ||
| 182 | +count0 -> count1 -> D2H0/D2H1/D2H2 async -> D2H3 sync -> dispatch0/1 | ||
| 183 | +``` | ||
| 184 | + | ||
| 185 | +为保证正确性,读取 host 数据的消费者都依赖最终同步点,而两个 dispatch 只依赖各自的 split-list 物化路径。token-count 通信不会和相邻通信交换;其 wait 进入数据通信关键路径后也会被优先完成。 | ||
| 186 | + | ||
| 187 | +### 4.4 节点选择优先级 | ||
| 188 | + | ||
| 189 | +主循环优先保持通信连续下发,同时用不会延迟下一次下发的计算填充空闲窗口。 | ||
| 190 | + | ||
| 191 | +准备下一次通信时,调度器会比较原始顺序中相邻的两个候选通信。只有在两者属于同一通信组、彼此无依赖、准备路径安全且都不是 token-count 通信时,才允许交换。 | ||
| 192 | + | ||
| 193 | +候选顺序的 score 考虑: | ||
| 194 | + | ||
| 195 | +- 下发前的准备工作是否造成通信资源空闲; | ||
| 196 | +- 第一段通信还有多少尾部无法被准备工作和可执行计算覆盖; | ||
| 197 | +- 第一段通信完成后会解锁多少后续计算; | ||
| 198 | +- 避免重复计算两个候选共同的准备工作。 | ||
| 199 | + | ||
| 200 | +只有所有 ranks 都认为交换合法、且跨 rank 平均收益为正,才接受交换,保证通信顺序相同。 | ||
| 201 | + | ||
| 202 | +确定好下个通信后,按如下优先级下发算子: | ||
| 203 | + | ||
| 204 | +| 优先级 | 场景 | 处理 | | ||
| 205 | +| ---: | --- | --- | | ||
| 206 | +| 1 | 下一个通信已可执行 | 立即下发 | | ||
| 207 | +| 2 | 通信正在执行,下一次通信下发尚未进入准备阶段 | 在预留准备预算后,用能够放入剩余窗口的独立计算填充 | | ||
| 208 | +| 3 | 下一次下发仍有可执行的非 wait 前置节点 | 按稳定顺序推进关键准备路径 | | ||
| 209 | +| 4 | token-count wait 阻塞数据通信准备 | 尽快完成 host 协议,不把它当作普通长通信窗口 | | ||
| 210 | +| 5 | 已无待下发通信,但仍有通信在执行 | 执行较大的就绪计算,覆盖剩余通信时间 | | ||
| 211 | +| 6 | 下一通个信依赖尚未完成的通信结果 | 在执行可能阻塞的 wait 前,先用就绪计算掩盖通信尾部 | | ||
| 212 | +| 7 | 没有需要优先处理的通信 | 按稳定顺序执行节点,继续推进图 | | ||
| 213 | +| 8 | 只剩 wait | 完成最早的 wait | | ||
| 214 | +| 9 | 防御性兜底 | 选择稳定顺序最早的就绪节点 | | ||
| 215 | + | ||
| 216 | +当调度器已经选择某个通信后,会持续推进它的输入准备直到下发,避免准备过程中反复改选目标。 | ||
| 217 | + | ||
| 218 | +### 4.5 跨 Rank 一致性 | ||
| 219 | + | ||
| 220 | +调度器通过以下机制避免 ranks 之间的通信顺序分叉: | ||
| 221 | + | ||
| 222 | +- 调度前比较各 rank 的通信清单,包括通信组内序号、算子类型与角色,以及所属 MoE; | ||
| 223 | +- 通信交换由所有 ranks 共同决策; | ||
| 224 | +- 多个节点在依赖和调度优先级上等价时,按首次调度前的 canonical 顺序确定先后; | ||
| 225 | +- 调度后按通信组校验最终 launch-order signature。 | ||
| 226 | + | ||
| 227 | +非均匀切分可以使计算节点和 wait 的具体位置不同,但同一通信组内的通信 launch 顺序必须一致。 | ||
| 228 | + | ||
| 229 | +## 5. 调试与实现索引 | ||
| 230 | + | ||
| 231 | +设置 `--compile.debug-graph-passes` 后,除原生 graph pass 调试信息外,auto overlap 还会: | ||
| 232 | + | ||
| 233 | +- 保留内部 CANN profiling 目录,位于 `$TMPDIR` 或系统临时目录; | ||
| 234 | +- 保存自动调度前后的可读 FX 图,位于 `./fx_graphs/` 目录; | ||
| 235 | +- 日志打印单算子本地/对齐 cost、整图应用 cost 和逐步调度决策。 | ||
| 236 | + | ||
| 237 | +相关代码: | ||
| 238 | + | ||
| 239 | +| 文件 | 作用 | | ||
| 240 | +| --- | --- | | ||
| 241 | +| `auto_overlap.py` | pipeline 注册、调度与整图校准流程编排 | | ||
| 242 | +| `npu_moe_auto_scheduler.py` | 调度区域收集、节点重排和安全校验 | | ||
| 243 | +| `compute_benchmark.py` | 计算节点输入物化与单算子 benchmark | | ||
| 244 | +| `collective_benchmark.py` | 通信输入物化、CANN benchmark 和 event fallback | | ||
| 245 | +| `whole_graph_benchmark.py` | 整图校准执行、CANN cost 获取和对齐 | | ||
| 246 | +| `utils.py` | 设置 profiling 工作目录、FX 图保存和通用方法 | | ||
| 247 | + | ||
| 248 | +## 相关文档 | ||
| 249 | + | ||
| 250 | +- 原生 EP overlap 与 NPU 适配:[`graph_trainer_ep_overlap.md`](graph_trainer_ep_overlap.md) | ||
| 251 | +- DeepSeek-V4 GraphTrainer 编译路径:[`deepseek_v4_graph_trainer.md`](deepseek_v4_graph_trainer.md) | ||
| @@ -0,0 +1,25 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +export TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER=1 | ||
| 8 | +export TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=0 | ||
| 9 | +export TORCH_NPU_USE_COMPATIBLE_IMPL=1 | ||
| 10 | + | ||
| 11 | +SEQ_LEN="${SEQ_LEN:-4096}" | ||
| 12 | +GBS="${GBS:-8}" | ||
| 13 | +STEPS="${STEPS:-20}" | ||
| 14 | + | ||
| 15 | +bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3_graphtrainer.sh \ | ||
| 16 | + --training.seq-len "${SEQ_LEN}" \ | ||
| 17 | + --training.global-batch-size "${GBS}" \ | ||
| 18 | + --training.steps "${STEPS}" \ | ||
| 19 | + --debug.moe-force-load-balance \ | ||
| 20 | + --compile.ep_overlap.enabled \ | ||
| 21 | + --compile.ep_overlap.chunk_dim seq \ | ||
| 22 | + --compile.ep_overlap.strategy graph \ | ||
| 23 | + --compile.ep_overlap.module_fqn "layers.*.moe" \ | ||
| 24 | + --compile.pass_pipeline mutation-functionalization+npu_auto_overlap \ | ||
| 25 | + "$@" | ||
| @@ -515,9 +515,12 @@ def test_ema_schema_is_inherited_by_npu_trainer_ex_config() -> None: | |||
| 515 | from torchtitan_npu.patches.torchtitan.components.checkpoint import EMACheckpointManager | 515 | from torchtitan_npu.patches.torchtitan.components.checkpoint import EMACheckpointManager |
| 516 | import torchtitan.components.checkpoint as upstream_checkpoint | 516 | import torchtitan.components.checkpoint as upstream_checkpoint |
| 517 | import torchtitan.trainer as upstream_trainer | 517 | import torchtitan.trainer as upstream_trainer |
| 518 | + from torchtitan.experiments.graph_trainer.trainer import GraphTrainer | ||
| 518 | 519 | ||
| 519 | assert upstream_trainer.Trainer is trainer_module.EMATrainer | 520 | assert upstream_trainer.Trainer is trainer_module.EMATrainer |
| 520 | assert "ema_weights" in trainer_module.EMATrainer.Config.__dataclass_fields__ | 521 | assert "ema_weights" in trainer_module.EMATrainer.Config.__dataclass_fields__ |
| 522 | + assert issubclass(GraphTrainer.Config, trainer_module.EMATrainer.Config) | ||
| 523 | + assert "ema_weights" in GraphTrainer.Config.__dataclass_fields__ | ||
| 521 | config = TrainerEx.Config() | 524 | config = TrainerEx.Config() |
| 522 | assert isinstance(config, trainer_module.EMATrainer.Config) | 525 | assert isinstance(config, trainer_module.EMATrainer.Config) |
| 523 | assert config.ema_weights.enable is False | 526 | assert config.ema_weights.enable is False |
| @@ -0,0 +1,359 @@ | |||
| 1 | +"""Tests for auto-overlap pass construction and calibration rounds.""" | ||
| 2 | + | ||
| 3 | +from functools import partial | ||
| 4 | +from types import SimpleNamespace | ||
| 5 | +from unittest.mock import Mock | ||
| 6 | + | ||
| 7 | +import pytest | ||
| 8 | +import torch | ||
| 9 | +from torchtitan.experiments.graph_trainer.registry import PASS_PIPELINE_REGISTRY | ||
| 10 | + | ||
| 11 | +import torchtitan_npu.extensions.graph_trainer as graph_trainer_extension | ||
| 12 | +from torchtitan_npu.extensions.graph_trainer import auto_overlap as graph_trainer_auto_overlap | ||
| 13 | +from torchtitan_npu.extensions.graph_trainer.utils import node_id | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def _config(*, debug_graph_passes: bool = False) -> SimpleNamespace: | ||
| 17 | + return SimpleNamespace( | ||
| 18 | + compile=SimpleNamespace( | ||
| 19 | + passes=[], | ||
| 20 | + precompile_artifact_dir="", | ||
| 21 | + debug_graph_passes=debug_graph_passes, | ||
| 22 | + ) | ||
| 23 | + ) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def _named_pass(name: str): | ||
| 27 | + def pass_fn(gm, example_inputs): | ||
| 28 | + return gm | ||
| 29 | + | ||
| 30 | + pass_fn.__name__ = name | ||
| 31 | + return pass_fn | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def test_auto_overlap_pipeline_is_registered(): | ||
| 35 | + assert PASS_PIPELINE_REGISTRY["npu_auto_overlap"] is graph_trainer_auto_overlap.construct_npu_auto_overlap_passes | ||
| 36 | + assert ( | ||
| 37 | + PASS_PIPELINE_REGISTRY["mutation-functionalization+npu_auto_overlap"] | ||
| 38 | + is graph_trainer_auto_overlap.construct_mutation_functionalization_npu_auto_overlap_passes | ||
| 39 | + ) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +@pytest.mark.parametrize( | ||
| 43 | + ("pipeline", "expected_calls"), | ||
| 44 | + [ | ||
| 45 | + ("default", 0), | ||
| 46 | + ("npu_auto_overlap", 1), | ||
| 47 | + ("mutation-functionalization+npu_auto_overlap", 1), | ||
| 48 | + ], | ||
| 49 | +) | ||
| 50 | +def test_runtime_context_patch_is_enabled_only_for_runtime_auto_overlap( | ||
| 51 | + monkeypatch, | ||
| 52 | + pipeline, | ||
| 53 | + expected_calls, | ||
| 54 | +): | ||
| 55 | + from torchtitan_npu.patches.torchtitan.experiments.graph_trainer import ( | ||
| 56 | + graph_trainer_runtime_context, | ||
| 57 | + ) | ||
| 58 | + | ||
| 59 | + apply = Mock() | ||
| 60 | + monkeypatch.setattr(graph_trainer_runtime_context, "apply", apply) | ||
| 61 | + config = _config() | ||
| 62 | + config.compile.pass_pipeline = pipeline | ||
| 63 | + | ||
| 64 | + graph_trainer_extension._apply_auto_overlap_runtime_context_patch(config) | ||
| 65 | + | ||
| 66 | + assert apply.call_count == expected_calls | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def test_npu_auto_overlap_runs_after_chunk_shape_concretization(): | ||
| 70 | + config = _config() | ||
| 71 | + passes = [ | ||
| 72 | + _named_pass("before"), | ||
| 73 | + _named_pass("joint_transformer_block_bucketing_reordering_pass"), | ||
| 74 | + _named_pass("ep_overlap_schedule_pass"), | ||
| 75 | + _named_pass("concretize_ep_chunk_symbolic_shapes_pass"), | ||
| 76 | + _named_pass("regional_inductor_pass"), | ||
| 77 | + ] | ||
| 78 | + | ||
| 79 | + configured = graph_trainer_auto_overlap._configure_npu_auto_overlap_passes( | ||
| 80 | + passes, | ||
| 81 | + config, | ||
| 82 | + ) | ||
| 83 | + | ||
| 84 | + assert [graph_trainer_auto_overlap._pass_name(pass_fn) for pass_fn in configured] == [ | ||
| 85 | + "before", | ||
| 86 | + "joint_transformer_block_bucketing_reordering_pass", | ||
| 87 | + "ep_overlap_validate_pass", | ||
| 88 | + "concretize_ep_chunk_symbolic_shapes_pass", | ||
| 89 | + "npu_moe_auto_overlap_pass", | ||
| 90 | + "regional_inductor_pass", | ||
| 91 | + ] | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def test_npu_auto_overlap_keeps_original_pipeline_without_ep_preparation(caplog): | ||
| 95 | + config = _config() | ||
| 96 | + passes = [_named_pass("before"), _named_pass("regional_inductor_pass")] | ||
| 97 | + | ||
| 98 | + configured = graph_trainer_auto_overlap._configure_npu_auto_overlap_passes( | ||
| 99 | + passes, | ||
| 100 | + config, | ||
| 101 | + ) | ||
| 102 | + | ||
| 103 | + assert configured is passes | ||
| 104 | + assert "ep_overlap_schedule_pass=0" in caplog.text | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +def test_npu_auto_overlap_keeps_original_pipeline_with_duplicate_manual_pass(caplog): | ||
| 108 | + config = _config() | ||
| 109 | + manual_pass = _named_pass("ep_overlap_schedule_pass") | ||
| 110 | + passes = [ | ||
| 111 | + manual_pass, | ||
| 112 | + manual_pass, | ||
| 113 | + _named_pass("concretize_ep_chunk_symbolic_shapes_pass"), | ||
| 114 | + _named_pass("regional_inductor_pass"), | ||
| 115 | + ] | ||
| 116 | + | ||
| 117 | + configured = graph_trainer_auto_overlap._configure_npu_auto_overlap_passes( | ||
| 118 | + passes, | ||
| 119 | + config, | ||
| 120 | + ) | ||
| 121 | + | ||
| 122 | + assert configured is passes | ||
| 123 | + assert "ep_overlap_schedule_pass=2" in caplog.text | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +def test_npu_auto_overlap_keeps_original_pipeline_without_concretize_pass(caplog): | ||
| 127 | + config = _config() | ||
| 128 | + passes = [ | ||
| 129 | + _named_pass("ep_overlap_schedule_pass"), | ||
| 130 | + _named_pass("regional_inductor_pass"), | ||
| 131 | + ] | ||
| 132 | + | ||
| 133 | + configured = graph_trainer_auto_overlap._configure_npu_auto_overlap_passes( | ||
| 134 | + passes, | ||
| 135 | + config, | ||
| 136 | + ) | ||
| 137 | + | ||
| 138 | + assert configured is passes | ||
| 139 | + assert "concretize_ep_chunk_symbolic_shapes_pass=0" in caplog.text | ||
| 140 | + | ||
| 141 | + | ||
| 142 | +def test_npu_auto_overlap_keeps_precompiled_runtime_pipeline(caplog): | ||
| 143 | + config = _config() | ||
| 144 | + config.compile.precompile_artifact_dir = "/tmp/precompiled" | ||
| 145 | + passes = [_named_pass("cudagraph_pass")] | ||
| 146 | + | ||
| 147 | + configured = graph_trainer_auto_overlap._configure_npu_auto_overlap_passes( | ||
| 148 | + passes, | ||
| 149 | + config, | ||
| 150 | + ) | ||
| 151 | + | ||
| 152 | + assert configured is passes | ||
| 153 | + assert "precompiled artifact" in caplog.text | ||
| 154 | + | ||
| 155 | + | ||
| 156 | +@pytest.mark.parametrize("debug", [False, True]) | ||
| 157 | +def test_npu_auto_overlap_writes_back_scheduler_result(monkeypatch, tmp_path, caplog, debug): | ||
| 158 | + from torchtitan_npu.extensions.graph_trainer import npu_moe_auto_scheduler | ||
| 159 | + | ||
| 160 | + class Scheduler: | ||
| 161 | + def __init__(self, candidate_gm, **_kwargs): | ||
| 162 | + self.candidate_gm = candidate_gm | ||
| 163 | + | ||
| 164 | + def run(self): | ||
| 165 | + return self.candidate_gm | ||
| 166 | + | ||
| 167 | + monkeypatch.setattr( | ||
| 168 | + npu_moe_auto_scheduler, | ||
| 169 | + "NpuMoeAutoOverlapScheduler", | ||
| 170 | + Scheduler, | ||
| 171 | + ) | ||
| 172 | + config = _config(debug_graph_passes=debug) | ||
| 173 | + config.dump_folder = str(tmp_path) | ||
| 174 | + passes = [ | ||
| 175 | + _named_pass("before"), | ||
| 176 | + _named_pass("ep_overlap_schedule_pass"), | ||
| 177 | + _named_pass("concretize_ep_chunk_symbolic_shapes_pass"), | ||
| 178 | + _named_pass("regional_inductor_pass"), | ||
| 179 | + ] | ||
| 180 | + | ||
| 181 | + configured = graph_trainer_auto_overlap._configure_npu_auto_overlap_passes( | ||
| 182 | + passes, | ||
| 183 | + config, | ||
| 184 | + ) | ||
| 185 | + | ||
| 186 | + assert [graph_trainer_auto_overlap._pass_name(pass_fn) for pass_fn in configured] == [ | ||
| 187 | + "before", | ||
| 188 | + "ep_overlap_validate_pass", | ||
| 189 | + "concretize_ep_chunk_symbolic_shapes_pass", | ||
| 190 | + "npu_moe_auto_overlap_pass", | ||
| 191 | + "regional_inductor_pass", | ||
| 192 | + ] | ||
| 193 | + graph = torch.fx.Graph() | ||
| 194 | + value = graph.placeholder("value") | ||
| 195 | + graph.output(value) | ||
| 196 | + gm = torch.fx.GraphModule({}, graph) | ||
| 197 | + monkeypatch.chdir(tmp_path) | ||
| 198 | + assert configured[3](gm, ()) is gm | ||
| 199 | + before_dump = tmp_path / "fx_graphs/auto_overlap_before_rank0.py" | ||
| 200 | + after_dump = tmp_path / "fx_graphs/auto_overlap_after_rank0.py" | ||
| 201 | + assert before_dump.is_file() is debug | ||
| 202 | + assert after_dump.is_file() is debug | ||
| 203 | + if debug: | ||
| 204 | + assert "class GraphModule" in after_dump.read_text(encoding="utf-8") | ||
| 205 | + assert "did not provide a runtime context" in caplog.text | ||
| 206 | + | ||
| 207 | + | ||
| 208 | +def test_pipeline_factory_preserves_default_preparation_and_partial_passes(monkeypatch): | ||
| 209 | + from torchtitan.experiments.graph_trainer import passes as upstream_passes | ||
| 210 | + | ||
| 211 | + traced_result, parallel_dims = object(), object() | ||
| 212 | + config = _config() | ||
| 213 | + config.compile.ep_overlap = SimpleNamespace(module_fqn="layers.*.moe") | ||
| 214 | + before = _named_pass("before") | ||
| 215 | + schedule = partial( | ||
| 216 | + _named_pass("ep_overlap_schedule_pass"), | ||
| 217 | + module_pattern="layers.*.moe", | ||
| 218 | + require_all_to_all=True, | ||
| 219 | + pair_first_token_exchange=True, | ||
| 220 | + ) | ||
| 221 | + concretize = _named_pass("concretize_ep_chunk_symbolic_shapes_pass") | ||
| 222 | + terminal = partial(_named_pass("regional_inductor_pass")) | ||
| 223 | + default_passes = [ | ||
| 224 | + before, | ||
| 225 | + schedule, | ||
| 226 | + concretize, | ||
| 227 | + terminal, | ||
| 228 | + ] | ||
| 229 | + factory = Mock(return_value=default_passes) | ||
| 230 | + monkeypatch.setattr(upstream_passes, "construct_default_graph_passes", factory) | ||
| 231 | + | ||
| 232 | + configured = graph_trainer_auto_overlap.construct_npu_auto_overlap_passes( | ||
| 233 | + traced_result, | ||
| 234 | + config, | ||
| 235 | + parallel_dims=parallel_dims, | ||
| 236 | + ) | ||
| 237 | + | ||
| 238 | + factory.assert_called_once_with(traced_result, config, parallel_dims=parallel_dims) | ||
| 239 | + assert configured[0] is before | ||
| 240 | + assert graph_trainer_auto_overlap._pass_name(configured[1]) == "ep_overlap_validate_pass" | ||
| 241 | + assert configured[1].keywords == schedule.keywords | {"require_all_to_all": False} | ||
| 242 | + assert configured[2] is concretize | ||
| 243 | + assert configured[3].func is graph_trainer_auto_overlap.npu_moe_auto_overlap_pass | ||
| 244 | + assert configured[3].keywords["config"] is config | ||
| 245 | + assert configured[3].keywords["traced_result"] is traced_result | ||
| 246 | + assert configured[3]._requires_runtime_context is True | ||
| 247 | + assert configured[4] is terminal | ||
| 248 | + assert len(default_passes) == 4 # Do not mutate the upstream pass list. | ||
| 249 | + | ||
| 250 | + | ||
| 251 | +def test_mutation_functionalization_pipeline_is_composed_before_auto_overlap( | ||
| 252 | + monkeypatch, | ||
| 253 | +): | ||
| 254 | + traced_result, parallel_dims = object(), object() | ||
| 255 | + config = _config() | ||
| 256 | + functionalize = _named_pass("functionalize_recompute_mutations_pass") | ||
| 257 | + manual = _named_pass("ep_overlap_schedule_pass") | ||
| 258 | + concretize = _named_pass("concretize_ep_chunk_symbolic_shapes_pass") | ||
| 259 | + base_passes = [functionalize, manual, concretize] | ||
| 260 | + factory = Mock(return_value=base_passes) | ||
| 261 | + monkeypatch.setitem( | ||
| 262 | + PASS_PIPELINE_REGISTRY, | ||
| 263 | + "mutation-functionalization", | ||
| 264 | + factory, | ||
| 265 | + ) | ||
| 266 | + | ||
| 267 | + configured = graph_trainer_auto_overlap.construct_mutation_functionalization_npu_auto_overlap_passes( | ||
| 268 | + traced_result, | ||
| 269 | + config, | ||
| 270 | + parallel_dims=parallel_dims, | ||
| 271 | + ) | ||
| 272 | + | ||
| 273 | + factory.assert_called_once_with( | ||
| 274 | + traced_result, | ||
| 275 | + config, | ||
| 276 | + parallel_dims=parallel_dims, | ||
| 277 | + ) | ||
| 278 | + assert [graph_trainer_auto_overlap._pass_name(pass_fn) for pass_fn in configured] == [ | ||
| 279 | + "functionalize_recompute_mutations_pass", | ||
| 280 | + "ep_overlap_validate_pass", | ||
| 281 | + "concretize_ep_chunk_symbolic_shapes_pass", | ||
| 282 | + "npu_moe_auto_overlap_pass", | ||
| 283 | + ] | ||
| 284 | + assert base_passes == [functionalize, manual, concretize] | ||
| 285 | + | ||
| 286 | + | ||
| 287 | +def test_two_whole_graph_rounds_measure_previous_schedule_and_keep_latest_fallback( | ||
| 288 | + monkeypatch, | ||
| 289 | + tmp_path, | ||
| 290 | +): | ||
| 291 | + from torchtitan_npu.extensions.graph_trainer import npu_moe_auto_scheduler as scheduler_module | ||
| 292 | + from torchtitan_npu.extensions.graph_trainer import whole_graph_benchmark as benchmark_module | ||
| 293 | + | ||
| 294 | + graph = torch.fx.Graph() | ||
| 295 | + x = graph.placeholder("x") | ||
| 296 | + compute = graph.call_function(torch.ops.aten.neg.default, (x,)) | ||
| 297 | + comm = graph.call_function(torch.ops._c10d_functional.all_reduce.default, (compute, "sum", "test_group")) | ||
| 298 | + graph.output(comm) | ||
| 299 | + gm = torch.fx.GraphModule({}, graph) | ||
| 300 | + schedulers, profiles = [], [] | ||
| 301 | + runner = Mock() | ||
| 302 | + | ||
| 303 | + class Scheduler: | ||
| 304 | + def __init__(self, candidate, **kwargs): | ||
| 305 | + assert candidate is gm | ||
| 306 | + self.kwargs = kwargs | ||
| 307 | + self.costs_by_node_id = {} | ||
| 308 | + schedulers.append(self) | ||
| 309 | + | ||
| 310 | + def run(self): | ||
| 311 | + # A real scheduler calls the cost callbacks synchronously in run(). | ||
| 312 | + self.costs_by_node_id[node_id(compute)] = ( | ||
| 313 | + self.kwargs["compute_cost_fn"](compute) if "compute_cost_fn" in self.kwargs else 10.0 | ||
| 314 | + ) | ||
| 315 | + self.costs_by_node_id[node_id(comm)] = ( | ||
| 316 | + self.kwargs["collective_cost_fn"](comm) if "collective_cost_fn" in self.kwargs else 20.0 | ||
| 317 | + ) | ||
| 318 | + gm.meta["test_schedule_generation"] = len(schedulers) | ||
| 319 | + return gm | ||
| 320 | + | ||
| 321 | + def profile(candidate, run_candidate, *, profile_node_ids, calibration_round, debug): | ||
| 322 | + assert candidate is gm | ||
| 323 | + assert run_candidate is runner | ||
| 324 | + assert candidate.meta["test_schedule_generation"] == calibration_round | ||
| 325 | + assert debug is True | ||
| 326 | + cid, aid = node_id(compute), node_id(comm) | ||
| 327 | + assert profile_node_ids == frozenset((cid, aid)) | ||
| 328 | + profiles.append(calibration_round) | ||
| 329 | + # Round 2 missing collective must reuse round 1's 3ms, not initial 20ms. | ||
| 330 | + # A measured zero is valid, not a missing mapping. | ||
| 331 | + costs = {cid: 4.0, aid: 3.0} if calibration_round == 1 else {cid: 0.0} | ||
| 332 | + return benchmark_module.WholeGraphProfileCosts(costs, costs, frozenset(costs)) | ||
| 333 | + | ||
| 334 | + monkeypatch.setattr(scheduler_module, "NpuMoeAutoOverlapScheduler", Scheduler) | ||
| 335 | + monkeypatch.setattr(benchmark_module, "profile_whole_graph_costs", profile) | ||
| 336 | + monkeypatch.setattr( | ||
| 337 | + benchmark_module, | ||
| 338 | + "make_calibration_runner", | ||
| 339 | + lambda _traced_result, _runtime_context: runner, | ||
| 340 | + ) | ||
| 341 | + config = _config(debug_graph_passes=True) | ||
| 342 | + config.dump_folder = str(tmp_path) | ||
| 343 | + monkeypatch.chdir(tmp_path) | ||
| 344 | + passes = graph_trainer_auto_overlap._configure_npu_auto_overlap_passes( | ||
| 345 | + [_named_pass("ep_overlap_schedule_pass"), _named_pass("concretize_ep_chunk_symbolic_shapes_pass")], | ||
| 346 | + config, | ||
| 347 | + ) | ||
| 348 | + result = passes[2](gm, (), runtime_context={"test": "context"}) | ||
| 349 | + assert result is gm | ||
| 350 | + assert profiles == [1, 2] | ||
| 351 | + assert len(schedulers) == 3 | ||
| 352 | + assert gm.meta["test_schedule_generation"] == 3 | ||
| 353 | + for scheduler in schedulers[1:]: | ||
| 354 | + assert scheduler.kwargs["use_profile_compute_costs"] is True | ||
| 355 | + assert scheduler.kwargs["align_across_ranks"] is False | ||
| 356 | + assert scheduler.kwargs["canonical_order_override"] is schedulers[0].kwargs["canonical_order_override"] | ||
| 357 | + assert schedulers[-1].costs_by_node_id[node_id(compute)] == 0.0 | ||
| 358 | + assert schedulers[-1].costs_by_node_id[node_id(comm)] == 3.0 | ||
| 359 | + assert (tmp_path / "fx_graphs/auto_overlap_after_rank0.py").is_file() | ||
| @@ -0,0 +1,192 @@ | |||
| 1 | +"""Tests for standalone collective benchmarks and CANN cost extraction.""" | ||
| 2 | + | ||
| 3 | +import pytest | ||
| 4 | +import torch | ||
| 5 | + | ||
| 6 | +from torchtitan_npu.extensions.graph_trainer.collective_benchmark import ( | ||
| 7 | + _a2a_splits_for_rank, | ||
| 8 | + _balanced_splits, | ||
| 9 | + _build_a2a_split_matrix, | ||
| 10 | + _CollectiveBenchmarkSpec, | ||
| 11 | + _contiguous_strides, | ||
| 12 | + _extract_hcom_durations_ms, | ||
| 13 | + benchmark_collective_with_npu_events, | ||
| 14 | + benchmark_collectives_with_cann_profiler, | ||
| 15 | +) | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +@pytest.mark.parametrize( | ||
| 19 | + ("total", "parts", "expected"), | ||
| 20 | + [ | ||
| 21 | + (0, 4, [0, 0, 0, 0]), | ||
| 22 | + (8, 4, [2, 2, 2, 2]), | ||
| 23 | + (10, 4, [3, 3, 2, 2]), | ||
| 24 | + ], | ||
| 25 | +) | ||
| 26 | +def test_balanced_splits(total, parts, expected): | ||
| 27 | + assert _balanced_splits(total, parts) == expected | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def test_a2a_split_matrix_is_valid_for_uneven_rank_inputs(): | ||
| 31 | + rows_per_rank = [8, 10, 3, 0] | ||
| 32 | + matrix = _build_a2a_split_matrix(rows_per_rank) | ||
| 33 | + | ||
| 34 | + for rank, rows in enumerate(rows_per_rank): | ||
| 35 | + input_splits, output_splits = _a2a_splits_for_rank(matrix, rank) | ||
| 36 | + assert sum(input_splits) == rows | ||
| 37 | + assert output_splits == [matrix[source][rank] for source in range(4)] | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def test_a2a_split_matrix_requires_square_matrix(): | ||
| 41 | + with pytest.raises(ValueError, match="square"): | ||
| 42 | + _a2a_splits_for_rank([[1, 2], [3]], rank=0) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +@pytest.mark.parametrize( | ||
| 46 | + ("shape", "expected"), | ||
| 47 | + [ | ||
| 48 | + ([8, 2048], [2048, 1]), | ||
| 49 | + ([2, 3, 4], [12, 4, 1]), | ||
| 50 | + ([0, 2048], [2048, 1]), | ||
| 51 | + ], | ||
| 52 | +) | ||
| 53 | +def test_contiguous_strides(shape, expected): | ||
| 54 | + assert _contiguous_strides(shape) == expected | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +def test_extract_hcom_durations_uses_longest_contained_event(): | ||
| 58 | + marker = "NPU_COMM_BENCH::0::0" | ||
| 59 | + trace = { | ||
| 60 | + "traceEvents": [ | ||
| 61 | + {"name": marker, "ph": "X", "ts": 100.0, "dur": 1000.0}, | ||
| 62 | + {"name": "hcom_alltoallv", "ph": "X", "ts": 200.0, "dur": 600.0}, | ||
| 63 | + {"name": "hcom_link", "ph": "X", "ts": 250.0, "dur": 200.0}, | ||
| 64 | + # A barrier from outside the marker must not be attributed to it. | ||
| 65 | + {"name": "hcom_allreduce", "ph": "X", "ts": 1200.0, "dur": 50.0}, | ||
| 66 | + ] | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + assert _extract_hcom_durations_ms(trace, [marker]) == {marker: 0.6} | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def test_extract_hcom_durations_associates_async_events_by_issue_order(): | ||
| 73 | + marker0 = "NPU_COMM_BENCH::0::0" | ||
| 74 | + marker1 = "NPU_COMM_BENCH::0::1" | ||
| 75 | + trace = [ | ||
| 76 | + {"name": marker0, "ph": "X", "ts": 100.0, "dur": 20.0}, | ||
| 77 | + {"name": marker1, "ph": "X", "ts": 130.0, "dur": 20.0}, | ||
| 78 | + {"name": "hcom_alltoallv_0", "ph": "X", "ts": 300.0, "dur": 10.0}, | ||
| 79 | + {"name": "hcom_alltoallv_1", "ph": "X", "ts": 320.0, "dur": 30.0}, | ||
| 80 | + ] | ||
| 81 | + | ||
| 82 | + assert _extract_hcom_durations_ms(trace, [marker0, marker1]) == { | ||
| 83 | + marker0: 0.01, | ||
| 84 | + marker1: 0.03, | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +@pytest.mark.parametrize(("total", "parts"), [(-1, 2), (1, 0)]) | ||
| 89 | +def test_balanced_splits_rejects_invalid_inputs(total, parts): | ||
| 90 | + with pytest.raises(ValueError): | ||
| 91 | + _balanced_splits(total, parts) | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def test_event_benchmark_uses_npu_a2a_materializer(monkeypatch): | ||
| 95 | + from types import SimpleNamespace | ||
| 96 | + | ||
| 97 | + from torchtitan_npu.extensions.graph_trainer import collective_benchmark | ||
| 98 | + | ||
| 99 | + node = SimpleNamespace(target=torch.ops._c10d_functional.all_to_all_single.default) | ||
| 100 | + calls = [] | ||
| 101 | + monkeypatch.setattr( | ||
| 102 | + collective_benchmark, | ||
| 103 | + "_benchmark_a2a_with_npu_events", | ||
| 104 | + lambda passed_node, nruns, **kwargs: calls.append((passed_node, nruns, kwargs)) or (2.0, "a2a-event"), | ||
| 105 | + ) | ||
| 106 | + | ||
| 107 | + result = benchmark_collective_with_npu_events( | ||
| 108 | + node, | ||
| 109 | + nruns=5, | ||
| 110 | + uniform_dispatch_rows=24576, | ||
| 111 | + reverse_uniform_splits=True, | ||
| 112 | + generic_benchmark=lambda *_args: pytest.fail("used generic benchmark"), | ||
| 113 | + ) | ||
| 114 | + | ||
| 115 | + assert result == (2.0, "a2a-event") | ||
| 116 | + assert calls == [ | ||
| 117 | + ( | ||
| 118 | + node, | ||
| 119 | + 5, | ||
| 120 | + { | ||
| 121 | + "uniform_dispatch_rows": 24576, | ||
| 122 | + "reverse_uniform_splits": True, | ||
| 123 | + }, | ||
| 124 | + ) | ||
| 125 | + ] | ||
| 126 | + | ||
| 127 | + | ||
| 128 | +def test_event_benchmark_delegates_non_a2a_collectives(): | ||
| 129 | + from types import SimpleNamespace | ||
| 130 | + | ||
| 131 | + node = SimpleNamespace(target=object()) | ||
| 132 | + calls = [] | ||
| 133 | + | ||
| 134 | + result = benchmark_collective_with_npu_events( | ||
| 135 | + node, | ||
| 136 | + nruns=3, | ||
| 137 | + generic_benchmark=lambda passed_node, nruns: calls.append((passed_node, nruns)) or (1.0, "generic-event"), | ||
| 138 | + ) | ||
| 139 | + | ||
| 140 | + assert result == (1.0, "generic-event") | ||
| 141 | + assert calls == [(node, 3)] | ||
| 142 | + | ||
| 143 | + | ||
| 144 | +def test_cann_batch_deduplicates_before_materialization(monkeypatch): | ||
| 145 | + from torch._inductor.fx_passes import node_runtime_estimation | ||
| 146 | + | ||
| 147 | + from torchtitan_npu.extensions.graph_trainer import collective_benchmark | ||
| 148 | + | ||
| 149 | + class Node: | ||
| 150 | + def __init__(self, name, signature): | ||
| 151 | + self.name = name | ||
| 152 | + self.signature = signature | ||
| 153 | + | ||
| 154 | + nodes = [Node("a0", "payload"), Node("a1", "payload"), Node("a2", "score")] | ||
| 155 | + monkeypatch.setattr(node_runtime_estimation, "can_benchmark_collective", lambda: True) | ||
| 156 | + monkeypatch.setattr(node_runtime_estimation, "get_cached_runtime", lambda _key: None) | ||
| 157 | + monkeypatch.setattr( | ||
| 158 | + collective_benchmark, | ||
| 159 | + "_collective_preliminary_key", | ||
| 160 | + lambda node, **_kwargs: (node.signature,), | ||
| 161 | + ) | ||
| 162 | + | ||
| 163 | + described = [] | ||
| 164 | + | ||
| 165 | + def describe(node, **_kwargs): | ||
| 166 | + described.append(node.name) | ||
| 167 | + return _CollectiveBenchmarkSpec( | ||
| 168 | + node=node, | ||
| 169 | + process_group="ep", | ||
| 170 | + cache_key=node.signature, | ||
| 171 | + materialize=lambda: pytest.fail("materialized before unique profiling"), | ||
| 172 | + ) | ||
| 173 | + | ||
| 174 | + monkeypatch.setattr(collective_benchmark, "_describe_collective_for_cann", describe) | ||
| 175 | + monkeypatch.setattr(torch.distributed, "get_world_size", lambda _group: 1) | ||
| 176 | + | ||
| 177 | + def all_gather(output, value, **_kwargs): | ||
| 178 | + output[0] = value | ||
| 179 | + | ||
| 180 | + monkeypatch.setattr(torch.distributed, "all_gather_object", all_gather) | ||
| 181 | + profiled = [] | ||
| 182 | + monkeypatch.setattr( | ||
| 183 | + collective_benchmark, | ||
| 184 | + "_profile_one_collective_spec", | ||
| 185 | + lambda spec, **_kwargs: profiled.append(spec.cache_key) or {"payload": 1.0, "score": 2.0}[spec.cache_key], | ||
| 186 | + ) | ||
| 187 | + | ||
| 188 | + result = benchmark_collectives_with_cann_profiler([(node, 12, False) for node in nodes]) | ||
| 189 | + | ||
| 190 | + assert described == ["a0", "a2"] | ||
| 191 | + assert profiled == ["payload", "score"] | ||
| 192 | + assert result == {nodes[0]: 1.0, nodes[1]: 1.0, nodes[2]: 2.0} | ||
| @@ -0,0 +1,406 @@ | |||
| 1 | +"""Tests for standalone compute, grouped-MM, and permutation benchmarks.""" | ||
| 2 | + | ||
| 3 | +from types import SimpleNamespace | ||
| 4 | + | ||
| 5 | +import pytest | ||
| 6 | +import torch | ||
| 7 | + | ||
| 8 | +from torchtitan_npu.extensions.graph_trainer import compute_benchmark | ||
| 9 | +from torchtitan_npu.extensions.graph_trainer.compute_benchmark import ( | ||
| 10 | + ComputeBenchmarker, | ||
| 11 | + _balanced_group_boundaries, | ||
| 12 | + _grouped_mm_benchmark_spec, | ||
| 13 | + _has_concrete_tensor_inputs, | ||
| 14 | + _is_npu_benchmark_compute_node, | ||
| 15 | + balanced_routing_indices, | ||
| 16 | + benchmark_npu_grouped_mm_node, | ||
| 17 | + benchmark_npu_permutation_node, | ||
| 18 | +) | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +def _make_binary_node(target, shape=(4, 8)): | ||
| 22 | + graph = torch.fx.Graph() | ||
| 23 | + lhs = graph.placeholder("lhs") | ||
| 24 | + rhs = graph.placeholder("rhs") | ||
| 25 | + lhs.meta["val"] = torch.empty(shape, device="meta") | ||
| 26 | + rhs.meta["val"] = torch.empty((shape[-1], shape[-1]), device="meta") | ||
| 27 | + return graph.call_function(target, (lhs, rhs)) | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def _mark_shared_expert_compute(node): | ||
| 31 | + node.meta["custom"] = { | ||
| 32 | + "EP": "compute", | ||
| 33 | + "module_fqn": "layers.1.moe.shared_experts.w1", | ||
| 34 | + } | ||
| 35 | + return node | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def test_compute_benchmarker_dispatches_supported_node_types(monkeypatch): | ||
| 39 | + do_bench = object() | ||
| 40 | + make_calls = [] | ||
| 41 | + calls = [] | ||
| 42 | + monkeypatch.setattr( | ||
| 43 | + compute_benchmark, | ||
| 44 | + "make_npu_do_bench", | ||
| 45 | + lambda: make_calls.append(True) or do_bench, | ||
| 46 | + ) | ||
| 47 | + monkeypatch.setattr( | ||
| 48 | + compute_benchmark, | ||
| 49 | + "benchmark_npu_permutation_node", | ||
| 50 | + lambda node, backend, **kwargs: calls.append(("permutation", node, backend, kwargs)), | ||
| 51 | + ) | ||
| 52 | + monkeypatch.setattr( | ||
| 53 | + compute_benchmark, | ||
| 54 | + "benchmark_npu_grouped_mm_node", | ||
| 55 | + lambda node, backend, **kwargs: calls.append(("gmm", node, backend, kwargs)), | ||
| 56 | + ) | ||
| 57 | + monkeypatch.setattr( | ||
| 58 | + compute_benchmark, | ||
| 59 | + "benchmark_npu_compute_node", | ||
| 60 | + lambda node, backend, **kwargs: calls.append(("compute", node, backend, kwargs)), | ||
| 61 | + ) | ||
| 62 | + | ||
| 63 | + permutation = SimpleNamespace(target="npu.npu_moe_token_permute.default") | ||
| 64 | + grouped_mm = SimpleNamespace(target="aten._grouped_mm.default") | ||
| 65 | + compute = SimpleNamespace(target="aten.mm.default") | ||
| 66 | + benchmarker = ComputeBenchmarker() | ||
| 67 | + | ||
| 68 | + benchmarker.benchmark(permutation, permutation_assumption=(12, 4)) | ||
| 69 | + benchmarker.benchmark(grouped_mm, assumed_tokens=12) | ||
| 70 | + benchmarker.benchmark(compute) | ||
| 71 | + | ||
| 72 | + assert len(make_calls) == 1 | ||
| 73 | + assert [kind for kind, *_ in calls] == ["permutation", "gmm", "compute"] | ||
| 74 | + assert all(call[2] is do_bench for call in calls) | ||
| 75 | + assert calls[0][3]["routed_tokens"] == 12 | ||
| 76 | + assert calls[0][3]["experts"] == 4 | ||
| 77 | + assert calls[1][3]["assumed_tokens"] == 12 | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +def test_matmul_is_npu_benchmark_compute_node(): | ||
| 81 | + node = _mark_shared_expert_compute(_make_binary_node(torch.ops.aten.matmul.default)) | ||
| 82 | + | ||
| 83 | + assert _has_concrete_tensor_inputs(node) | ||
| 84 | + assert _is_npu_benchmark_compute_node(node) | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +def test_lightweight_floating_point_target_is_selected_by_capability(): | ||
| 88 | + node = _mark_shared_expert_compute(_make_binary_node(torch.ops.aten.add.Tensor)) | ||
| 89 | + | ||
| 90 | + assert _is_npu_benchmark_compute_node(node) | ||
| 91 | + | ||
| 92 | + | ||
| 93 | +def test_unannotated_matmul_is_selected_for_standalone_benchmark(): | ||
| 94 | + node = _make_binary_node(torch.ops.aten.matmul.default) | ||
| 95 | + | ||
| 96 | + assert _is_npu_benchmark_compute_node(node) | ||
| 97 | + | ||
| 98 | + | ||
| 99 | +def test_static_activation_and_softmax_targets_are_selected(): | ||
| 100 | + targets = ( | ||
| 101 | + torch.ops.aten._log_softmax.default, | ||
| 102 | + torch.ops.aten._log_softmax_backward_data.default, | ||
| 103 | + torch.ops.aten._softmax.default, | ||
| 104 | + torch.ops.aten._softmax_backward_data.default, | ||
| 105 | + torch.ops.aten.silu.default, | ||
| 106 | + torch.ops.aten.silu_backward.default, | ||
| 107 | + ) | ||
| 108 | + | ||
| 109 | + for target in targets: | ||
| 110 | + assert _is_npu_benchmark_compute_node(_make_binary_node(target)) | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +def test_grouped_mm_balanced_boundaries_support_zero_token_experts(): | ||
| 114 | + counts, boundaries = _balanced_group_boundaries(tokens=3, experts=5) | ||
| 115 | + | ||
| 116 | + assert counts == (1, 1, 1, 0, 0) | ||
| 117 | + assert boundaries == (1, 2, 3, 3, 3) | ||
| 118 | + | ||
| 119 | + | ||
| 120 | +def test_grouped_mm_balanced_boundaries_support_empty_input(): | ||
| 121 | + counts, boundaries = _balanced_group_boundaries(tokens=0, experts=4) | ||
| 122 | + | ||
| 123 | + assert counts == (0, 0, 0, 0) | ||
| 124 | + assert boundaries == (0, 0, 0, 0) | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +def test_grouped_mm_spec_handles_forward_and_weight_gradient_shapes(): | ||
| 128 | + offsets = torch.empty((4,), dtype=torch.int64) | ||
| 129 | + forward = _grouped_mm_benchmark_spec( | ||
| 130 | + torch.empty((10, 8)), | ||
| 131 | + torch.empty((4, 8, 16)), | ||
| 132 | + offsets, | ||
| 133 | + ) | ||
| 134 | + wgrad = _grouped_mm_benchmark_spec( | ||
| 135 | + torch.empty((8, 10)), | ||
| 136 | + torch.empty((10, 16)), | ||
| 137 | + offsets, | ||
| 138 | + ) | ||
| 139 | + | ||
| 140 | + assert forward is not None and forward.tokens == 10 | ||
| 141 | + assert wgrad is not None and wgrad.tokens == 10 | ||
| 142 | + assert forward.experts == wgrad.experts == 4 | ||
| 143 | + assert forward.boundaries[-1] == wgrad.boundaries[-1] == 10 | ||
| 144 | + | ||
| 145 | + | ||
| 146 | +def test_grouped_mm_spec_uses_assumed_tokens_for_dynamic_routing_dimension(): | ||
| 147 | + offsets = torch.empty((4,), dtype=torch.int64) | ||
| 148 | + forward = _grouped_mm_benchmark_spec( | ||
| 149 | + SimpleNamespace(shape=(None, 8)), | ||
| 150 | + torch.empty((4, 8, 16)), | ||
| 151 | + offsets, | ||
| 152 | + assumed_tokens=12, | ||
| 153 | + ) | ||
| 154 | + wgrad = _grouped_mm_benchmark_spec( | ||
| 155 | + SimpleNamespace(shape=(8, None)), | ||
| 156 | + SimpleNamespace(shape=(None, 16)), | ||
| 157 | + offsets, | ||
| 158 | + assumed_tokens=12, | ||
| 159 | + ) | ||
| 160 | + | ||
| 161 | + assert forward is not None and forward.tokens == 12 | ||
| 162 | + assert wgrad is not None and wgrad.tokens == 12 | ||
| 163 | + assert forward.counts == wgrad.counts == (3, 3, 3, 3) | ||
| 164 | + | ||
| 165 | + | ||
| 166 | +def test_grouped_mm_is_selected_for_benchmark_and_uses_distribution_cache_key(): | ||
| 167 | + graph = torch.fx.Graph() | ||
| 168 | + lhs = graph.placeholder("lhs") | ||
| 169 | + rhs = graph.placeholder("rhs") | ||
| 170 | + offsets = graph.placeholder("offsets") | ||
| 171 | + lhs.meta["val"] = torch.empty((7, 8)) | ||
| 172 | + rhs.meta["val"] = torch.empty((4, 8, 16)) | ||
| 173 | + offsets.meta["val"] = torch.empty((4,), dtype=torch.int64) | ||
| 174 | + node = graph.call_function( | ||
| 175 | + torch.ops.aten._grouped_mm.default, | ||
| 176 | + (lhs, rhs, offsets), | ||
| 177 | + ) | ||
| 178 | + | ||
| 179 | + assert _is_npu_benchmark_compute_node(node) | ||
| 180 | + result = benchmark_npu_grouped_mm_node(node, lambda _callable: 1.25) | ||
| 181 | + | ||
| 182 | + assert result is not None | ||
| 183 | + elapsed_ms, key = result | ||
| 184 | + assert elapsed_ms == 1.25 | ||
| 185 | + assert "tokens=7" in key | ||
| 186 | + assert "experts=4" in key | ||
| 187 | + assert "distribution=(2, 2, 2, 1)" in key | ||
| 188 | + | ||
| 189 | + | ||
| 190 | +def test_empty_grouped_mm_returns_zero_without_backend_launch(): | ||
| 191 | + graph = torch.fx.Graph() | ||
| 192 | + lhs = graph.placeholder("lhs") | ||
| 193 | + rhs = graph.placeholder("rhs") | ||
| 194 | + offsets = graph.placeholder("offsets") | ||
| 195 | + lhs.meta["val"] = torch.empty((0, 8)) | ||
| 196 | + rhs.meta["val"] = torch.empty((4, 8, 16)) | ||
| 197 | + offsets.meta["val"] = torch.empty((4,), dtype=torch.int64) | ||
| 198 | + node = graph.call_function( | ||
| 199 | + torch.ops.aten._grouped_mm.default, | ||
| 200 | + (lhs, rhs, offsets), | ||
| 201 | + ) | ||
| 202 | + | ||
| 203 | + def should_not_run(_callable): | ||
| 204 | + raise AssertionError("zero-token GMM must not launch the backend") | ||
| 205 | + | ||
| 206 | + result = benchmark_npu_grouped_mm_node(node, should_not_run) | ||
| 207 | + | ||
| 208 | + assert result is not None and result[0] == 0.0 | ||
| 209 | + | ||
| 210 | + | ||
| 211 | +def test_grouped_mm_benchmark_accepts_offsets_keyword_argument(): | ||
| 212 | + graph = torch.fx.Graph() | ||
| 213 | + lhs = graph.placeholder("lhs") | ||
| 214 | + rhs = graph.placeholder("rhs") | ||
| 215 | + offsets = graph.placeholder("offsets") | ||
| 216 | + lhs.meta["val"] = torch.empty((9, 8)) | ||
| 217 | + rhs.meta["val"] = torch.empty((4, 8, 16)) | ||
| 218 | + offsets.meta["val"] = torch.empty((4,), dtype=torch.int64) | ||
| 219 | + node = graph.call_function( | ||
| 220 | + torch.ops.aten._grouped_mm.default, | ||
| 221 | + (lhs, rhs), | ||
| 222 | + {"offs": offsets}, | ||
| 223 | + ) | ||
| 224 | + | ||
| 225 | + result = benchmark_npu_grouped_mm_node(node, lambda _callable: 2.5) | ||
| 226 | + | ||
| 227 | + assert result is not None | ||
| 228 | + assert result[0] == 2.5 | ||
| 229 | + assert "tokens=9" in result[1] | ||
| 230 | + | ||
| 231 | + | ||
| 232 | +def test_balanced_routing_preserves_topk_and_balances_experts(): | ||
| 233 | + indices = balanced_routing_indices(11, 3, 8, device="cpu", dtype=torch.int32) | ||
| 234 | + counts = torch.bincount(indices.flatten().long(), minlength=8) | ||
| 235 | + | ||
| 236 | + assert int(counts.max() - counts.min()) <= 1 | ||
| 237 | + assert all(row.unique().numel() == 3 for row in indices) | ||
| 238 | + | ||
| 239 | + | ||
| 240 | +@pytest.mark.parametrize( | ||
| 241 | + ("mode", "dynamic"), | ||
| 242 | + [ | ||
| 243 | + ("permute", False), | ||
| 244 | + ("permute", True), | ||
| 245 | + ("unpermute", False), | ||
| 246 | + ("weighted_unpermute", False), | ||
| 247 | + ("weighted_unpermute", True), | ||
| 248 | + ("wrapper_unpermute", False), | ||
| 249 | + ("unpermute", True), | ||
| 250 | + ], | ||
| 251 | +) | ||
| 252 | +def test_permutation_benchmark_inputs_and_cache(monkeypatch, mode, dynamic): | ||
| 253 | + from torch._inductor.fx_passes import overlap_scheduling | ||
| 254 | + | ||
| 255 | + permute = mode == "permute" | ||
| 256 | + weighted = mode in {"weighted_unpermute", "wrapper_unpermute"} | ||
| 257 | + namespace = "torchtitan_npu" if mode == "wrapper_unpermute" else "npu" | ||
| 258 | + name = "npu_moe_token_permute" if permute else "npu_moe_token_unpermute" | ||
| 259 | + signature = ( | ||
| 260 | + "Tensor tokens, Tensor indices, int? num_out_tokens=None, bool padded_mode=False" | ||
| 261 | + if permute | ||
| 262 | + else "Tensor permuted_tokens, Tensor sorted_indices, Tensor? probs=None" | ||
| 263 | + ) | ||
| 264 | + captured = [] | ||
| 265 | + | ||
| 266 | + class Target: | ||
| 267 | + _schema = torch._C.parse_schema(f"{namespace}::{name}({signature}) -> Tensor") | ||
| 268 | + | ||
| 269 | + def __str__(self): | ||
| 270 | + return f"{namespace}.{name}.default" | ||
| 271 | + | ||
| 272 | + def __call__(self, *args, **kwargs): | ||
| 273 | + captured.append(args) | ||
| 274 | + | ||
| 275 | + # Model the runtime-produced inverse; verify it is passed through unchanged. | ||
| 276 | + inverse = torch.arange(12, dtype=torch.int32).flip(0) | ||
| 277 | + native_calls = [] | ||
| 278 | + | ||
| 279 | + def native_permute(tokens, routing): | ||
| 280 | + native_calls.append(routing) | ||
| 281 | + assert torch.bincount(routing.flatten().long(), minlength=4).tolist() == [3] * 4 | ||
| 282 | + return tokens, inverse | ||
| 283 | + | ||
| 284 | + monkeypatch.setattr( | ||
| 285 | + torch.ops.npu, | ||
| 286 | + "npu_moe_token_permute", | ||
| 287 | + SimpleNamespace(default=native_permute), | ||
| 288 | + raising=False, | ||
| 289 | + ) | ||
| 290 | + tokens = torch.empty_strided((6 if permute else 12, 5), (1, 12)) | ||
| 291 | + indices = ( | ||
| 292 | + torch.empty_strided((6, 2), (1, 6), dtype=torch.int32) | ||
| 293 | + if permute | ||
| 294 | + else torch.empty_strided((12,), (2,), dtype=torch.int32) | ||
| 295 | + ) | ||
| 296 | + probs = torch.empty_strided((6, 2), (1, 6)) if weighted else None | ||
| 297 | + if dynamic: | ||
| 298 | + from torch._subclasses.fake_tensor import FakeTensorMode | ||
| 299 | + from torch.fx.experimental.symbolic_shapes import ShapeEnv | ||
| 300 | + | ||
| 301 | + env = ShapeEnv() | ||
| 302 | + with FakeTensorMode(shape_env=env): | ||
| 303 | + if permute: | ||
| 304 | + source_rows = env.create_unbacked_symint() | ||
| 305 | + tokens = torch.empty_strided((source_rows, 5), (5, 1)) | ||
| 306 | + indices = torch.empty_strided( | ||
| 307 | + (source_rows, 2), | ||
| 308 | + (2, 1), | ||
| 309 | + dtype=torch.int32, | ||
| 310 | + ) | ||
| 311 | + else: | ||
| 312 | + routed_rows = env.create_unbacked_symint() | ||
| 313 | + tokens = torch.empty_strided((routed_rows, 5), (5, 1)) | ||
| 314 | + indices = torch.empty_strided( | ||
| 315 | + (routed_rows,), | ||
| 316 | + (1,), | ||
| 317 | + dtype=torch.int32, | ||
| 318 | + ) | ||
| 319 | + if weighted: | ||
| 320 | + source_rows = env.create_unbacked_symint() | ||
| 321 | + probs = torch.empty_strided( | ||
| 322 | + (source_rows, 2), | ||
| 323 | + (2, 1), | ||
| 324 | + ) | ||
| 325 | + args = (tokens, indices) if permute else (tokens, indices, probs) | ||
| 326 | + monkeypatch.setattr( | ||
| 327 | + torch._inductor.fx_utils, | ||
| 328 | + "get_fake_args_kwargs", | ||
| 329 | + lambda node: (True, args, {}), | ||
| 330 | + ) | ||
| 331 | + cache = {} | ||
| 332 | + monkeypatch.setattr(overlap_scheduling, "get_cached_node_time", cache.get) | ||
| 333 | + monkeypatch.setattr( | ||
| 334 | + overlap_scheduling, | ||
| 335 | + "set_cached_node_time", | ||
| 336 | + lambda key, value: cache.__setitem__(key, value), | ||
| 337 | + ) | ||
| 338 | + node = SimpleNamespace(op="call_function", target=Target()) | ||
| 339 | + | ||
| 340 | + def bench(fn): | ||
| 341 | + fn() | ||
| 342 | + return 0.125 | ||
| 343 | + | ||
| 344 | + result = benchmark_npu_permutation_node( | ||
| 345 | + node, | ||
| 346 | + bench, | ||
| 347 | + routed_tokens=12, | ||
| 348 | + experts=4, | ||
| 349 | + ) | ||
| 350 | + assert result[0] == 0.125 | ||
| 351 | + assert ( | ||
| 352 | + benchmark_npu_permutation_node( | ||
| 353 | + node, | ||
| 354 | + bench, | ||
| 355 | + routed_tokens=12, | ||
| 356 | + experts=4, | ||
| 357 | + ) | ||
| 358 | + == result | ||
| 359 | + ) | ||
| 360 | + assert len(captured) == 1 | ||
| 361 | + actual = captured[0] | ||
| 362 | + expected_token_shape = (6, 5) if dynamic and permute else ((12, 5) if dynamic else tokens.shape) | ||
| 363 | + assert actual[0].shape == expected_token_shape | ||
| 364 | + assert actual[0].stride() == tokens.stride() | ||
| 365 | + assert actual[1].stride() == indices.stride() | ||
| 366 | + assert actual[1].dtype == indices.dtype | ||
| 367 | + if permute: | ||
| 368 | + assert not native_calls | ||
| 369 | + assert torch.bincount(actual[1].flatten().long()).tolist() == [3] * 4 | ||
| 370 | + else: | ||
| 371 | + assert len(native_calls) == 1 | ||
| 372 | + assert torch.equal(actual[1], inverse) | ||
| 373 | + if weighted: | ||
| 374 | + assert actual[2].stride() == probs.stride() | ||
| 375 | + torch.testing.assert_close(actual[2].sum(-1), torch.ones(6)) | ||
| 376 | + | ||
| 377 | + | ||
| 378 | +def test_permute_dropped_tokens_is_not_silently_benchmarked(monkeypatch): | ||
| 379 | + class Target: | ||
| 380 | + _schema = torch._C.parse_schema( | ||
| 381 | + "npu::npu_moe_token_permute(Tensor tokens, Tensor indices, int? num_out_tokens=None) -> Tensor" | ||
| 382 | + ) | ||
| 383 | + | ||
| 384 | + def __str__(self): | ||
| 385 | + return "npu.npu_moe_token_permute.default" | ||
| 386 | + | ||
| 387 | + def __call__(self, *args, **kwargs): | ||
| 388 | + pytest.fail("unexpected permutation call") | ||
| 389 | + | ||
| 390 | + monkeypatch.setattr( | ||
| 391 | + torch._inductor.fx_utils, | ||
| 392 | + "get_fake_args_kwargs", | ||
| 393 | + lambda node: ( | ||
| 394 | + True, | ||
| 395 | + (torch.empty(6, 5), torch.empty(6, 2, dtype=torch.int32), 5), | ||
| 396 | + {}, | ||
| 397 | + ), | ||
| 398 | + ) | ||
| 399 | + result = benchmark_npu_permutation_node( | ||
| 400 | + SimpleNamespace(op="call_function", target=Target()), | ||
| 401 | + lambda fn: pytest.fail("unexpected benchmark"), | ||
| 402 | + routed_tokens=12, | ||
| 403 | + experts=4, | ||
| 404 | + ) | ||
| 405 | + | ||
| 406 | + assert result is None | ||
| @@ -0,0 +1,123 @@ | |||
| 1 | +"""Tests for graph metadata and profiling/debug utilities.""" | ||
| 2 | + | ||
| 3 | +import os | ||
| 4 | +from pathlib import Path | ||
| 5 | + | ||
| 6 | +import pytest | ||
| 7 | +import torch | ||
| 8 | + | ||
| 9 | +from torchtitan_npu.extensions.graph_trainer.utils import ( | ||
| 10 | + assign_stable_node_tags, | ||
| 11 | + canonical_order, | ||
| 12 | + dump_fx_graph, | ||
| 13 | + is_metadata_only_compute_node, | ||
| 14 | + isolated_cann_profiler_work_path, | ||
| 15 | + node_id, | ||
| 16 | +) | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def test_stable_node_ids_preserve_custom_metadata_and_original_order(): | ||
| 20 | + graph = torch.fx.Graph() | ||
| 21 | + x = graph.placeholder("x") | ||
| 22 | + x.meta["custom"] = {"module_fqn": "layers.0"} | ||
| 23 | + neg = graph.call_function(torch.ops.aten.neg.default, (x,)) | ||
| 24 | + graph.output(neg) | ||
| 25 | + gm = torch.fx.GraphModule({}, graph) | ||
| 26 | + | ||
| 27 | + assign_stable_node_tags(gm) | ||
| 28 | + | ||
| 29 | + assert x.meta["custom"]["module_fqn"] == "layers.0" | ||
| 30 | + assert [node_id(node) for node in gm.graph.nodes] == [0, 1, 2] | ||
| 31 | + assert canonical_order(gm) == {node: ordinal for ordinal, node in enumerate(gm.graph.nodes)} | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def test_stable_node_ids_survive_reordering_and_repeated_assignment(): | ||
| 35 | + graph = torch.fx.Graph() | ||
| 36 | + x = graph.placeholder("x") | ||
| 37 | + first = graph.call_function(torch.ops.aten.neg.default, (x,)) | ||
| 38 | + second = graph.call_function(torch.ops.aten.relu.default, (x,)) | ||
| 39 | + output = graph.output((first, second)) | ||
| 40 | + gm = torch.fx.GraphModule({}, graph) | ||
| 41 | + assign_stable_node_tags(gm) | ||
| 42 | + | ||
| 43 | + first.prepend(second) | ||
| 44 | + assign_stable_node_tags(gm) | ||
| 45 | + | ||
| 46 | + assert list(gm.graph.nodes) == [x, second, first, output] | ||
| 47 | + assert [node_id(node) for node in gm.graph.nodes] == [0, 2, 1, 3] | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def test_canonical_order_rejects_untagged_graph(): | ||
| 51 | + graph = torch.fx.Graph() | ||
| 52 | + x = graph.placeholder("x") | ||
| 53 | + graph.output(x) | ||
| 54 | + gm = torch.fx.GraphModule({}, graph) | ||
| 55 | + | ||
| 56 | + with pytest.raises(RuntimeError, match="has no auto-overlap node ID"): | ||
| 57 | + canonical_order(gm) | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +@pytest.mark.parametrize("requires_copy", [False, True]) | ||
| 61 | +def test_reshape_is_metadata_only_only_when_storage_is_shared(requires_copy): | ||
| 62 | + graph = torch.fx.Graph() | ||
| 63 | + x = graph.placeholder("x") | ||
| 64 | + value = torch.empty((2, 3)) | ||
| 65 | + if requires_copy: | ||
| 66 | + value = value.t() | ||
| 67 | + x.meta["val"] = value | ||
| 68 | + reshape = graph.call_function(torch.ops.aten.reshape.default, (x, (6,))) | ||
| 69 | + reshape.meta["val"] = value.reshape(6) | ||
| 70 | + | ||
| 71 | + assert is_metadata_only_compute_node(reshape) is not requires_copy | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +@pytest.mark.parametrize("retain", [False, True]) | ||
| 75 | +@pytest.mark.parametrize("original", [None, "training/profiling"]) | ||
| 76 | +@pytest.mark.parametrize("fail", [False, True]) | ||
| 77 | +def test_profile_directory_retention_and_environment_restore(monkeypatch, tmp_path, caplog, retain, original, fail): | ||
| 78 | + monkeypatch.setenv("RANK", "3") | ||
| 79 | + monkeypatch.setattr("tempfile.tempdir", str(tmp_path)) | ||
| 80 | + if original is None: | ||
| 81 | + monkeypatch.delenv("ASCEND_WORK_PATH", raising=False) | ||
| 82 | + else: | ||
| 83 | + monkeypatch.setenv("ASCEND_WORK_PATH", original) | ||
| 84 | + caplog.set_level("INFO") | ||
| 85 | + | ||
| 86 | + def collect(): | ||
| 87 | + nonlocal work_path | ||
| 88 | + with isolated_cann_profiler_work_path("test_cann_profile_", retain=retain) as work_path: | ||
| 89 | + assert work_path.is_absolute() | ||
| 90 | + assert Path(os.environ["ASCEND_WORK_PATH"]) == work_path | ||
| 91 | + (work_path / "raw_data").mkdir() | ||
| 92 | + (work_path / "trace.json").write_text("{}", encoding="utf-8") | ||
| 93 | + if fail: | ||
| 94 | + raise RuntimeError("parse failed") | ||
| 95 | + | ||
| 96 | + work_path = None | ||
| 97 | + if fail: | ||
| 98 | + with pytest.raises(RuntimeError, match="parse failed"): | ||
| 99 | + collect() | ||
| 100 | + else: | ||
| 101 | + collect() | ||
| 102 | + assert os.environ.get("ASCEND_WORK_PATH") == original | ||
| 103 | + assert work_path.exists() is retain | ||
| 104 | + if retain: | ||
| 105 | + assert (work_path / "trace.json").read_text(encoding="utf-8") == "{}" | ||
| 106 | + assert (work_path / "raw_data").is_dir() | ||
| 107 | + assert "rank3_pid" in work_path.name | ||
| 108 | + assert str(work_path) in caplog.text | ||
| 109 | + assert "profiling retained" in caplog.text | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +def test_dump_fx_graph_is_self_contained(monkeypatch, tmp_path): | ||
| 113 | + graph = torch.fx.Graph() | ||
| 114 | + x = graph.placeholder("x") | ||
| 115 | + graph.output(x) | ||
| 116 | + gm = torch.fx.GraphModule({}, graph) | ||
| 117 | + monkeypatch.chdir(tmp_path) | ||
| 118 | + | ||
| 119 | + output = dump_fx_graph(gm, prefix="auto_overlap_before") | ||
| 120 | + | ||
| 121 | + assert output == tmp_path / "fx_graphs/auto_overlap_before_rank0.py" | ||
| 122 | + assert output.is_file() | ||
| 123 | + assert "def forward" in output.read_text(encoding="utf-8") | ||
| @@ -0,0 +1,645 @@ | |||
| 1 | +"""Tests for whole-graph profiling, cost extraction, and rank alignment.""" | ||
| 2 | + | ||
| 3 | +import operator | ||
| 4 | +from contextlib import contextmanager, nullcontext | ||
| 5 | +from dataclasses import dataclass | ||
| 6 | +from types import SimpleNamespace | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | + | ||
| 11 | +from torchtitan_npu.extensions.graph_trainer import whole_graph_benchmark as benchmark_module | ||
| 12 | +from torchtitan_npu.extensions.graph_trainer.utils import ( | ||
| 13 | + assign_stable_node_tags, | ||
| 14 | + node_id, | ||
| 15 | +) | ||
| 16 | +from torchtitan_npu.extensions.graph_trainer.whole_graph_benchmark import ( | ||
| 17 | + _align_costs, | ||
| 18 | + _collective_count_manifest, | ||
| 19 | + _cross_rank_semantic_keys, | ||
| 20 | + _extract_cann_node_costs, | ||
| 21 | + _host_op_names, | ||
| 22 | + _is_host_only_scalar_node, | ||
| 23 | + _is_non_collective_device_work, | ||
| 24 | + _match_fx_nodes_to_host_scopes, | ||
| 25 | + make_calibration_runner, | ||
| 26 | +) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +@pytest.mark.parametrize( | ||
| 30 | + ("event", "expected"), | ||
| 31 | + [ | ||
| 32 | + ({"name": "aclnnMul", "args": {"Task Type": "AI_VECTOR_CORE"}}, True), | ||
| 33 | + ({"name": "KERNEL_MIX_AIC", "args": {"Task Type": "MIX_AIC"}}, True), | ||
| 34 | + ({"name": "MEMCPY_ASYNC", "args": {"Task Type": "MEMCPY_ASYNC"}}, True), | ||
| 35 | + ({"name": "SDMA_SQE", "args": {"Task Type": "SDMA_SQE"}}, True), | ||
| 36 | + ({"name": "future_kernel", "args": {"Task Type": "NEW_CORE"}}, True), | ||
| 37 | + ({"name": "EVENT_WAIT", "args": {"Task Type": "EVENT_WAIT"}}, False), | ||
| 38 | + ({"name": "notify", "args": {"Task Type": "NOTIFY_WAIT_SQE"}}, False), | ||
| 39 | + ({"name": "WRITE_VALUE_SQE", "args": {}}, False), | ||
| 40 | + ({"name": "hcom_alltoallv", "args": {}}, False), | ||
| 41 | + ({"name": "task", "args": {"Task Type": "COMMUNICATION"}}, False), | ||
| 42 | + ], | ||
| 43 | +) | ||
| 44 | +def test_non_collective_device_work_filters_only_control_tasks(event, expected): | ||
| 45 | + assert _is_non_collective_device_work(event) is expected | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +def test_local_scalar_from_cpu_tensor_is_host_only(): | ||
| 49 | + graph = torch.fx.Graph() | ||
| 50 | + value = graph.placeholder("value") | ||
| 51 | + value.meta["val"] = torch.empty((), device="cpu") | ||
| 52 | + scalar = graph.call_function(torch.ops.aten._local_scalar_dense.default, (value,)) | ||
| 53 | + | ||
| 54 | + assert _is_host_only_scalar_node(scalar) | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +def test_local_scalar_from_non_cpu_tensor_is_not_host_only(): | ||
| 58 | + graph = torch.fx.Graph() | ||
| 59 | + value = graph.placeholder("value") | ||
| 60 | + value.meta["val"] = torch.empty((), device="meta") | ||
| 61 | + scalar = graph.call_function(torch.ops.aten._local_scalar_dense.default, (value,)) | ||
| 62 | + | ||
| 63 | + assert not _is_host_only_scalar_node(scalar) | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +def test_candidate_runner_clones_inputs_and_restores_mutated_buffers(monkeypatch): | ||
| 67 | + class Model(torch.nn.Module): | ||
| 68 | + def __init__(self): | ||
| 69 | + super().__init__() | ||
| 70 | + self.weight = torch.nn.Parameter(torch.tensor(2.0)) | ||
| 71 | + self.register_buffer("running", torch.tensor(3.0)) | ||
| 72 | + | ||
| 73 | + @dataclass | ||
| 74 | + class TracedResult: | ||
| 75 | + gm: object | ||
| 76 | + | ||
| 77 | + model = Model() | ||
| 78 | + original_gm, candidate_gm = object(), object() | ||
| 79 | + traced_result = TracedResult(original_gm) | ||
| 80 | + training_input = torch.tensor([1.0]) | ||
| 81 | + seen = {} | ||
| 82 | + | ||
| 83 | + def fake_run_traced(candidate, *, module): | ||
| 84 | + assert candidate.gm is candidate_gm | ||
| 85 | + assert module is model | ||
| 86 | + | ||
| 87 | + def execute(value): | ||
| 88 | + seen["value"] = value | ||
| 89 | + value.add_(10) | ||
| 90 | + model.running.add_(4) | ||
| 91 | + return value * model.weight | ||
| 92 | + | ||
| 93 | + return execute | ||
| 94 | + | ||
| 95 | + monkeypatch.setattr(benchmark_module, "run_traced", fake_run_traced) | ||
| 96 | + runner = make_calibration_runner( | ||
| 97 | + None, | ||
| 98 | + { | ||
| 99 | + "module": model, | ||
| 100 | + "traced_result": traced_result, | ||
Atests/unit_tests/patches/torchtitan/experiments/graph_trainer/test_ep_forward_accumulation.py+132-0
| @@ -0,0 +1,132 @@ | |||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 2 | +# All rights reserved. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +"""Tests for EP chunk materialization of functionalized accumulations.""" | ||
| 8 | + | ||
| 9 | +from unittest.mock import Mock | ||
| 10 | + | ||
| 11 | +import pytest | ||
| 12 | +import torch | ||
| 13 | +from torch.utils.checkpoint import CheckpointPolicy | ||
| 14 | +from torchtitan.experiments.graph_trainer.common_utils import _MODULE_FQN | ||
| 15 | +from torchtitan.experiments.graph_trainer.ep_chunk_pass import apply_chunk_pass | ||
| 16 | + | ||
| 17 | +# Tests exercise the patched EP chunk implementation directly. | ||
| 18 | +from torchtitan_npu.patches.torchtitan.experiments.graph_trainer import ( | ||
| 19 | + ep_forward_accumulation, | ||
| 20 | +) | ||
| 21 | + | ||
| 22 | +ep_forward_accumulation.apply() | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def test_mutation_functionalization_pipeline_enables_accumulation_patch(monkeypatch): | ||
| 26 | + from torchtitan_npu.patches.torchtitan.experiments.graph_trainer import ( | ||
| 27 | + functionalize_recompute_mutations, | ||
| 28 | + ) | ||
| 29 | + | ||
| 30 | + apply = Mock() | ||
| 31 | + monkeypatch.setattr(ep_forward_accumulation, "apply", apply) | ||
| 32 | + monkeypatch.setattr( | ||
| 33 | + functionalize_recompute_mutations, | ||
| 34 | + "construct_default_graph_passes", | ||
| 35 | + Mock(return_value=[]), | ||
| 36 | + ) | ||
| 37 | + | ||
| 38 | + functionalize_recompute_mutations._mutation_functionalization_pipeline( | ||
| 39 | + object(), | ||
| 40 | + object(), | ||
| 41 | + ) | ||
| 42 | + | ||
| 43 | + apply.assert_called_once_with() | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _symbolic_batch_fake_mode(batch: int = 4): | ||
| 47 | + from torch.fx.experimental.symbolic_shapes import ShapeEnv | ||
| 48 | + | ||
| 49 | + shape_env = ShapeEnv() | ||
| 50 | + fake_mode = torch._subclasses.FakeTensorMode( | ||
| 51 | + allow_non_fake_inputs=True, | ||
| 52 | + shape_env=shape_env, | ||
| 53 | + ) | ||
| 54 | + with fake_mode: | ||
| 55 | + sym_batch = shape_env.create_unbacked_symint() | ||
| 56 | + torch._dynamo.override_optimization_hint(sym_batch, batch) | ||
| 57 | + return fake_mode, sym_batch | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def _functionalized_buffer_update_graph() -> torch.fx.GraphModule: | ||
| 61 | + graph = torch.fx.Graph() | ||
| 62 | + buffer = graph.placeholder("buffer") | ||
| 63 | + x = graph.placeholder("x") | ||
| 64 | + output = graph.call_function(torch.ops.aten.relu.default, args=(x,)) | ||
| 65 | + delta = graph.call_function(torch.ops.aten.sum.dim_IntList, args=(x, [0])) | ||
| 66 | + updated = graph.call_function(torch.ops.aten.add.Tensor, args=(buffer, delta)) | ||
| 67 | + graph.call_function(torch.ops.aten.copy_.default, args=(buffer, updated)) | ||
| 68 | + graph.output(output) | ||
| 69 | + gm = torch.fx.GraphModule(torch.nn.Module(), graph) | ||
| 70 | + | ||
| 71 | + fake_mode, sym_batch = _symbolic_batch_fake_mode() | ||
| 72 | + with fake_mode: | ||
| 73 | + x_val = torch.empty(sym_batch, 3) | ||
| 74 | + buffer_val = torch.empty(3) | ||
| 75 | + | ||
| 76 | + buffer.meta["val"] = buffer_val | ||
| 77 | + x.meta["val"] = x_val | ||
| 78 | + output.meta["val"] = x_val | ||
| 79 | + for node in (output, delta, updated): | ||
| 80 | + node.meta["custom"] = {_MODULE_FQN: "layers.0.moe"} | ||
| 81 | + node.meta["recompute"] = CheckpointPolicy.PREFER_RECOMPUTE | ||
| 82 | + delta.meta["val"] = buffer_val | ||
| 83 | + updated.meta["val"] = buffer_val | ||
| 84 | + return gm | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +def test_chunk_materializes_functionalized_buffer_accumulation_once(): | ||
| 88 | + gm = _functionalized_buffer_update_graph() | ||
| 89 | + apply_chunk_pass( | ||
| 90 | + gm, | ||
| 91 | + mode="batch", | ||
| 92 | + module_patterns=["layers.*.moe"], | ||
| 93 | + num_static_inputs=1, | ||
| 94 | + ) | ||
| 95 | + gm.graph.lint() | ||
| 96 | + | ||
| 97 | + materializations = [ | ||
| 98 | + node | ||
| 99 | + for node in gm.graph.nodes | ||
| 100 | + if node.meta.get("chunked_materialization_proof") == "forward_functionalized_buffer_accumulation" | ||
| 101 | + ] | ||
| 102 | + assert len(materializations) == 1 | ||
| 103 | + | ||
| 104 | + x = torch.arange(12.0).reshape(4, 3) | ||
| 105 | + initial = torch.tensor([10.0, 20.0, 30.0]) | ||
| 106 | + buffer = initial.clone() | ||
| 107 | + output = gm(buffer, x) | ||
| 108 | + | ||
| 109 | + torch.testing.assert_close(output, torch.relu(x)) | ||
| 110 | + torch.testing.assert_close(buffer, initial + x.sum(dim=0)) | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +def test_chunk_still_rejects_unproven_forward_live_out(): | ||
| 114 | + graph = torch.fx.Graph() | ||
| 115 | + x = graph.placeholder("x") | ||
| 116 | + relu = graph.call_function(torch.ops.aten.relu.default, args=(x,)) | ||
| 117 | + reduced = graph.call_function(torch.ops.aten.amax.default, args=(relu, [0], False)) | ||
| 118 | + graph.output((relu, reduced)) | ||
| 119 | + gm = torch.fx.GraphModule(torch.nn.Module(), graph) | ||
| 120 | + | ||
| 121 | + fake_mode, sym_batch = _symbolic_batch_fake_mode() | ||
| 122 | + with fake_mode: | ||
| 123 | + x_val = torch.empty(sym_batch, 3) | ||
| 124 | + reduced_val = torch.empty(3) | ||
| 125 | + x.meta["val"] = x_val | ||
| 126 | + relu.meta["val"] = x_val | ||
| 127 | + reduced.meta["val"] = reduced_val | ||
| 128 | + for node in (relu, reduced): | ||
| 129 | + node.meta["custom"] = {_MODULE_FQN: "layers.0.moe"} | ||
| 130 | + | ||
| 131 | + with pytest.raises(ValueError, match="forward accumulation proof"): | ||
| 132 | + apply_chunk_pass(gm, mode="batch", module_patterns=["layers.*.moe"]) | ||
Atests/unit_tests/patches/torchtitan/experiments/graph_trainer/test_graph_trainer_runtime_context.py+73-0
| @@ -0,0 +1,73 @@ | |||
| 1 | +"""Tests for the GraphTrainer runtime-context compatibility patch.""" | ||
| 2 | + | ||
| 3 | +from types import SimpleNamespace | ||
| 4 | + | ||
| 5 | +import torch | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +def test_runtime_context_is_bound_to_opted_in_pass_during_tracing(monkeypatch): | ||
| 9 | + from torchtitan_npu.patches.torchtitan.experiments.graph_trainer import ( | ||
| 10 | + graph_trainer_runtime_context as trainer_patch, | ||
| 11 | + ) | ||
| 12 | + | ||
| 13 | + graph = torch.fx.Graph() | ||
| 14 | + x = graph.placeholder("x") | ||
| 15 | + graph.output(x) | ||
| 16 | + gm = torch.fx.GraphModule({}, graph) | ||
| 17 | + traced_result = SimpleNamespace(gm=gm) | ||
| 18 | + model = object() | ||
| 19 | + inputs, labels, tokens = object(), object(), object() | ||
| 20 | + extra_kwargs = {"metadata": object()} | ||
| 21 | + train_context = object() | ||
| 22 | + instance = SimpleNamespace( | ||
| 23 | + _traced_step=traced_result, | ||
| 24 | + train_context=train_context, | ||
| 25 | + ) | ||
| 26 | + seen = [] | ||
| 27 | + | ||
| 28 | + def fake_original(self, *args): | ||
| 29 | + def ordinary(candidate, example_inputs): | ||
| 30 | + seen.append(("ordinary", example_inputs)) | ||
| 31 | + return candidate | ||
| 32 | + | ||
| 33 | + def runtime_aware(candidate, example_inputs, *, runtime_context=None): | ||
| 34 | + seen.append(("runtime", example_inputs, runtime_context)) | ||
| 35 | + return candidate | ||
| 36 | + | ||
| 37 | + runtime_aware._requires_runtime_context = True | ||
| 38 | + trainer_patch.patched_apply_graph_passes( | ||
| 39 | + gm, | ||
| 40 | + (), | ||
| 41 | + [ordinary, runtime_aware], | ||
| 42 | + ) | ||
| 43 | + return "result" | ||
| 44 | + | ||
| 45 | + monkeypatch.setattr( | ||
| 46 | + trainer_patch, | ||
| 47 | + "original_make_fx_forward_backward_step", | ||
| 48 | + fake_original, | ||
| 49 | + ) | ||
| 50 | + result = trainer_patch.patched_make_fx_forward_backward_step( | ||
| 51 | + instance, | ||
| 52 | + model, | ||
| 53 | + inputs, | ||
| 54 | + labels, | ||
| 55 | + tokens, | ||
| 56 | + [], | ||
| 57 | + extra_kwargs, | ||
| 58 | + ) | ||
| 59 | + | ||
| 60 | + assert result == "result" | ||
| 61 | + assert seen == [ | ||
| 62 | + ("ordinary", []), | ||
| 63 | + ( | ||
| 64 | + "runtime", | ||
| 65 | + [], | ||
| 66 | + { | ||
| 67 | + "traced_result": traced_result, | ||
| 68 | + "module": model, | ||
| 69 | + "args": (inputs, labels, tokens, extra_kwargs), | ||
| 70 | + "train_context": train_context, | ||
| 71 | + }, | ||
| 72 | + ), | ||
| 73 | + ] | ||
Rtests/unit_tests/patches/torchtitan/graph_trainer/test_rope_recompute_integration.py→tests/unit_tests/patches/torchtitan/experiments/graph_trainer/test_rope_recompute_integration.py+0-0
File renamed without changes.
Rtorchtitan_npu/extensions/graph_trainer.py→torchtitan_npu/extensions/graph_trainer/__init__.py+18-2
| @@ -15,8 +15,19 @@ from torchtitan_npu.config.configs import OptimizerConfig, TrainingConfig | |||
| 15 | from torchtitan_npu.config.converters import TrainerConfigConverter | 15 | from torchtitan_npu.config.converters import TrainerConfigConverter |
| 16 | from torchtitan_npu.extensions.components.checkpoint import CheckpointManager | 16 | from torchtitan_npu.extensions.components.checkpoint import CheckpointManager |
| 17 | 17 | ||
| 18 | -from .profiler import CANNProfiler | 18 | +from ..profiler import CANNProfiler |
| 19 | -from .trainer import TrainerEx | 19 | +from ..trainer import TrainerEx |
| 20 | +from . import auto_overlap | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def _apply_auto_overlap_runtime_context_patch(config) -> None: | ||
| 24 | + if not auto_overlap.is_npu_auto_overlap_pipeline(config.compile.pass_pipeline): | ||
| 25 | + return | ||
| 26 | + from torchtitan_npu.patches.torchtitan.experiments.graph_trainer import ( | ||
| 27 | + graph_trainer_runtime_context, | ||
| 28 | + ) | ||
| 29 | + | ||
| 30 | + graph_trainer_runtime_context.apply() | ||
| 20 | 31 | ||
| 21 | 32 | ||
| 22 | class GraphTrainerEx(TrainerEx, GraphTrainer): | 33 | class GraphTrainerEx(TrainerEx, GraphTrainer): |
| @@ -28,6 +39,11 @@ class GraphTrainerEx(TrainerEx, GraphTrainer): | |||
| 28 | default_factory=GraphTrainerCompileConfig, | 39 | default_factory=GraphTrainerCompileConfig, |
| 29 | ) | 40 | ) |
| 30 | 41 | ||
| 42 | + def __init__(self, config: Config) -> None: | ||
| 43 | + # This patch must wrap GraphTrainer before its first trace. | ||
| 44 | + _apply_auto_overlap_runtime_context_patch(config) | ||
| 45 | + super().__init__(config) | ||
| 46 | + | ||
| 31 | 47 | ||
| 32 | config_manager.register_config_converter( | 48 | config_manager.register_config_converter( |
| 33 | GraphTrainer.Config, | 49 | GraphTrainer.Config, |
| @@ -0,0 +1,360 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 2 | +# | ||
| 3 | +# This source code is licensed under the BSD-style license found in the | ||
| 4 | +# LICENSE file in the root directory of this source tree. | ||
| 5 | + | ||
| 6 | +"""NPU auto-overlap pass for GraphTrainer.""" | ||
| 7 | + | ||
| 8 | +from __future__ import annotations | ||
| 9 | + | ||
| 10 | +import functools | ||
| 11 | +from typing import TYPE_CHECKING | ||
| 12 | + | ||
| 13 | +from torchtitan.experiments.graph_trainer.registry import ( | ||
| 14 | + PASS_PIPELINE_REGISTRY, | ||
| 15 | + register_pass_pipeline, | ||
| 16 | +) | ||
| 17 | +from torchtitan.tools.logging import logger | ||
| 18 | + | ||
| 19 | +from torchtitan_npu.extensions.graph_trainer.utils import ( | ||
| 20 | + assign_stable_node_tags, | ||
| 21 | + canonical_order, | ||
| 22 | + dump_fx_graph, | ||
| 23 | + node_id, | ||
| 24 | +) | ||
| 25 | + | ||
| 26 | +if TYPE_CHECKING: | ||
| 27 | + from collections.abc import Callable | ||
| 28 | + | ||
| 29 | +AUTO_OVERLAP_PIPELINE = "npu_auto_overlap" | ||
| 30 | +MUTATION_FUNCTIONALIZATION_PIPELINE = "mutation-functionalization" | ||
| 31 | +MUTATION_FUNCTIONALIZATION_AUTO_OVERLAP_PIPELINE = "mutation-functionalization+npu_auto_overlap" | ||
| 32 | +_AUTO_OVERLAP_PIPELINES = { | ||
| 33 | + "default": AUTO_OVERLAP_PIPELINE, | ||
| 34 | + MUTATION_FUNCTIONALIZATION_PIPELINE: (MUTATION_FUNCTIONALIZATION_AUTO_OVERLAP_PIPELINE), | ||
| 35 | +} | ||
| 36 | +_EP_OVERLAP_SCHEDULE_PASS = "ep_overlap_schedule_pass" | ||
| 37 | +_CONCRETIZE_EP_SHAPES_PASS = "concretize_ep_chunk_symbolic_shapes_pass" | ||
| 38 | +_WHOLE_GRAPH_CALIBRATION_ROUNDS = 2 | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def _pass_name(pass_fn: Callable) -> str: | ||
| 42 | + return getattr(getattr(pass_fn, "func", pass_fn), "__name__", "") | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def is_npu_auto_overlap_pipeline(name: str) -> bool: | ||
| 46 | + """Return whether ``name`` selects an NPU auto-overlap composition.""" | ||
| 47 | + return name in _AUTO_OVERLAP_PIPELINES.values() | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def npu_moe_auto_overlap_pass( | ||
| 51 | + gm, | ||
| 52 | + _example_inputs, | ||
| 53 | + *, | ||
| 54 | + config, | ||
| 55 | + traced_result=None, | ||
| 56 | + runtime_context=None, | ||
| 57 | +): | ||
| 58 | + """Benchmark and schedule the configured NPU MoE regions.""" | ||
| 59 | + debug = bool(config.compile.debug_graph_passes) | ||
| 60 | + if debug: | ||
| 61 | + dump_fx_graph(gm, prefix="auto_overlap_before") | ||
| 62 | + from torchtitan_npu.extensions.graph_trainer.npu_moe_auto_scheduler import ( | ||
| 63 | + NpuMoeAutoOverlapScheduler, | ||
| 64 | + ) | ||
| 65 | + from torchtitan_npu.extensions.graph_trainer.whole_graph_benchmark import ( | ||
| 66 | + make_calibration_runner, | ||
| 67 | + profile_whole_graph_costs, | ||
| 68 | + ) | ||
| 69 | + | ||
| 70 | + ep_overlap_config = getattr(config.compile, "ep_overlap", None) | ||
| 71 | + module_pattern = getattr( | ||
| 72 | + ep_overlap_config, | ||
| 73 | + "module_fqn", | ||
| 74 | + "layers.*.moe", | ||
| 75 | + ) | ||
| 76 | + assign_stable_node_tags(gm) | ||
| 77 | + original_order = canonical_order(gm) | ||
| 78 | + | ||
| 79 | + scheduler = NpuMoeAutoOverlapScheduler( | ||
| 80 | + gm, | ||
| 81 | + module_pattern=module_pattern, | ||
| 82 | + canonical_order_override=original_order, | ||
| 83 | + debug=debug, | ||
| 84 | + ) | ||
| 85 | + scheduled = scheduler.run() | ||
| 86 | + if runtime_context is None: | ||
| 87 | + logger.warning( | ||
| 88 | + "Skipped NPU auto-overlap whole-graph calibration because " | ||
| 89 | + "apply_graph_passes did not provide a runtime context; keeping " | ||
| 90 | + "the first benchmark-driven schedule" | ||
| 91 | + ) | ||
| 92 | + else: | ||
| 93 | + run_candidate = make_calibration_runner( | ||
| 94 | + traced_result, | ||
| 95 | + runtime_context, | ||
| 96 | + ) | ||
| 97 | + for calibration_round in range(1, _WHOLE_GRAPH_CALIBRATION_ROUNDS + 1): | ||
| 98 | + # Profile and reschedule the graph produced by the previous round. | ||
| 99 | + # Stable IDs and canonical heuristic order stay fixed. | ||
| 100 | + fallback_costs = scheduler.costs_by_node_id | ||
| 101 | + logger.info( | ||
| 102 | + "NPU auto-overlap calibration round starting: calibration_round=%d total_rounds=%d cost_nodes=%d", | ||
| 103 | + calibration_round, | ||
| 104 | + _WHOLE_GRAPH_CALIBRATION_ROUNDS, | ||
| 105 | + len(fallback_costs), | ||
| 106 | + ) | ||
| 107 | + profile_costs = profile_whole_graph_costs( | ||
| 108 | + scheduled, | ||
| 109 | + run_candidate, | ||
| 110 | + profile_node_ids=frozenset(fallback_costs), | ||
| 111 | + calibration_round=calibration_round, | ||
| 112 | + debug=debug, | ||
| 113 | + ) | ||
| 114 | + if profile_costs is None: | ||
| 115 | + logger.warning( | ||
| 116 | + "Stopped NPU auto-overlap calibration after round %d; keeping the previous schedule", | ||
| 117 | + calibration_round, | ||
| 118 | + ) | ||
| 119 | + break | ||
| 120 | + # Whole-graph measurements replace prior costs directly; missing | ||
| 121 | + # measurements retain the latest available cost. | ||
| 122 | + applied_costs = fallback_costs | profile_costs.aligned_ms | ||
| 123 | + | ||
| 124 | + def calibrated_cost( | ||
| 125 | + node, | ||
| 126 | + *, | ||
| 127 | + applied_costs=applied_costs, | ||
| 128 | + fallback_costs=fallback_costs, | ||
| 129 | + aligned_costs=profile_costs.aligned_ms, | ||
| 130 | + calibration_round=calibration_round, | ||
| 131 | + ): | ||
| 132 | + stable_id = node_id(node) | ||
| 133 | + if stable_id is None: | ||
| 134 | + raise RuntimeError(f"FX node {node.name} has no auto-overlap node ID") | ||
| 135 | + previous_ms = fallback_costs.get(stable_id, 0.0) | ||
| 136 | + measured_ms = aligned_costs.get(stable_id) | ||
| 137 | + cost = applied_costs.get(stable_id, 0.0) | ||
| 138 | + if debug: | ||
| 139 | + logger.info( | ||
| 140 | + "NPU auto-overlap calibration applied cost: " | ||
| 141 | + "calibration_round=%d schedule_round=%d node_id=%s " | ||
| 142 | + "node=%s target=%s previous_ms=%.6f scheduler_ms=%.6f " | ||
| 143 | + "delta_ms=%.6f source=%s", | ||
| 144 | + calibration_round, | ||
| 145 | + calibration_round + 1, | ||
| 146 | + stable_id, | ||
| 147 | + node.name, | ||
| 148 | + node.target, | ||
| 149 | + previous_ms, | ||
| 150 | + cost, | ||
| 151 | + cost - previous_ms, | ||
| 152 | + "previous_round_fallback" if measured_ms is None else "whole_graph_profile", | ||
| 153 | + ) | ||
| 154 | + return cost | ||
| 155 | + | ||
| 156 | + scheduler = NpuMoeAutoOverlapScheduler( | ||
| 157 | + scheduled, | ||
| 158 | + module_pattern=module_pattern, | ||
| 159 | + compute_cost_fn=calibrated_cost, | ||
| 160 | + use_profile_compute_costs=True, | ||
| 161 | + collective_cost_fn=calibrated_cost, | ||
| 162 | + align_across_ranks=False, | ||
| 163 | + canonical_order_override=original_order, | ||
| 164 | + debug=debug, | ||
| 165 | + ) | ||
| 166 | + # Callbacks are consumed synchronously here, before loop state | ||
| 167 | + # changes. No single-op benchmark is rerun in calibrated rounds. | ||
| 168 | + scheduled = scheduler.run() | ||
| 169 | + next_costs = scheduler.costs_by_node_id | ||
| 170 | + logger.info( | ||
| 171 | + "NPU auto-overlap calibration round completed: " | ||
| 172 | + "calibration_round=%d measured_nodes=%d aligned_nodes=%d " | ||
| 173 | + "fallback_nodes=%d", | ||
| 174 | + calibration_round, | ||
| 175 | + len(profile_costs.local_ms), | ||
| 176 | + len(profile_costs.aligned_ms), | ||
| 177 | + len(next_costs.keys() - profile_costs.aligned_ms.keys()), | ||
| 178 | + ) | ||
| 179 | + scheduled.graph.lint() | ||
| 180 | + if debug: | ||
| 181 | + dump_fx_graph(scheduled, prefix="auto_overlap_after") | ||
| 182 | + return scheduled | ||
| 183 | + | ||
| 184 | + | ||
| 185 | +def _configure_npu_auto_overlap_passes( | ||
| 186 | + passes: list[Callable], | ||
| 187 | + config, | ||
| 188 | + *, | ||
| 189 | + traced_result=None, | ||
| 190 | + runtime_context=None, | ||
| 191 | +) -> list[Callable]: | ||
| 192 | + """Insert the only supported NPU MoE scheduler pass into ``passes``.""" | ||
| 193 | + precompile_artifact_dir = getattr( | ||
| 194 | + config.compile, | ||
| 195 | + "precompile_artifact_dir", | ||
| 196 | + "", | ||
| 197 | + ) | ||
| 198 | + if precompile_artifact_dir: | ||
| 199 | + logger.warning( | ||
| 200 | + "Skipped NPU auto-overlap because a precompiled artifact is " | ||
| 201 | + "being loaded; keeping the original runtime graph-pass pipeline" | ||
| 202 | + ) | ||
| 203 | + return passes | ||
| 204 | + | ||
| 205 | + schedule_passes = [pass_fn for pass_fn in passes if _pass_name(pass_fn) == _EP_OVERLAP_SCHEDULE_PASS] | ||
| 206 | + concretize_passes = [pass_fn for pass_fn in passes if _pass_name(pass_fn) == _CONCRETIZE_EP_SHAPES_PASS] | ||
| 207 | + if len(schedule_passes) != 1 or len(concretize_passes) != 1: | ||
| 208 | + logger.warning( | ||
| 209 | + "Skipped NPU auto-overlap because its required pass pipeline " | ||
| 210 | + "is unavailable: %s=%d, %s=%d; keeping the " | ||
| 211 | + "original graph-pass pipeline", | ||
| 212 | + _EP_OVERLAP_SCHEDULE_PASS, | ||
| 213 | + len(schedule_passes), | ||
| 214 | + _CONCRETIZE_EP_SHAPES_PASS, | ||
| 215 | + len(concretize_passes), | ||
| 216 | + ) | ||
| 217 | + return passes | ||
| 218 | + | ||
| 219 | + schedule_index = passes.index(schedule_passes[0]) | ||
| 220 | + concretize_index = passes.index(concretize_passes[0]) | ||
| 221 | + if schedule_index >= concretize_index: | ||
| 222 | + logger.warning( | ||
| 223 | + "Skipped NPU auto-overlap because the original pass order is " | ||
| 224 | + "unsupported: %s must precede %s; keeping the original " | ||
| 225 | + "graph-pass pipeline", | ||
| 226 | + _EP_OVERLAP_SCHEDULE_PASS, | ||
| 227 | + _CONCRETIZE_EP_SHAPES_PASS, | ||
| 228 | + ) | ||
| 229 | + return passes | ||
| 230 | + | ||
| 231 | + # Install the compatibility patch only after confirming that this pipeline | ||
| 232 | + # will use auto-overlap. Remove it after the torch_npu support lands. | ||
| 233 | + from torchtitan_npu.patches.torch_npu import inductor_benchmarking | ||
| 234 | + | ||
| 235 | + inductor_benchmarking.apply() | ||
| 236 | + | ||
| 237 | + pass_kwargs = { | ||
| 238 | + "config": config, | ||
| 239 | + "traced_result": traced_result, | ||
| 240 | + } | ||
| 241 | + if runtime_context is not None: | ||
| 242 | + pass_kwargs["runtime_context"] = runtime_context | ||
| 243 | + configured_pass = functools.partial(npu_moe_auto_overlap_pass, **pass_kwargs) | ||
| 244 | + if runtime_context is None: | ||
| 245 | + # Compatibility with TorchTitan revisions that do not pass runtime | ||
| 246 | + # context to pipeline construction. The local patch binds it later. | ||
| 247 | + configured_pass._requires_runtime_context = True # pyrefly: ignore [missing-attribute] | ||
| 248 | + | ||
| 249 | + # Retain the native EP structural checks at the original scheduling | ||
| 250 | + # position. Runtime benchmarking requires concrete tensor dimensions, so | ||
| 251 | + # defer the NPU scheduler until after concretization. | ||
| 252 | + from torchtitan.experiments.graph_trainer.ep_overlap_pass import ( | ||
| 253 | + ep_overlap_validate_pass, | ||
| 254 | + ) | ||
| 255 | + | ||
| 256 | + schedule_pass = schedule_passes[0] | ||
| 257 | + if isinstance(schedule_pass, functools.partial): | ||
| 258 | + validation_kwargs = dict(schedule_pass.keywords or {}) | ||
| 259 | + # The pinned validator uses ``require_all_to_all`` only on its | ||
| 260 | + # scheduling branch and raises when ``reorder=False``. The NPU | ||
| 261 | + # scheduler below independently requires a matching chunked region. | ||
| 262 | + validation_kwargs["require_all_to_all"] = False | ||
| 263 | + validation_pass = functools.partial( | ||
| 264 | + ep_overlap_validate_pass, | ||
| 265 | + *schedule_pass.args, | ||
| 266 | + **validation_kwargs, | ||
| 267 | + ) | ||
| 268 | + else: | ||
| 269 | + validation_pass = ep_overlap_validate_pass | ||
| 270 | + configured = [validation_pass if pass_fn is schedule_pass else pass_fn for pass_fn in passes] | ||
| 271 | + concretize_index = configured.index(concretize_passes[0]) | ||
| 272 | + configured.insert(concretize_index + 1, configured_pass) | ||
| 273 | + return configured | ||
| 274 | + | ||
| 275 | + | ||
| 276 | +def enable_npu_auto_overlap(config): | ||
| 277 | + """Select the NPU auto-overlap composition for the current base pipeline.""" | ||
| 278 | + base_pipeline = config.compile.pass_pipeline | ||
| 279 | + try: | ||
| 280 | + config.compile.pass_pipeline = _AUTO_OVERLAP_PIPELINES[base_pipeline] | ||
| 281 | + except KeyError as error: | ||
| 282 | + supported = ", ".join(sorted(_AUTO_OVERLAP_PIPELINES)) | ||
| 283 | + raise ValueError( | ||
| 284 | + f"NPU auto-overlap does not support base pass pipeline {base_pipeline!r}; supported pipelines: {supported}" | ||
| 285 | + ) from error | ||
| 286 | + return config | ||
| 287 | + | ||
| 288 | + | ||
| 289 | +def _construct_npu_auto_overlap_pipeline( | ||
| 290 | + base_pipeline: str, | ||
| 291 | + traced_result, | ||
| 292 | + config, | ||
| 293 | + *, | ||
| 294 | + parallel_dims=None, | ||
| 295 | + runtime_context=None, | ||
| 296 | +) -> list[Callable]: | ||
| 297 | + """Build ``base_pipeline`` with EP validation and NPU scheduling.""" | ||
| 298 | + if base_pipeline == "default": | ||
| 299 | + from torchtitan.experiments.graph_trainer.passes import ( | ||
| 300 | + construct_default_graph_passes, | ||
| 301 | + ) | ||
| 302 | + | ||
| 303 | + pipeline_fn = construct_default_graph_passes | ||
| 304 | + else: | ||
| 305 | + pipeline_fn = PASS_PIPELINE_REGISTRY.get(base_pipeline) | ||
| 306 | + if pipeline_fn is None: | ||
| 307 | + raise ValueError(f"Base pass pipeline {base_pipeline!r} is not registered") | ||
| 308 | + | ||
| 309 | + passes = pipeline_fn( | ||
| 310 | + traced_result, | ||
| 311 | + config, | ||
| 312 | + parallel_dims=parallel_dims, | ||
| 313 | + ) | ||
| 314 | + return _configure_npu_auto_overlap_passes( | ||
| 315 | + passes, | ||
| 316 | + config, | ||
| 317 | + traced_result=traced_result, | ||
| 318 | + runtime_context=runtime_context, | ||
| 319 | + ) | ||
| 320 | + | ||
| 321 | + | ||
| 322 | +@register_pass_pipeline(AUTO_OVERLAP_PIPELINE) | ||
| 323 | +def construct_npu_auto_overlap_passes( | ||
| 324 | + traced_result, | ||
| 325 | + config, | ||
| 326 | + *, | ||
| 327 | + parallel_dims=None, | ||
| 328 | + runtime_context=None, | ||
| 329 | +) -> list[Callable]: | ||
| 330 | + """Build the default pipeline with the NPU MoE scheduler as its EP pass.""" | ||
| 331 | + return _construct_npu_auto_overlap_pipeline( | ||
| 332 | + "default", | ||
| 333 | + traced_result, | ||
| 334 | + config, | ||
| 335 | + parallel_dims=parallel_dims, | ||
| 336 | + runtime_context=runtime_context, | ||
| 337 | + ) | ||
| 338 | + | ||
| 339 | + | ||
| 340 | +# Compatibility composition for the local functionalization backport in | ||
| 341 | +# torchtitan_npu/patches/torchtitan/experiments/graph_trainer/ | ||
| 342 | +# functionalize_recompute_mutations.py. | ||
| 343 | +# Remove this pipeline after pytorch/torchtitan#4708 lands in the pinned | ||
| 344 | +# TorchTitan dependency with equivalent pipeline support. | ||
| 345 | +@register_pass_pipeline(MUTATION_FUNCTIONALIZATION_AUTO_OVERLAP_PIPELINE) | ||
| 346 | +def construct_mutation_functionalization_npu_auto_overlap_passes( | ||
| 347 | + traced_result, | ||
| 348 | + config, | ||
| 349 | + *, | ||
| 350 | + parallel_dims=None, | ||
| 351 | + runtime_context=None, | ||
| 352 | +) -> list[Callable]: | ||
| 353 | + """Compose the local mutation-functionalization pipeline with the NPU scheduler.""" | ||
| 354 | + return _construct_npu_auto_overlap_pipeline( | ||
| 355 | + MUTATION_FUNCTIONALIZATION_PIPELINE, | ||
| 356 | + traced_result, | ||
| 357 | + config, | ||
| 358 | + parallel_dims=parallel_dims, | ||
| 359 | + runtime_context=runtime_context, | ||
| 360 | + ) | ||