Merged
feat: adapt GraphTrainer EP overlap for DeepSeek-V4 #695
feat: adapt GraphTrainer EP overlap for DeepSeek-V4 #695
Merged
wanlinanAdd on Sep 3
Total: 16 files changed+577-7
@@ -84,9 +84,10 @@ torchrun --nproc_per_node=8 -m torchtitan.train \
84| 并行组合 | FSDP(含 degree 1)、EP 已验证;TP 要求 `seq_len` 整除 `seq_len_divisor` |84| 并行组合 | FSDP(含 degree 1)、EP 已验证;TP 要求 `seq_len` 整除 `seq_len_divisor` |
85| `spmd_types` backend | 不支持(simple_fsdp 依赖 raw DTensor 操作) |85| `spmd_types` backend | 不支持(simple_fsdp 依赖 raw DTensor 操作) |
86| Context Parallel | 不支持(DSV4 稀疏注意力编译路径未适配 CP) |86| Context Parallel | 不支持(DSV4 稀疏注意力编译路径未适配 CP) |
87-| EP overlap(上游实验性 pass) | 未验证 |87+| EP overlap(上游实验性 pass) | 已通过patch适配;见 [`graph_trainer_ep_overlap.md`](graph_trainer_ep_overlap.md) |
88 88 
89## 相关文档89## 相关文档
90 90 
91- 上游 GraphTrainer 说明与 EP overlap 用法:[`torchtitan/experiments/graph_trainer/README.md`](https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/graph_trainer/README.md)91- 上游 GraphTrainer 说明与 EP overlap 用法:[`torchtitan/experiments/graph_trainer/README.md`](https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/graph_trainer/README.md)
92+- EP overlap 适配:[`graph_trainer_ep_overlap.md`](graph_trainer_ep_overlap.md)
92- DSV4 稀疏注意力与 TND 融合路径:[`deepseek_v4_tnd.md`](deepseek_v4_tnd.md)93- DSV4 稀疏注意力与 TND 融合路径:[`deepseek_v4_tnd.md`](deepseek_v4_tnd.md)
@@ -91,7 +91,7 @@ torchtitan/experiments/graph_trainer/memory_policy.py
91### 4.2 NPU 策略框架91### 4.2 NPU 策略框架
92 92 
93```text93```text
94-torchtitan_npu/patches/torchtitan/graph_trainer/memory_policy.py94+torchtitan_npu/patches/torchtitan/experiments/graph_trainer/memory_policy.py
95```95```
96 96 
97NPU 扩展使用 `NodePolicyKey` 按 FX target、模块 FQN 和 occurrence 定位节点,并提供 layer boundary、`MUST_SAVE`、反向节点跳过、`lm_head/loss` 跳过和 SymInt 保存等规则。97NPU 扩展使用 `NodePolicyKey` 按 FX target、模块 FQN 和 occurrence 定位节点,并提供 layer boundary、`MUST_SAVE`、反向节点跳过、`lm_head/loss` 跳过和 SymInt 保存等规则。
@@ -150,12 +150,12 @@ CPU offload 与 SAR 之前把变异写入显式化为数据流,原生 SAR 随
150| --- | --- |150| --- | --- |
151| DSV4 GraphTrainer 配置 | `torchtitan_npu/models/deepseek_v4/config_registry.py` |151| DSV4 GraphTrainer 配置 | `torchtitan_npu/models/deepseek_v4/config_registry.py` |
152| 通用 full policy | `torchtitan/experiments/graph_trainer/memory_policy.py` |152| 通用 full policy | `torchtitan/experiments/graph_trainer/memory_policy.py` |
153-| NPU policy 框架 | `torchtitan_npu/patches/torchtitan/graph_trainer/memory_policy.py` |153+| NPU policy 框架 | `torchtitan_npu/patches/torchtitan/experiments/graph_trainer/memory_policy.py` |
154| `dsv4-mhc` 策略 | `torchtitan_npu/models/deepseek_v4/memory_policy.py` |154| `dsv4-mhc` 策略 | `torchtitan_npu/models/deepseek_v4/memory_policy.py` |
155| FX tracer/replay | `torchtitan/experiments/graph_trainer/make_fx_tracer.py`、`torchtitan/experiments/graph_trainer/trainer.py` |155| FX tracer/replay | `torchtitan/experiments/graph_trainer/make_fx_tracer.py`、`torchtitan/experiments/graph_trainer/trainer.py` |
156| SimpleFSDP | `torchtitan/experiments/graph_trainer/simple_fsdp.py` |156| SimpleFSDP | `torchtitan/experiments/graph_trainer/simple_fsdp.py` |
157| 函数式 compressor | `torchtitan_npu/models/deepseek_v4/compressor.py` |157| 函数式 compressor | `torchtitan_npu/models/deepseek_v4/compressor.py` |
158-| 变异重算保真(functionalization backport) | `torchtitan_npu/patches/torchtitan/graph_trainer/functionalize_recompute_mutations.py` |158+| 变异重算保真(functionalization backport) | `torchtitan_npu/patches/torchtitan/experiments/graph_trainer/functionalize_recompute_mutations.py` |
159| 重算单测 | `tests/unit_tests/compile/test_recompute_policy.py` |159| 重算单测 | `tests/unit_tests/compile/test_recompute_policy.py` |
160 160 
161## 7. 结论161## 7. 结论
@@ -0,0 +1,278 @@
1+# GraphTrainer EP overlap 适配
2+ 
张德鹏
张德鹏张德鹏Sep 16

文档就不用耦合DSV4了吧 这是个通用的ep-overlap方案

likedislike
wanlinan
wanlinan
Sep 17 Comments:
likedislike
3+EP overlap 是 torchtitan 上游 `experiments/graph_trainer/` 为 MoE + Expert Parallel(EP)训练提供的通用 graph pass:把 MoE 区域按 token 维切成两个 chunk,使一个 chunk 的 all-to-all 通信与另一个 chunk 的专家计算重叠。该能力的配置接口、pass pipeline 和本文的临时补丁均不绑定具体模型名称。本文描述启用该能力所需的四个 `patches/torchtitan/` 临时补丁;这些问题最先由 DeepSeek-V4(DSV4)验证图暴露,当前整网验证也使用 DSV4。
4+ 
5+| 序号 | pass名称 | 内容 |
6+| --- | --- | --- |
7+| 1 | mark_unbacked(前置操作,不属于pass) | 在 trace 前制造 chunk 动态维度及 hint |
8+| 2 | populate_chunk_dim_metadata_pass | trace 后识别该符号,并登记“这是 EP chunk symbol” |
9+| 3 | ep_overlap_chunk_pass | 利用 EP chunk symbol 符号切图 |
10+| 4 | ep_overlap_schedule_pass | 根据两个 chunk 重排通信和计算 |
11+| 5 | concretize_ep_chunk_symbolic_shapes_pass | 调度结束后,使用筛选后的 hint 具体化相关符号 |
12+ 
13+EP overlap 默认不启用。它只在 GraphTrainer 编译路径(`graph_trainer_*` 配置)下生效,普通 eager 训练不走这些 graph pass;下文配置项中的 `strategy=eager` 指 GraphTrainer 的另一种 chunk 实现方式。DSV4 验证样例所依赖的模型侧 GraphTrainer 适配见 [`deepseek_v4_graph_trainer.md`](deepseek_v4_graph_trainer.md)。
14+ 
15+## 能力范围、依赖与验证边界
16+ 
17+| 项 | 值 |
18+| --- | --- |
19+| 能力对象 | 使用 GraphTrainer、MoE 和真实 EP token exchange 的训练图;EP degree > 1 |
20+| 当前整网验证模型 | DeepSeek-V4,使用 `graph_trainer_deepseek_v4_flash_43layers_16experts` 配置 |
21+| 训练路径 | GraphTrainer `aot_fx_trace`;eager 路径不涉及 |
22+| torchtitan 基线 | `0.3.0`(`requirements.txt` 固定版本) |
23+| 环境 | Ascend NPU + `torch-npu` + CANN + HCCL;EP degree > 1 |
24+| 默认状态 | 关闭,需显式传 `--compile.ep_overlap.enabled` |
25+ 
26+## 实现原理
27+ 
28+### 四个上游临时补丁
29+ 
30+补丁位于 `torchtitan_npu/patches/torchtitan/experiments/graph_trainer/`,针对 `requirements.txt` 固定的 torchtitan 0.3.0,在 `import torchtitan_npu` 时经 `patches/torchtitan/__init__.py` 自动 `apply()`。它们修正的是上游 graph pass 的行为,代码不依赖 NPU 专有算子,也不检查模型类型。DSV4 验证图只是这些问题的首个整网复现场景;任何产生相同符号关系、节点标注或调度依赖的 GraphTrainer MoE 图都会进入相同处理逻辑。
31+ 
32+四个 patch 共替换或包装五个上游函数,均有标记防止重复 `apply()`。它们的执行顺序是:第四个作用于 chunk pass,第二、第三个作用于 overlap schedule pass,第一个作用于调度后的 concretization pass。
33+ 
34+| 补丁模块 | 替换或包装的上游符号 | 当前修复方案 |
35+| --- | --- | --- |
36+| `ep_chunk_concretization` | `ep_pass_utils._placeholder_symbol_hints`、`_concretize_value` | 筛选含 chunk symbol 的 placeholder 维度;与传入 hint 符号无交集的值保持原样 |
37+| `ep_overlap_shape_queries` | `ep_overlap_pass._collect_token_exchanges` | 清理 body 内 AllToAll launch 的 size query 误继承的 exchange 标注,再调用上游收集器 |
38+| `ep_ready_nodes_dedup` | `ep_overlap_pass._ready_nodes` | 保留候选遍历和依赖检查,用本轮 `selected` 集合跨 chunk 去重 |
39+| `ep_shape_live_out` | `ep_chunk_pass._split_live_out_users` | 将同一 root 内直接查询 AllToAll dim-0 的 full user 移到 chunked |
40+ 
41+#### 1. ep_chunk_concretization.py
42+ 
43+报错示例:
44+ 
45+```text
46+ValueError: Chunk pass could not derive a base hint for symbol u0 from
47+arg2594_1.shape[0] extent Max(0, u0 - Min(1, u0)) + 1.
48+```
49+ 
50+FX 图中既有 EP chunk symbol,也有独立的数据相关 metadata symbol。社区 `ep_pass_utils.py` 中的 `_placeholder_symbol_hints` 遍历所有 tensor placeholder 的 shape 维度,对每个维度调用 `_record_symbols_from_extent`。因此,与 chunk 无关的非线性 metadata 维度也会进入 hint 推导,可能因无法推导 base hint 而报错。
51+ 
52+社区具体化流程先合并 placeholder hint 和 chunk hint,再调用 `_concretize_value`。原 `_concretize_value` 还可能通过值自身的 hint 把不属于目标范围的动态值折叠成常量。
53+ 
54+**Patch 方案:**
55+ 
56+| 社区函数 | 当前实现 |
57+| --- | --- |
58+| `_placeholder_symbol_hints` | 替换为 `_chunk_placeholder_symbol_hints`:取得 `chunk_symbol_hints_for_mode(gm).keys()`,只对自由符号与它有交集的 placeholder shape 维度调用上游 `_record_symbols_from_extent` |
59+| `_concretize_value` | 包装原函数:值的自由符号与传入 `symbol_hints.keys()` 无交集时原样返回,否则委托上游原函数具体化 |
60+ 
61+placeholder hint 收集逻辑:
62+ 
63+```python
64+def _chunk_placeholder_symbol_hints(gm: fx.GraphModule) -> dict[object, int]:
65+ chunk_symbols = ep_pass_utils.chunk_symbol_hints_for_mode(gm).keys()
66+ hints: dict[object, int] = {}
67+ for node in gm.graph.nodes:
68+ if node.op != "placeholder" or (val := ep_pass_utils.tensor_meta(node)) is None:
69+ continue
70+ for dim, extent in enumerate(val.shape):
71+ symbols = ep_pass_utils.free_symbols(extent)
72+ if not symbols & chunk_symbols:
73+ continue
74+ ep_pass_utils._record_symbols_from_extent(hints, extent, source=f"{node.name}.shape[{dim}]")
75+ return hints
76+```
77+ 
78+值具体化的包装逻辑:
79+ 
80+```python
81+def _concretize_chunk_value(value: object, symbol_hints: dict[object, int]) -> object:
82+ if not ep_pass_utils.free_symbols(value) & symbol_hints.keys():
83+ return value
84+ return original_concretize_value(value, symbol_hints)
85+```
86+ 
87+这里有两个不同的筛选集合:placeholder 维度按 **EP chunk symbol** 筛选;值具体化按调用方传入的 **合并后 hint 字典**筛选。若选中的维度包含其他符号且上游能推导其 hint,这些符号也可能进入具体化范围,不能将第二层条件表述为“值必须直接含有 EP chunk symbol”。
88+ 
89+当前实现不扫描全图的 shape、stride、storage offset,也不计算符号依赖连通分量。选中维度的 hint 推导仍使用上游规则:缺少 hint、无法推导 base hint、hint 冲突都会继续报错,不会被忽略。`apply()` 检查六个所需上游辅助符号,缺失时记录 warning 并跳过此 patch。
90+ 
91+#### 2. ep_overlap_shape_queries.py
92+ 
93+报错示例:
94+ 
95+```text
96+ValueError: ep_overlap found EP token-exchange metadata on non-marker
97+node sym_size_int (aten.sym_size.int). Only all_to_all launches
98+and their wait_tensor nodes may carry this annotation.
99+```
100+ 
101+错误发生在 `ep_overlap_schedule_pass` 的通信节点收集阶段。AllToAll 输出的接收 token 数是数据相关的,trace 会生成 `aten.sym_size.int(all_to_all_output, 0)` 来绑定其首维长度。该节点在通信标注的作用域内生成,可能继承 `EP_token_exchange=dispatch`。社区 `_collect_token_exchanges` 只接受带此标注的 token-exchange launch 及其 wait,遇到 size query 就报错。
102+ 
103+**Patch 方案:**在原 `_collect_token_exchanges` 前遍历当前 `body.nodes`,仅处理同时满足以下条件的节点:
104+ 
105+- `op == "call_function"`、target 为 `aten.sym_size.int`,且恰有两个位置参数。
106+- 第一个参数是当前 body 内的 FX 节点,并且上游 `_is_token_exchange_launch` 将其识别为 token-exchange launch。
107+ 
108+包装函数的主体如下;只在 `custom` 中存在 `EP_token_exchange` 时复制字典并删除这个键:
109+ 
110+```python
111+node_set = set(body.nodes)
112+for node in body.nodes:
113+ if not _is_token_exchange_shape_query(node, node_set):
114+ continue
115+ custom = ep_overlap_pass._custom_meta(node)
116+ if _EP_TOKEN_EXCHANGE in custom:
117+ custom = dict(custom)
118+ del custom[_EP_TOKEN_EXCHANGE]
119+ node.meta["custom"] = custom
120+return current(body, order=order)
121+```
122+ 
123+其余 metadata 保留;删除后即使 `custom` 为空也保留该容器;没有该标签时不改写 metadata。匹配条件不限制查询维度为 0,也不显式检查查询值是否 unbacked。launch/wait 的识别、唯一 wait 检查、顺序检查和 wait 标注归一化仍由上游完成,其他非目标节点的错误继续抛出。
124+ 
125+当前正式 patch 仍采用“删除 shape query 继承的标签”方案,没有改成“保留标签、仅绕过报错”。
126+ 
127+#### 3. ep_ready_nodes_dedup.py
128+ 
129+报错示例及调用关系:
130+ 
131+```text
132+AssertionError: stable topological sort failed
133+ 
134+ep_overlap_schedule_pass()
135+ -> _schedule_ep_overlap_regions()
136+ -> _plan_region()
137+ -> _build_region_phases()
138+ -> _append_ready_blocks()
139+ -> _ready_nodes() # 可能返回重复 node
140+ -> _apply_schedule()
141+ -> _phase_order_deps() # 顺序约束可能构成环
142+ -> _stable_topological_sort()
143+```
144+ 
145+节点有确定的 chunk 所有权,但两个 chunk 的调度候选集合可能有交集。例如,节点 N 属于 chunk0,同时又是 chunk1 后续 AllToAll 的依赖,它可能同时出现在两个 chunk 的候选集中。
146+ 
147+社区 `_ready_nodes` 对每个 chunk 仅排除此前已经 `emitted` 的节点;`_append_ready_blocks` 要等整个 ready 元组生成后才更新 `emitted`,因此无法排除本轮内部的重复项。若返回结果为 `[N, A, N]`,后续顺序依赖会形成 `N -> A -> N`。
148+ 
149+**Patch 方案:**当前提交保留 `_ready_nodes` 的遍历实现,在一次调用内新增 `selected` 集合;不修改传入的 `emitted`。替换函数的主体如下:
150+ 
151+```python
152+ready = []
153+selected: set[fx.Node] = set()
154+for chunk_id in chunk_order:
155+ body = region.bodies_by_chunk[chunk_id]
156+ candidates = sorted(candidates_by_chunk.get(chunk_id, set()) - emitted, key=order.__getitem__)
157+ for node in candidates:
158+ if node in selected:
159+ continue
160+ if not include_waits and ep_overlap_pass._is_c10d_functional_node(node):
161+ continue
162+ deps = ep_overlap_pass._body_deps(node, body=body, owner_by_node=owner_by_node)
163+ if all(dep in emitted for dep in deps):
164+ ready.append(node)
165+ selected.add(node)
166+return tuple(ready)
167+```
168+ 
169+chunk 遍历顺序、chunk 内候选排序、`include_waits` 过滤以及依赖必须已经 `emitted` 的条件都保留;只有实际追加到 ready 的节点才记入 `selected`。每个节点在一次返回中最多出现一次,保留首次被选中的位置。当前代码没有调用原 `_ready_nodes` 后再对返回值去重。
170+ 
171+#### 4. ep_shape_live_out.py
172+ 
173+报错示例:
174+ 
175+```text
176+ValueError: Chunk pass cannot materialize live-out without chunk dimension;
177+all_to_all_single_default from 'layers.0.moe' has full users
178+['sym_size_int:sym_size.int:fqn=layers.0.moe.dispatcher']
179+and requires a forward accumulation proof or a backward parameter-gradient consumer.
180+```
181+ 
182+live-out 是 chunk body 内产生、但仍被 body 外节点使用的值。社区 `_split_live_out_users` 将消费者分成 `chunked`(跟随对应 chunk 的值)和 `full`(需要重建完整值)。某些 dispatcher size query 带有 MoE 模块 FQN,却位于 body 外;它们需要查询各 chunk 自己接收的 token 数,但上游分类将其归入 `full`。
183+ 
184+社区 `_materialize_live_out` 只能在识别到 chunk 维时沿该维 `cat`,或在有加法重建依据时 `add`。AllToAll 输出首维是独立的接收 token symbol,通常不含选定的 chunk symbol,因而无法识别拼接维度;正向也没有适用的加法依据,最终报错。修复此场景的关键是调整消费者归属,使它无需完整值重建。
185+ 
186+**Patch 方案:**只包装 `_split_live_out_users`。先调用社区原函数,再从 `full` 中筛选:
187+ 
188+- user 是 `call_function` 节点,target 为 `aten.sym_size.int`,恰有两个位置参数,第二个参数为 `0`。
189+- 第一个参数直接指向 `call_function` 类型的 `_c10d_functional.all_to_all_single.default` 节点。
190+- user 的模块 FQN 位于 `producer_region.root_fqn` 内。
191+ 
192+```python
193+chunked, full = current(users, plans, producer_region, symbol_hints)
194+moved = tuple(
195+ user
196+ for user in full
197+ if _is_dim0_all_to_all_size_user(user)
198+ and ep_chunk_pass.is_module_fqn_inside_root(
199+ ep_chunk_pass._get_module_fqn(user), producer_region.root_fqn
200+ )
201+)
202+if not moved:
203+ return chunked, full
204+moved_set = set(moved)
205+return (*chunked, *moved), tuple(user for user in full if user not in moved_set)
206+```
207+ 
208+| 函数 | 当前行为 |
209+| --- | --- |
210+| `_split_live_out_users` | 将满足上述条件的 user 从 full 移到 chunked;没有匹配者时返回原分类结果 |
211+| `_materialize_live_out` | **保持社区原函数,不再替换,也不新增 AllToAll dim-0 的 cat fallback** |
212+ 
213+匹配不依赖 `EP_token_exchange` 标签,也不覆盖 wait 输出、普通张量或其他维度的 size query。没有剩余 full users 时,社区 chunk pass 跳过这个 live-out 的完整值重建。仍有 full users 时继续执行社区重建规则和校验,不能重建的情况仍报错。
214+ 
215+第二个 patch 的标签清理发生在后续 schedule pass,晚于这里的 live-out 分类,因此第四个问题不是删除标签引起的。
216+ 
217+父模块、其他 root 或缺失 FQN 的 dim-0 query 仍可能被归为 full;若未来要支持这些场景,需要额外定义重建方案,不能将当前补丁的适用范围外推为所有 AllToAll shape live-out 都受支持。
218+ 
219+## 启用方式
220+ 
221+EP overlap 通过 `--compile.ep_overlap.*` 打开。满足前述条件的 GraphTrainer MoE recipe 均通过同一组配置项启用;模型入口、dispatcher、并行配置和算子 override 仍由各模型 recipe 负责。
222+ 
223+下面仅给出本文整网验证使用的 DSV4 示例:flash 43layers/16experts、8 卡、EP=8,复用仓内 DSV4 GraphTrainer 入口脚本。
224+ 
225+```bash
226+NGPU=8 \
227+HF_ASSETS_PATH=/path/to/DeepSeekV4_tokenizer \
228+bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3_graphtrainer.sh \
229+ --optimizer.name native \
230+ --compile.disable_passes cudagraph_pass,annotate_flex_attention_for_regional_inductor_pass,regional_inductor_pass \
231+ --compile.ep_overlap.enabled \
232+ --compile.ep_overlap.strategy graph \
233+ --compile.ep_overlap.chunk_dim seq \
234+ --compile.ep_overlap.module_fqn 'layers.*.moe'
235+```
236+ 
237+`EpOverlapConfig`(`torchtitan/experiments/graph_trainer/configs.py`)字段:
238+ 
239+| 字段 | 取值 | 说明 |
240+| --- | --- | --- |
241+| `enabled` | `bool`,默认 `False` | 是否启用 EP overlap |
242+| `strategy` | `eager` / `graph`,默认 `graph` | `eager` 在 trace 前包装模块 forward;`graph` trace 原模型后用 FX pass 切分 |
243+| `chunk_dim` | `batch` / `seq`,默认 `batch` | 切分的逻辑输入维 |
244+| `module_fqn` | `layers.*` / `layers.*.moe`,默认 `layers.*` | 被切分的模块 FQN 模式 |
245+| `disable_early_grad_accumulation` | `bool`,默认 `False` | 关闭 graph chunking 的早期参数梯度累加,用于需要与 eager chunking 保持严格顺序的验证场景 |
246+ 
247+上游 `validate_ep_overlap_config` 约束:`chunk_dim=seq` 仅在 `module_fqn=layers.*.moe` 时可用——序列切分要求完整 K/V 上下文,因此只对 MoE block 根成立。
248+ 
249+若需把 EP overlap 固化为某个配置的默认值,在 `config_registry.py` 的对应工厂中对 `config.compile.ep_overlap` 赋 `EpOverlapConfig(...)`。
250+ 
251+## DSV4 整网实跑验证(2026-09-16)
252+ 
253+本节只记录 DSV4 作为验证载体的结果,用于证明通用 EP overlap 能力及临时补丁在这一具体组合上可以完成整网训练。
254+ 
255+在同一台机器上按“关闭 EP overlap -> 开启 EP overlap”的顺序各运行 10 step。两组均使用 8 张 Ascend 910、CANN 9.2.0、TorchTitan `v0.3.0`(`086bf6c166ec85c1298eb5596fa9bf95f6a2d840`)和本仓库 HEAD `ec98b86809e024e105958b50c7714666c8c65ff2`。模型为 flash 43 layers / 16 experts,EP=8、DP shard=8、TP/CP/PP=1,local/global batch size 为 1/64,sequence length 为 4096,seed 为 42。
256+ 
257+开启组再追加“启用方式”中的四个 `--compile.ep_overlap.*` 参数;关闭组不追加这些参数。
258+ 
259+| 指标 | EP overlap 关闭 | EP overlap 开启 |
260+| --- | ---: | ---: |
261+| 结果 | 10/10 step,退出码 0 | 10/10 step,退出码 0 |
262+| graph pass | 7 个,43.617 s | 13 个,228.628 s |
263+| EP 图变换 | 无 | seq chunking 86 个 region;scheduling 86 个 region |
264+| step 2-10 平均耗时 | 64.975 s | 62.923 s |
265+| step 2-10 平均 TPS | 505.000 | 521.222 |
266+| loss(step 1 -> 10) | 12.19569 -> 9.91401 | 12.19564 -> 9.94998 |
267+| 日志记录的峰值显存 | 52.22 GiB(85.23%) | 59.37 GiB(96.90%) |
268+ 
269+该次顺序单跑中,开启组 step 2-10 的平均 TPS 比关闭组高约 3.2%。
270+ 
271+开启组的代价也较明显:日志峰值显存增加 7.15 GiB。
272+ 
273+## 相关文档
274+ 
275+- DSV4 模型侧 GraphTrainer 适配:[`deepseek_v4_graph_trainer.md`](deepseek_v4_graph_trainer.md)
276+- 临时补丁目录约定:[`torchtitan_npu/patches/torchtitan/README.md`](../../torchtitan_npu/patches/torchtitan/README.md)
277+- Override 注册表:[`torchtitan_npu/override/README.md`](../../torchtitan_npu/override/README.md)
278+- 上游 GraphTrainer 与 EP overlap 说明:[`torchtitan/experiments/graph_trainer/README.md`](https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/graph_trainer/README.md)
@@ -40,7 +40,7 @@ from tests.unit_tests.rope_test_utils import (
40 split_workaround_reference,40 split_workaround_reference,
41)41)
42from torchtitan_npu.override.common.rope import AscPartialComplexRoPE42from torchtitan_npu.override.common.rope import AscPartialComplexRoPE
43-from torchtitan_npu.patches.torchtitan.graph_trainer.functionalize_recompute_mutations import (43+from torchtitan_npu.patches.torchtitan.experiments.graph_trainer.functionalize_recompute_mutations import (
44 functionalize_recompute_mutations_pass,44 functionalize_recompute_mutations_pass,
45)45)
46 46 
@@ -40,7 +40,7 @@ from torchtitan_npu.config import (
40)40)
41from torchtitan_npu.extensions.profiler import CANNProfiler41from torchtitan_npu.extensions.profiler import CANNProfiler
42from torchtitan_npu.extensions.trainer import TrainerEx42from torchtitan_npu.extensions.trainer import TrainerEx
43-from torchtitan_npu.patches.torchtitan.graph_trainer import (43+from torchtitan_npu.patches.torchtitan.experiments.graph_trainer import (
44 functionalize_recompute_mutations as _functionalize_mutations,44 functionalize_recompute_mutations as _functionalize_mutations,
45)45)
46 46 
@@ -22,7 +22,7 @@ from torchtitan.experiments.graph_trainer.registry import (
22 register_memory_policy,22 register_memory_policy,
23)23)
24 24 
25-from torchtitan_npu.patches.torchtitan.graph_trainer import memory_policy25+from torchtitan_npu.patches.torchtitan.experiments.graph_trainer import memory_policy
26 26 
27if TYPE_CHECKING:27if TYPE_CHECKING:
28 import torch28 import torch
@@ -5,6 +5,8 @@
5- https://github.com/pytorch/torchtitan/pull/38645- https://github.com/pytorch/torchtitan/pull/3864
6- https://github.com/pytorch/torchtitan/pull/44746- https://github.com/pytorch/torchtitan/pull/4474
7- https://github.com/pytorch/torchtitan/pull/39857- https://github.com/pytorch/torchtitan/pull/3985
8+- https://github.com/pytorch/torchtitan/pull/4650
9+- https://github.com/pytorch/torchtitan/pull/4651
8-->10-->
9 11 
10# TorchTitan 临时补丁12# TorchTitan 临时补丁
@@ -36,5 +38,12 @@ grep -L "Pending upstream PR: https://github.com/pytorch/torchtitan/pull/" \
36| [#3864](https://github.com/pytorch/torchtitan/pull/3864) | 为 torchtitan 补充 LoggedAuxLoss 辅助损失框架 |38| [#3864](https://github.com/pytorch/torchtitan/pull/3864) | 为 torchtitan 补充 LoggedAuxLoss 辅助损失框架 |
37| [#4474](https://github.com/pytorch/torchtitan/pull/4474) | 补齐部分初始化的 optimizer state,支持完整 checkpoint 恢复 |39| [#4474](https://github.com/pytorch/torchtitan/pull/4474) | 补齐部分初始化的 optimizer state,支持完整 checkpoint 恢复 |
38| [#3985](https://github.com/pytorch/torchtitan/pull/3985) | 为 Trainer 补充 EMA 权重维护及 checkpoint 集成 |40| [#3985](https://github.com/pytorch/torchtitan/pull/3985) | 为 Trainer 补充 EMA 权重维护及 checkpoint 集成 |
41+| [#4529](https://github.com/pytorch/torchtitan/pull/4529) | 限定 EP chunk 具体化使用的符号 hint 范围,对应 `ep_chunk_concretization` |
42+| [#4650](https://github.com/pytorch/torchtitan/pull/4650) | 修正 EP overlap 对 shape query 通信标注的校验,对应 `ep_overlap_shape_queries` |
43+| [#4516](https://github.com/pytorch/torchtitan/pull/4516) | 去重跨 chunk 共享的 EP ready node,对应 `ep_ready_nodes_dedup` |
44+| [#4651](https://github.com/pytorch/torchtitan/pull/4651) | 将同一 root 的 AllToAll dim-0 shape query 保留在 chunk 内,对应 `ep_shape_live_out` |
45+ 
46+四个 EP overlap 补丁的作用、启用方式与排查手段见
47+[`docs/feature_guides/graph_trainer_ep_overlap.md`](../../../docs/feature_guides/graph_trainer_ep_overlap.md)。
39 48 
40对应 PR 合入且 TorchTitan 依赖更新后,应删除相关补丁及导入;全部补丁清理完成后,删除本目录。49对应 PR 合入且 TorchTitan 依赖更新后,应删除相关补丁及导入;全部补丁清理完成后,删除本目录。
@@ -8,4 +8,10 @@ from . import trainer # noqa: F401
8from .components import metrics, optimizer, validate # noqa: F4018from .components import metrics, optimizer, validate # noqa: F401
9from .distributed import context_parallel, full_dtensor, parallel_dims # noqa: F4019from .distributed import context_parallel, full_dtensor, parallel_dims # noqa: F401
10from .distributed.flex_shard import dist_muon # noqa: F40110from .distributed.flex_shard import dist_muon # noqa: F401
11+from .experiments.graph_trainer import ( # noqa: F401
12+ ep_chunk_concretization,
13+ ep_overlap_shape_queries,
14+ ep_ready_nodes_dedup,
15+ ep_shape_live_out,
16+)
11from .models.common import decoder, moe, rope, token_dispatcher # noqa: F40117from .models.common import decoder, moe, rope, token_dispatcher # noqa: F401
@@ -0,0 +1 @@
1+"""Patches for TorchTitan experiments."""
@@ -0,0 +1 @@
1+"""Patches for TorchTitan GraphTrainer."""
@@ -0,0 +1,77 @@
1+# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4529
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+"""Keep independent DSV4 metadata out of EP chunk concretization.
8+ 
9+Filter placeholder extents by the selected chunk symbols before invoking the
10+upstream hint collector helper. Preserve unrelated symbolic values; delegate
11+concretization of selected values to the upstream implementation.
12+ 
13+Remove this module after the TorchTitan dependency includes the PR.
14+"""
15+ 
16+from __future__ import annotations
17+ 
18+from functools import wraps
19+from typing import TYPE_CHECKING
20+ 
21+import torchtitan.experiments.graph_trainer.ep_pass_utils as ep_pass_utils
22+from torchtitan.tools.logging import logger
23+ 
24+if TYPE_CHECKING:
25+ import torch.fx as fx
26+ 
27+ 
28+def _chunk_placeholder_symbol_hints(gm: fx.GraphModule) -> dict[object, int]:
29+ """Collect hints only from placeholder extents containing chunk symbols."""
30+ chunk_symbols = ep_pass_utils.chunk_symbol_hints_for_mode(gm).keys()
31+ hints: dict[object, int] = {}
32+ for node in gm.graph.nodes:
33+ if node.op != "placeholder" or (val := ep_pass_utils.tensor_meta(node)) is None:
34+ continue
35+ for dim, extent in enumerate(val.shape):
36+ symbols = ep_pass_utils.free_symbols(extent)
37+ if not symbols & chunk_symbols:
38+ continue
39+ ep_pass_utils._record_symbols_from_extent(hints, extent, source=f"{node.name}.shape[{dim}]")
40+ return hints
41+ 
42+ 
43+def apply() -> None:
44+ required_helpers = (
45+ "_concretize_value",
46+ "_placeholder_symbol_hints",
47+ "_record_symbols_from_extent",
48+ "chunk_symbol_hints_for_mode",
49+ "free_symbols",
50+ "tensor_meta",
51+ )
52+ if not all(hasattr(ep_pass_utils, name) for name in required_helpers):
53+ logger.warning(
54+ "Skipping GraphTrainer EP chunk concretization patch: required symbolic-shape helpers are unavailable."
55+ )
56+ return
57+ 
58+ current = ep_pass_utils._placeholder_symbol_hints
59+ if getattr(current, "npu_preserves_independent_symbols", False):
60+ return
61+ 
62+ original_concretize_value = ep_pass_utils._concretize_value
63+ 
64+ @wraps(original_concretize_value)
65+ def _concretize_chunk_value(value: object, symbol_hints: dict[object, int]) -> object:
66+ if not ep_pass_utils.free_symbols(value) & symbol_hints.keys():
67+ return value
68+ return original_concretize_value(value, symbol_hints)
69+ 
70+ # pyrefly: ignore [missing-attribute]
71+ _chunk_placeholder_symbol_hints.npu_preserves_independent_symbols = True
72+ ep_pass_utils._placeholder_symbol_hints = _chunk_placeholder_symbol_hints
73+ ep_pass_utils._concretize_value = _concretize_chunk_value
74+ logger.info("Enabled GraphTrainer EP chunk concretization patch for independent dynamic shapes")
75+ 
76+ 
77+apply()
@@ -0,0 +1,61 @@
1+# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4650
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+"""Normalize EP_token_exchange annotations on token-exchange shape queries.
8+ 
9+``aten.sym_size.int`` can inherit the annotation of its all-to-all producer.
10+Remove only that key for queries of an in-body token-exchange launch, then let
11+the upstream collector perform its normal validation and wait normalization.
12+ 
13+Remove this module after the TorchTitan dependency includes the PR.
14+"""
15+ 
16+from __future__ import annotations
17+ 
18+from functools import wraps
19+ 
20+import torch
21+import torch.fx as fx
22+import torchtitan.experiments.graph_trainer.ep_overlap_pass as ep_overlap_pass
23+from torchtitan.experiments.graph_trainer.common_utils import _EP_TOKEN_EXCHANGE
24+from torchtitan.tools.logging import logger
25+ 
26+ 
27+def _is_token_exchange_shape_query(node: fx.Node, node_set: set[fx.Node]) -> bool:
28+ """Return whether a node is a size query on an in-body token exchange."""
29+ if node.op != "call_function" or node.target != torch.ops.aten.sym_size.int or len(node.args) != 2:
30+ return False
31+ producer = node.args[0]
32+ return (
33+ isinstance(producer, fx.Node) and producer in node_set and ep_overlap_pass._is_token_exchange_launch(producer)
34+ )
35+ 
36+ 
37+def apply() -> None:
38+ current = ep_overlap_pass._collect_token_exchanges
39+ if getattr(current, "npu_normalizes_ep_shape_queries", False):
40+ return
41+ 
42+ @wraps(current)
43+ def collect_token_exchanges(body, *, order):
44+ node_set = set(body.nodes)
45+ for node in body.nodes:
46+ if not _is_token_exchange_shape_query(node, node_set):
47+ continue
48+ custom = ep_overlap_pass._custom_meta(node)
49+ if _EP_TOKEN_EXCHANGE in custom:
50+ custom = dict(custom)
51+ del custom[_EP_TOKEN_EXCHANGE]
52+ node.meta["custom"] = custom
53+ return current(body, order=order)
54+ 
55+ # pyrefly: ignore [missing-attribute]
56+ collect_token_exchanges.npu_normalizes_ep_shape_queries = True
57+ ep_overlap_pass._collect_token_exchanges = collect_token_exchanges
58+ logger.info("Enabled GraphTrainer EP overlap shape-query annotation normalization patch")
59+ 
60+ 
61+apply()
@@ -0,0 +1,70 @@
1+# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4516
2+ 
3+# Copyright (c) Meta Platforms, Inc. and affiliates.
4+# All rights reserved.
5+#
6+# This source code is licensed under the BSD-style license found in the
7+# LICENSE file in the root directory of this source tree.
8+ 
9+"""Deduplicate ready nodes across EP-overlap chunk candidates.
10+ 
11+The upstream ``_ready_nodes`` can return a node once for each chunk containing
12+it as a candidate. Keep its scheduling decisions and first-occurrence order,
13+but remove duplicate results before they become cyclic phase-order edges.
14+ 
15+Remove this module after the TorchTitan dependency includes the PR.
16+"""
17+ 
18+from __future__ import annotations
19+ 
20+from typing import TYPE_CHECKING
21+ 
22+import torchtitan.experiments.graph_trainer.ep_overlap_pass as ep_overlap_pass
23+from torchtitan.tools.logging import logger
24+ 
25+if TYPE_CHECKING:
26+ import torch.fx as fx
27+ from torchtitan.experiments.graph_trainer.ep_pass_utils import ChunkedRegion, ChunkOwner
28+ 
29+ 
30+def apply() -> None:
31+ import torchtitan.experiments.graph_trainer.ep_overlap_pass
32+ 
33+ current = torchtitan.experiments.graph_trainer.ep_overlap_pass._ready_nodes
34+ if getattr(current, "npu_dedups_ready_nodes", False):
35+ return
36+ 
37+ def ready_nodes(
38+ *,
39+ candidates_by_chunk: dict[int, set[fx.Node]],
40+ emitted: set[fx.Node],
41+ region: ChunkedRegion,
42+ chunk_order: tuple[int, ...],
43+ order: dict[fx.Node, int],
44+ owner_by_node: dict[fx.Node, ChunkOwner],
45+ include_waits: bool,
46+ ) -> tuple[fx.Node, ...]:
47+ """Return schedulable body nodes, each candidate node at most once."""
48+ ready = []
49+ selected: set[fx.Node] = set()
50+ for chunk_id in chunk_order:
51+ body = region.bodies_by_chunk[chunk_id]
52+ candidates = sorted(candidates_by_chunk.get(chunk_id, set()) - emitted, key=order.__getitem__)
53+ for node in candidates:
54+ if node in selected:
55+ continue
56+ if not include_waits and ep_overlap_pass._is_c10d_functional_node(node):
57+ continue
58+ deps = ep_overlap_pass._body_deps(node, body=body, owner_by_node=owner_by_node)
59+ if all(dep in emitted for dep in deps):
60+ ready.append(node)
61+ selected.add(node)
62+ return tuple(ready)
63+ 
64+ # pyrefly: ignore [missing-attribute]
65+ ready_nodes.npu_dedups_ready_nodes = True
66+ ep_overlap_pass._ready_nodes = ready_nodes
67+ logger.info("Enabled GraphTrainer EP overlap ready-node dedup patch")
68+ 
69+ 
70+apply()
@@ -0,0 +1,66 @@
1+# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4651
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+"""Keep EP AllToAll size queries local to each graph chunk.
8+ 
9+Some dispatcher size queries carry the MoE module FQN but sit outside the
10+region body. Route only same-root ``sym_size.int(all_to_all, 0)`` users to the
11+chunked side after upstream classification. Leave full-value materialization
12+and its validation entirely to the upstream implementation.
13+ 
14+Remove this module after the TorchTitan dependency includes the PR.
15+"""
16+ 
17+from __future__ import annotations
18+ 
19+from functools import wraps
20+ 
21+import torch
22+import torch.fx as fx
23+import torchtitan.experiments.graph_trainer.ep_chunk_pass as ep_chunk_pass
24+from torchtitan.tools.logging import logger
25+ 
26+ 
27+def _is_dim0_all_to_all_size_user(user: fx.Node) -> bool:
28+ """Return whether ``user`` is ``aten.sym_size.int(all_to_all, 0)``."""
29+ if user.op != "call_function" or user.target is not torch.ops.aten.sym_size.int or len(user.args) != 2:
30+ return False
31+ producer, dimension = user.args
32+ return (
33+ isinstance(dimension, int)
34+ and dimension == 0
35+ and isinstance(producer, fx.Node)
36+ and producer.op == "call_function"
37+ and producer.target is torch.ops._c10d_functional.all_to_all_single.default
38+ )
39+ 
40+ 
41+def apply() -> None:
42+ current = ep_chunk_pass._split_live_out_users
43+ if getattr(current, "npu_keeps_ep_shapes_chunk_local", False):
44+ return
45+ 
46+ @wraps(current)
47+ def split_live_out_users(users, plans, producer_region, symbol_hints):
48+ chunked, full = current(users, plans, producer_region, symbol_hints)
49+ moved = tuple(
50+ user
51+ for user in full
52+ if _is_dim0_all_to_all_size_user(user)
53+ and ep_chunk_pass.is_module_fqn_inside_root(ep_chunk_pass._get_module_fqn(user), producer_region.root_fqn)
54+ )
55+ if not moved:
56+ return chunked, full
57+ moved_set = set(moved)
58+ return (*chunked, *moved), tuple(user for user in full if user not in moved_set)
59+ 
60+ # pyrefly: ignore [missing-attribute]
61+ split_live_out_users.npu_keeps_ep_shapes_chunk_local = True
62+ ep_chunk_pass._split_live_out_users = split_live_out_users
63+ logger.info("Enabled GraphTrainer EP AllToAll chunk-local shape live-out patch")
64+ 
65+ 
66+apply()
Rtorchtitan_npu/patches/torchtitan/graph_trainer/functionalize_recompute_mutations.py→torchtitan_npu/patches/torchtitan/experiments/graph_trainer/functionalize_recompute_mutations.py+0-0
File renamed without changes.
Rtorchtitan_npu/patches/torchtitan/graph_trainer/memory_policy.py→torchtitan_npu/patches/torchtitan/experiments/graph_trainer/memory_policy.py+0-0
File renamed without changes.