Merged
fix: adapt DeepSeek-V4 GraphTrainer to TorchTitan dc3985ad #1178
fix: adapt DeepSeek-V4 GraphTrainer to TorchTitan dc3985ad #1178
Merged
jizeweiAdd on Nov 4
Total: 12 files changed+145-73
@@ -39,11 +39,11 @@ GraphTrainer 是 torchtitan 上游 `experiments/graph_trainer/` 中的编译式
39`parallelize_graph_trainer_deepseek_v4`(`parallelize.py`)是 DSV4 专属路径——eager 路径复用 DeepSeek-V3 并行化(DSV4 稀疏注意力分片基于它),而编译路径不能把稀疏注意力计算在 FSDP 下重排,故单独实现:39`parallelize_graph_trainer_deepseek_v4`(`parallelize.py`)是 DSV4 专属路径——eager 路径复用 DeepSeek-V3 并行化(DSV4 稀疏注意力分片基于它),而编译路径不能把稀疏注意力计算在 FSDP 下重排,故单独实现:
40 40 
411. 对 MoE 的 dispatch / combine / compute 区域与各子模块 FQN 附加图节点标注(`annotate_moe_ep_regions` + `annotate_module_fqns`),供 bucketing、区域编译等下游 pass 消费。411. 对 MoE 的 dispatch / combine / compute 区域与各子模块 FQN 附加图节点标注(`annotate_moe_ep_regions` + `annotate_module_fqns`),供 bucketing、区域编译等下游 pass 消费。
42-2. TP / EP 启用时调用 `model.parallelize(parallel_dims)`。42+2. 使用 `spmd_types` 后端或启用 TP / EP 时调用 `model.parallelize(parallel_dims)`;`spmd_types` 即使在 singleton 模型并行轴下也需要类型标注。
433. 无条件应用 `apply_simple_fsdp`:fsdp mesh 在 degree 1 时也存在(`ParallelDims._mesh_exist`),因此单卡下 MixedPrecisionPolicy 的 param_dtype cast 仍然生效。433. 无条件应用 `apply_simple_fsdp`:fsdp mesh 在 degree 1 时也存在(`ParallelDims._mesh_exist`),因此单卡下 MixedPrecisionPolicy 的 param_dtype cast 仍然生效。
444. 按模式应用 `apply_graph_trainer_compile`。444. 按模式应用 `apply_graph_trainer_compile`。
45 45 
46-入口处有两条硬约束:`spmd_types` backend 不支持(simple_fsdp 构建于 raw DTensor 操作之上,该 backend 会报错);TP 启用时 `seq_len` 必须整除 `parallel_dims.seq_len_divisor`(TP degree × 2 x CP degree,`use_local_output=True` 使用 plain tensor)。46+支持 `partial_dtensor` 和 `spmd_types` 后端。`spmd_types` 复用上游 DTensor-backed SimpleFSDP 存储,在模型前向和反向计算侧使用本地 tensor 与 SPMD 类型。入口要求每个 DP rank 的 microbatch token 数能被 `parallel_dims.seq_len_divisor` 整除。
47 47 
48### Graph-safe 改造48### Graph-safe 改造
49 49 
@@ -63,7 +63,7 @@ torchrun --nproc_per_node=8 -m torchtitan.train \
63 --config graph_trainer_deepseek_v4_flash_43layers_16experts \63 --config graph_trainer_deepseek_v4_flash_43layers_16experts \
64 --parallelism.expert-parallel-degree 8 \64 --parallelism.expert-parallel-degree 8 \
65 --parallelism.data-parallel-shard-degree 8 \65 --parallelism.data-parallel-shard-degree 8 \
66- --parallelism.spmd-backend default \66+ --parallelism.spmd-backend spmd_types \
67 --override.imports \67 --override.imports \
68 torchtitan_npu.override.common.rms_norm.asc \68 torchtitan_npu.override.common.rms_norm.asc \
69 torchtitan_npu.override.common.rope.asc_complex \69 torchtitan_npu.override.common.rope.asc_complex \
@@ -83,7 +83,6 @@ torchrun --nproc_per_node=8 -m torchtitan.train \
83| --- | --- |83| --- | --- |
84| 编译模式 | `aot_fx_trace`;NPU 上禁用 `cudagraph_pass` |84| 编译模式 | `aot_fx_trace`;NPU 上禁用 `cudagraph_pass` |
85| 并行组合 | FSDP(含 degree 1)、EP 已验证;TP 要求 `seq_len` 整除 `seq_len_divisor` |85| 并行组合 | FSDP(含 degree 1)、EP 已验证;TP 要求 `seq_len` 整除 `seq_len_divisor` |
86-| `spmd_types` backend | 不支持(simple_fsdp 依赖 raw DTensor 操作) |
zhaowei1936
Outdated

文档能力矩阵删掉了 spmd_types 不支持项,但没有说明「哪个后端被验证过」

位置:docs/feature_guides/deepseek_v4_graph_trainer.md(diff pr1178.diff:5-31) 证据:新正文写「支持 partial_dtensor 和 spmd_types 后端」,同时把 3 个脚本默认值切到 spmd_types;但同一仓库里 examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5_cv_parallel.sh:17 仍传 --parallelism.spmd-backend partial_dtensor。文档未说明二者的差异(例如 P2-1 的 chunk-loss 合并、以及 loss.py:40 的 partial_dtensor 断言只在 DTensor 分支生效)。 建议动作:在 | 并行组合 | 表补一行「默认/已验证后端:spmd_types(本 PR 起);partial_dtensor 保留用于 X 场景」,并注明 TP>1 时 chunk-loss 合并失效。

likedislike
jizewei
jizewei
Nov 5 Comments:
likedislike
87| Context Parallel | 不支持(DSV4 稀疏注意力编译路径未适配 CP) |86| Context Parallel | 不支持(DSV4 稀疏注意力编译路径未适配 CP) |
88| EP overlap(上游实验性 pass) | 已通过patch适配;见 [`graph_trainer_ep_overlap.md`](graph_trainer_ep_overlap.md) |87| EP overlap(上游实验性 pass) | 已通过patch适配;见 [`graph_trainer_ep_overlap.md`](graph_trainer_ep_overlap.md) |
89 88 
@@ -24,6 +24,6 @@ EP_OVERLAP_ARGS=(
24 24 
25exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \25exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \
26 --debug.moe-force-load-balance \26 --debug.moe-force-load-balance \
27- --parallelism.spmd-backend partial_dtensor \27+ --parallelism.spmd-backend spmd_types \
28 "${EP_OVERLAP_ARGS[@]}" \28 "${EP_OVERLAP_ARGS[@]}" \
29 "$@"29 "$@"
@@ -28,7 +28,7 @@ EP_OVERLAP_ARGS=(
28 28 
29exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a5.sh" \29exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a5.sh" \
30 --debug.moe-force-load-balance \30 --debug.moe-force-load-balance \
31- --parallelism.spmd-backend partial_dtensor \31+ --parallelism.spmd-backend spmd_types \
32 --compile.memory-policy dsv4-mhc-moe-save \32 --compile.memory-policy dsv4-mhc-moe-save \
33 --training.steps "${STEPS}" \33 --training.steps "${STEPS}" \
34 "${EP_OVERLAP_ARGS[@]}" \34 "${EP_OVERLAP_ARGS[@]}" \
@@ -28,7 +28,7 @@ EP_OVERLAP_ARGS=(
28 28 
29exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \29exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \
30 --training.num-tokens-per-train-step 2097152 \30 --training.num-tokens-per-train-step 2097152 \
31- --parallelism.spmd-backend partial_dtensor \31+ --parallelism.spmd-backend spmd_types \
xuyujun
xuyujunxuyujunNov 4

这里把默认 SPMD 后端从 partial_dtensor 改成了 spmd_types,三个 GraphTrainer 启动脚本(含两个 A5)和文档示例都一起改了,但 MR 描述完全没有提到这个默认值变更。另外描述里提到 A5 低精度依赖上游 #4934,而当前 pin dc3985ad4 并不包含它——这等于把 A5 默认切到了作者自己认为尚未完全支持的路径。建议 A5 脚本先保持 partial_dtensor,等 pin 进 #4934 后再切;同时把默认值变更写进描述并勾选变更类型。

likedislike
jizewei
jizewei
Nov 5 Comments:
likedislike
32 --training.steps "${STEPS}" \32 --training.steps "${STEPS}" \
33 --debug.moe-force-load-balance \33 --debug.moe-force-load-balance \
34 "${EP_OVERLAP_ARGS[@]}" \34 "${EP_OVERLAP_ARGS[@]}" \
@@ -103,11 +103,18 @@ def _build_graph() -> tuple[fx.GraphModule, dict[str, fx.Node]]:
103 nodes[f"out{layer_id}"] = output103 nodes[f"out{layer_id}"] = output
104 previous = output104 previous = output
105 105 
106+ epilogue = _node(
107+ graph,
108+ "epilogue",
109+ torch.ops.aten.tanh.default,
110+ (previous,),
111+ "norm",
112+ )
106 nodes["bwd_output"] = _node(113 nodes["bwd_output"] = _node(
107 graph,114 graph,
108 "bwd_output",115 "bwd_output",
109 torch.ops.aten.mul.Tensor,116 torch.ops.aten.mul.Tensor,
110- (previous, grad),117+ (epilogue, grad),
111 "layers.7.backward",118 "layers.7.backward",
112 backward=True,119 backward=True,
113 )120 )
@@ -161,11 +168,12 @@ def test_dsv4_mhc_layer_boundaries_and_moe_save() -> None:
161 assert nodes[f"moe{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_SAVE168 assert nodes[f"moe{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_SAVE
162 assert nodes[f"pre{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_RECOMPUTE169 assert nodes[f"pre{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_RECOMPUTE
163 assert nodes[f"post{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_SAVE170 assert nodes[f"post{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_SAVE
164- for layer_id in range(7):171+ for layer_id in range(8):
165 assert nodes[f"out{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_SAVE172 assert nodes[f"out{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_SAVE
166 173 
167 gm = selective_activation_remat_pass(gm)174 gm = selective_activation_remat_pass(gm)
168 names = {node.name for node in gm.graph.nodes}175 names = {node.name for node in gm.graph.nodes}
176+ assert "out7_recomputed" not in names
169 for layer_id in (0, 4):177 for layer_id in (0, 4):
170 assert f"pre{layer_id}_recomputed" in names178 assert f"pre{layer_id}_recomputed" in names
171 assert f"post{layer_id}_recomputed" not in names179 assert f"post{layer_id}_recomputed" not in names
@@ -173,3 +181,25 @@ def test_dsv4_mhc_layer_boundaries_and_moe_save() -> None:
173 assert f"pre{layer_id}_recomputed" in {node.name for node in nodes[f"bwd_pre{layer_id}"].all_input_nodes}181 assert f"pre{layer_id}_recomputed" in {node.name for node in nodes[f"bwd_pre{layer_id}"].all_input_nodes}
174 gm.graph.lint()182 gm.graph.lint()
175 torch.testing.assert_close(gm(*inputs), expected, rtol=0, atol=0)183 torch.testing.assert_close(gm(*inputs), expected, rtol=0, atol=0)
184+ 
185+ 
186+def test_full_recompute_save_selectors_preserve_selected_projections() -> None:
187+ gm, nodes = _build_graph()
188+ inputs = tuple(torch.full((2, 2), 0.1) for _ in range(3))
189+ expected = gm(*inputs)
190+ config = SimpleNamespace(
191+ compile=SimpleNamespace(
192+ memory_policy="full",
193+ full_recompute_save_ops="layers.*.attention.wo_b::aten.matmul.default",
194+ ),
195+ )
196+ 
197+ gm = tag_with_memory_policy_pass(gm, config=config)
198+ 
199+ for layer_id in (0, 4):
200+ assert nodes[f"wo_b{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_SAVE
201+ assert nodes[f"pre{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_RECOMPUTE
202+ 
203+ gm = selective_activation_remat_pass(gm)
204+ gm.graph.lint()
205+ torch.testing.assert_close(gm(*inputs), expected, rtol=0, atol=0)
@@ -0,0 +1,53 @@
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+import torch
7+import torch.distributed as dist
8+from torch.distributed.tensor import DTensor
9+from torchtitan.distributed import ParallelDims
10+from torchtitan.distributed.utils import get_spmd_backend, get_spmd_context, set_spmd_backend
11+ 
12+from torchtitan_npu.models.deepseek_v4.config_registry import graph_trainer_deepseek_v4_debugmodel
13+ 
14+ 
15+def test_graph_trainer_spmd_types_initializes_singleton_model_parallel_axes(tmp_path, monkeypatch):
16+ monkeypatch.setattr("torchtitan.distributed.parallel_dims.device_type", "cpu")
17+ # EP annotations wrap shared dispatcher methods for the lifetime of the process.
18+ monkeypatch.setattr("torchtitan_npu.models.deepseek_v4.parallelize.annotate_moe_ep_regions", lambda: None)
19+ previous_backend = get_spmd_backend()
20+ dist.init_process_group("gloo", init_method=f"file://{tmp_path / 'rendezvous'}", world_size=1, rank=0)
21+ try:
22+ set_spmd_backend("spmd_types")
23+ config = graph_trainer_deepseek_v4_debugmodel()
24+ config.parallelism.spmd_backend = "spmd_types"
25+ config.training.mixed_precision_param = "float32"
26+ config.model_spec.model.layers = config.model_spec.model.layers[:1]
27+ config.model_spec.model.n_layers = 1
28+ config.model_spec.model.compress_ratios = (1,)
29+ config.model_spec.model.vocab_size = 128
30+ config.model_spec.model.tok_embeddings.num_embeddings = 128
31+ config.model_spec.model.lm_head.out_features = 128
32+ config.model_spec.model.update_from_config(config=config)
33+ dims = ParallelDims(dp_replicate=1, dp_shard=1, cp=1, tp=1, pp=1, ep=1, world_size=1)
34+ with get_spmd_context(parallel_dims=dims)():
35+ model = config.model_spec.model.build()
36+ model = config.model_spec.parallelize_fn(
37+ model,
38+ parallel_dims=dims,
39+ training=config.training,
40+ parallelism=config.parallelism,
41+ compile_config=config.compile,
42+ ac_config=config.activation_checkpoint,
43+ dump_folder=str(tmp_path),
44+ )
45+ projection = model.layers["0"].attention.wq_a
46+ assert projection._parallelized
47+ assert isinstance(projection._parameters["weight"], DTensor)
48+ assert not isinstance(projection.weight, DTensor)
49+ projection.weight.square().sum().backward()
50+ assert isinstance(projection._parameters["weight"].grad, DTensor)
51+ finally:
52+ set_spmd_backend(previous_backend)
53+ dist.destroy_process_group()
@@ -32,15 +32,13 @@ def _dense_reference(hidden, labels, weight, num_chunks, valid_tokens):
32 # this reference uses no chunk-loss wrapper or distributed collectives.32 # this reference uses no chunk-loss wrapper or distributed collectives.
33 chunk_losses = [33 chunk_losses = [
34 F.cross_entropy(34 F.cross_entropy(
35- F.linear(h, weight.to(hidden.dtype)).float().flatten(0, 1),35+ F.linear(h, weight.to(hidden.dtype)).float(),
36- target.flatten(),36+ target,
37 reduction="sum",37 reduction="sum",
38 ignore_index=-100,38 ignore_index=-100,
39 )39 )
40 / valid_tokens40 / valid_tokens
41- for h, target in zip(41+ for h, target in zip(rank_hidden.chunk(num_chunks), rank_labels.chunk(num_chunks), strict=True)
42- rank_hidden.chunk(num_chunks, dim=1), rank_labels.chunk(num_chunks, dim=1), strict=True
43- )
44 ]42 ]
45 losses.append(torch.stack(chunk_losses).sum())43 losses.append(torch.stack(chunk_losses).sum())
46 hidden_grad, weight_grad = torch.autograd.grad(torch.stack(losses).sum(), (hidden, weight))44 hidden_grad, weight_grad = torch.autograd.grad(torch.stack(losses).sum(), (hidden, weight))
@@ -60,10 +58,10 @@ def _assert_coalesced_microbatch_gradients(rank, rendezvous, dtype):
60 mesh = init_device_mesh("cpu", (2,), mesh_dim_names=("dp_shard",))58 mesh = init_device_mesh("cpu", (2,), mesh_dim_names=("dp_shard",))
61 generator = torch.Generator().manual_seed(42)59 generator = torch.Generator().manual_seed(42)
62 weight = torch.randn(13, 4, generator=generator) * 0.360 weight = torch.randn(13, 4, generator=generator) * 0.3
63- hidden = torch.randn(2, 1, 16, 4, generator=generator).to(dtype)61+ hidden = torch.randn(2, 16, 4, generator=generator).to(dtype)
64- labels = torch.randint(13, (2, 1, 16), generator=generator)62+ labels = torch.randint(13, (2, 16), generator=generator)
65- labels[0, 0, 1] = -10063+ labels[0, 1] = -100
66- labels[1, 0, 12] = -10064+ labels[1, 12] = -100
67 valid_tokens = (labels != -100).sum()65 valid_tokens = (labels != -100).sum()
68 cfg = graph_trainer_deepseek_v4_flash_43layers_16experts()66 cfg = graph_trainer_deepseek_v4_flash_43layers_16experts()
69 cfg.loss.num_chunks = 867 cfg.loss.num_chunks = 8
@@ -3,6 +3,7 @@
3# This source code is licensed under the BSD-style license found in the3# This source code is licensed under the BSD-style license found in the
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6+import pytest
6import sympy7import sympy
7import torch8import torch
8from torch.fx.experimental.symbolic_shapes import free_symbols, ShapeEnv9from torch.fx.experimental.symbolic_shapes import free_symbols, ShapeEnv
@@ -33,7 +34,8 @@ def test_patch_updates_cached_graph_trainer_bindings() -> None:
33 )34 )
34 35 
35 36 
36-def test_owned_chunk_symbols_exclude_independent_packed_metadata() -> None:37+@pytest.mark.parametrize("mode", ["batch", "seq"])
38+def test_owned_chunk_symbols_exclude_independent_packed_metadata(mode: str) -> None:
37 shape_env = ShapeEnv()39 shape_env = ShapeEnv()
38 fake_mode = torch._subclasses.FakeTensorMode(40 fake_mode = torch._subclasses.FakeTensorMode(
39 allow_non_fake_inputs=True,41 allow_non_fake_inputs=True,
@@ -44,9 +46,9 @@ def test_owned_chunk_symbols_exclude_independent_packed_metadata() -> None:
44 packed = shape_env.create_unbacked_symint()46 packed = shape_env.create_unbacked_symint()
45 torch._dynamo.override_optimization_hint(batch, 2)47 torch._dynamo.override_optimization_hint(batch, 2)
46 torch._dynamo.override_optimization_hint(packed, 2048)48 torch._dynamo.override_optimization_hint(packed, 2048)
47- inputs_meta = torch.empty(batch, 4096, device="cuda")49+ inputs_meta = torch.empty(batch, device="cuda")
48 packed_meta = torch.empty(packed, device="cuda")50 packed_meta = torch.empty(packed, device="cuda")
49- setattr(inputs_meta, "_dynamo_shape_ids", {0: "torchtitan_chunk_batch"})51+ setattr(inputs_meta, "_dynamo_shape_ids", {0: f"torchtitan_chunk_{mode}"})
50 52 
51 graph = torch.fx.Graph()53 graph = torch.fx.Graph()
52 inputs = graph.placeholder("inputs")54 inputs = graph.placeholder("inputs")
@@ -56,12 +58,21 @@ def test_owned_chunk_symbols_exclude_independent_packed_metadata() -> None:
56 inputs.meta["val"] = inputs_meta58 inputs.meta["val"] = inputs_meta
57 metadata.meta["val"] = packed_meta59 metadata.meta["val"] = packed_meta
58 60 
59- hints = ep_chunk_concretization._owned_chunk_symbol_hints(gm, "batch")61+ hints = ep_chunk_concretization._owned_chunk_symbol_hints(gm, mode)
60 62 
61 assert set(hints) == free_symbols(batch)63 assert set(hints) == free_symbols(batch)
62 assert not (set(hints) & free_symbols(packed))64 assert not (set(hints) & free_symbols(packed))
63 65 
64 66 
67+@pytest.mark.parametrize("mode", ["batch", "seq"])
68+def test_flat_token_inputs_are_marked_for_graph_chunking(mode: str) -> None:
69+ tokens = torch.zeros(4096, dtype=torch.int64)
70+ 
71+ ep_chunk_pass.mark_chunk_dynamic_dims(tokens, mode=mode)
72+ 
73+ assert tokens._dynamo_shape_ids == {0: f"torchtitan_chunk_{mode}"}
74+ 
75+ 
65def test_unrelated_packed_symbol_is_not_concretized() -> None:76def test_unrelated_packed_symbol_is_not_concretized() -> None:
66 shape_env = ShapeEnv()77 shape_env = ShapeEnv()
67 fake_mode = torch._subclasses.FakeTensorMode(78 fake_mode = torch._subclasses.FakeTensorMode(
@@ -144,11 +144,6 @@ def parallelize_graph_trainer_deepseek_v4(
144 ac_config: ActivationCheckpointingConfig,144 ac_config: ActivationCheckpointingConfig,
145 dump_folder: str,145 dump_folder: str,
146):146):
147- # The graph_trainer simple_fsdp wrapper is built on raw DTensor ops
148- # (``distribute_tensor`` / ``tensor._spec``) and errors under the
149- # spmd_types backend; only the eager path supports that backend for now.
150- assert get_spmd_backend() != "spmd_types", "The GraphTrainer path does not yet support the spmd_types backend."
151- 
152 # TP currently cannot handle uneven seq_len because we set147 # TP currently cannot handle uneven seq_len because we set
153 # ``use_local_output=True`` to use plain Tensors for legacy reasons.148 # ``use_local_output=True`` to use plain Tensors for legacy reasons.
154 assert training.num_tokens_per_microbatch_per_dp_rank % parallel_dims.seq_len_divisor == 0, f"""149 assert training.num_tokens_per_microbatch_per_dp_rank % parallel_dims.seq_len_divisor == 0, f"""
@@ -164,7 +159,7 @@ def parallelize_graph_trainer_deepseek_v4(
164 159 
165 annotate_deepseek_v4(model)160 annotate_deepseek_v4(model)
166 161 
167- if parallel_dims.tp_enabled or parallel_dims.ep_enabled:162+ if get_spmd_backend() == "spmd_types" or parallel_dims.tp_enabled or parallel_dims.ep_enabled:
168 model.parallelize(parallel_dims)163 model.parallelize(parallel_dims)
169 164 
170 # Apply simple_fsdp unconditionally. The ``fsdp`` mesh always exists with a165 # Apply simple_fsdp unconditionally. The ``fsdp`` mesh always exists with a
@@ -14,15 +14,15 @@ Remove this module after the TorchTitan dependency includes the PR.
14"""14"""
15 15 
16from functools import wraps16from functools import wraps
17-from inspect import getclosurevars, isfunction17+from inspect import isfunction, signature
18 18 
19import torch19import torch
20import torch.nn as nn20import torch.nn as nn
21-import torch.nn.functional as F
22import torchtitan.experiments.graph_trainer.chunked_loss21import torchtitan.experiments.graph_trainer.chunked_loss
22+from torch._subclasses.fake_tensor import FakeTensor
23from torch.distributed.tensor import DTensor, Partial, Shard23from torch.distributed.tensor import DTensor, Partial, Shard
24from torchtitan.experiments.graph_trainer.chunked_loss import ChunkedLossWrapperWithParamGrads24from torchtitan.experiments.graph_trainer.chunked_loss import ChunkedLossWrapperWithParamGrads
25-from torchtitan.experiments.graph_trainer.simple_fsdp import ReplicateComputation25+from torchtitan.experiments.graph_trainer.simple_fsdp import ReplicateComputation, disable_active_parametrization
26from torchtitan.tools.logging import logger26from torchtitan.tools.logging import logger
27 27 
28_original_call = ChunkedLossWrapperWithParamGrads.__call__28_original_call = ChunkedLossWrapperWithParamGrads.__call__
@@ -30,18 +30,22 @@ _original_gradient_backprop = ChunkedLossWrapperWithParamGrads._gradient_backpro
30 30 
31 31 
32class _LocalGradientLMHead(nn.Module):32class _LocalGradientLMHead(nn.Module):
33+ _head: nn.Linear
33 sharded_weight: DTensor34 sharded_weight: DTensor
34 35 
35- def __init__(self, weight: torch.Tensor, sharded_weight: DTensor):36+ def __init__(self, head: nn.Linear, weight: torch.Tensor, sharded_weight: DTensor):
36 super().__init__()37 super().__init__()
37 self.weight = nn.Parameter(weight.detach(), requires_grad=sharded_weight.requires_grad)38 self.weight = nn.Parameter(weight.detach(), requires_grad=sharded_weight.requires_grad)
38 # Keep the original parameter out of this temporary module's parameters.39 # Keep the original parameter out of this temporary module's parameters.
39 object.__setattr__(self, "sharded_weight", sharded_weight)40 object.__setattr__(self, "sharded_weight", sharded_weight)
41+ object.__setattr__(self, "_head", head)
40 self.accumulated_grad: torch.Tensor | None = None42 self.accumulated_grad: torch.Tensor | None = None
41 self.grad_hook = self.weight.register_post_accumulate_grad_hook(self._accumulate_grad)43 self.grad_hook = self.weight.register_post_accumulate_grad_hook(self._accumulate_grad)
42 44 
43 def forward(self, hidden: torch.Tensor) -> torch.Tensor:45 def forward(self, hidden: torch.Tensor) -> torch.Tensor:
44- return F.linear(hidden, self.weight)46+ # Keep the head's model-parallel forward wrappers with the gathered weight.
47+ with disable_active_parametrization():
48+ return torch.func.functional_call(self._head, {"weight": self.weight}, (hidden,))
45 49 
46 def _accumulate_grad(self, weight: torch.Tensor) -> None:50 def _accumulate_grad(self, weight: torch.Tensor) -> None:
47 assert weight.grad is not None51 assert weight.grad is not None
@@ -101,12 +105,15 @@ def _can_coalesce(head, pred) -> bool:
101 ):105 ):
102 return False106 return False
103 107 
104- # SimpleFSDP v0.3.0 keeps its precision policy in the weight getter closure.108+ # The pinned SimpleFSDP binds each parameter's wrapper as a getter default.
105 weight_property = getattr(type(head), "weight", None)109 weight_property = getattr(type(head), "weight", None)
106 if not isinstance(weight_property, property) or not isfunction(weight_property.fget):110 if not isinstance(weight_property, property) or not isfunction(weight_property.fget):
107 return False111 return False
108- parametrization = getclosurevars(weight_property.fget).nonlocals.get("parametrization")112+ parametrization = signature(weight_property.fget).parameters.get("p")
109- if not isinstance(parametrization, ReplicateComputation) or parametrization.full_dtensor:113+ if parametrization is None or not isinstance(parametrization.default, ReplicateComputation):
114+ return False
115+ parametrization = parametrization.default
116+ if parametrization.device_mesh != weight.device_mesh or parametrization.non_dp_mesh_types:
zhaowei1936

启用 spmd_types 后,chunk-loss 的 RS 合并会在 TP>1 时静默关闭

位置:torchtitan_npu/patches/torchtitan/experiments/graph_trainer/chunked_loss.py:116

if parametrization.device_mesh != weight.device_mesh or parametrization.non_dp_mesh_types:
    return False  # [!code warning] tp>1 时该项恒为真 → 直接放弃合并

证据链(全部读自 pin 的上游源码):

  • common_utils.apply_simple_fsdp 在 use_spmd_types 时把 non_dp_mesh=(parallel_dims.get_optional_mesh("tp") if use_spmd_types else None) 传给 data_parallel。
  • simple_fsdp.data_parallel:441-447 在 get_spmd_backend() == "spmd_types" 时对每个参数调用 _prepare_spmd_parameter_for_fsdp,后者(:98-102)对 non_dp_mesh 的每个轴都写一条 non_dp_mesh_types[axis] = ...(即使是 spmd.I 这种无需通信的类型也写)。因此 tp > 1 时该 dict 必然非空,_can_coalesce 恒 False。
  • partial_dtensor 后端下 non_dp_mesh 为 None(:480-484),non_dp_mesh_types 为 None → 该分支不触发,合并仍然生效。

影响:本 PR 把 3 个 graphtrainer 脚本与文档示例的默认后端从 partial_dtensor 切到 spmd_types,于是 --parallelism.tensor-parallel-degree > 1 的组合会从「RS 合并(1 次 reduce-scatter)」退化为「每 chunk 一次 RS」。这不是回归(base 上该组合直接被 assert 拦住),但是新可达路径上的静默性能退化,只在首次调用时打一条 logger.warning,端到端 loss 完全正确,不会被任何数值验证发现。 建议动作:二选一——(a) 若 TP>1 的 head 布局确应支持合并,把判据从「non_dp_mesh_types 非空」收窄为「存在会导致 BWD 额外通信的轴类型」(如 spmd.R);(b) 若不打算支持,在文档的「并行组合」表里显式写明「spmd_types + TP>1 时 chunk-loss RS 合并失效」,并给 _can_coalesce 的 warning 加上具体不满足项,便于现场定位。

likedislike
jizewei
jizewei
Nov 5 Comments:
likedislike
110 return False117 return False
111 reduce_dtype = parametrization.reduce_dtype or parametrization.param_dtype or weight.dtype118 reduce_dtype = parametrization.reduce_dtype or parametrization.param_dtype or weight.dtype
112 return reduce_dtype == torch.float32119 return reduce_dtype == torch.float32
@@ -118,17 +125,26 @@ def _coalesced_call(self, pred, labels, global_valid_tokens=None, **loss_inputs)
118 if type(self) is not ChunkedLossWrapperWithParamGrads or not pred.requires_grad or head is None:125 if type(self) is not ChunkedLossWrapperWithParamGrads or not pred.requires_grad or head is None:
119 return _original_call(self, pred, labels, global_valid_tokens, **loss_inputs)126 return _original_call(self, pred, labels, global_valid_tokens, **loss_inputs)
120 supported = _can_coalesce(head, pred)127 supported = _can_coalesce(head, pred)
128+ weight = head.weight if supported else None
129+ supported = type(weight) in (torch.Tensor, FakeTensor)
121 if not getattr(self, "_coalesced_rs_logged", False):130 if not getattr(self, "_coalesced_rs_logged", False):
122 if supported:131 if supported:
123 logger.info("[PATCH] GraphTrainer chunked loss: coalescing SimpleFSDP gradients before reduce-scatter")132 logger.info("[PATCH] GraphTrainer chunked loss: coalescing SimpleFSDP gradients before reduce-scatter")
124 else:133 else:
125- logger.warning("[PATCH] Chunk-loss RS coalescing is unsupported for this head/layout; using upstream loss")134+ sharded_weight = head._parameters.get("weight")
135+ logger.warning(
136+ "[PATCH] Chunk-loss RS coalescing is unsupported for this head/layout; using upstream loss. "
137+ "TP > 1 is unsupported. Head weight mesh=%s, placements=%s, dtype=%s",
138+ getattr(sharded_weight, "device_mesh", None),
139+ getattr(sharded_weight, "placements", None),
140+ getattr(sharded_weight, "dtype", None),
141+ )
126 self._coalesced_rs_logged = True # pyrefly: ignore[missing-attribute]142 self._coalesced_rs_logged = True # pyrefly: ignore[missing-attribute]
127- if not supported:143+ if not supported or weight is None:
128 return _original_call(self, pred, labels, global_valid_tokens, **loss_inputs)144 return _original_call(self, pred, labels, global_valid_tokens, **loss_inputs)
129 145 
130 # Preserve the original all-gather and compute dtype, but defer gradient sync.146 # Preserve the original all-gather and compute dtype, but defer gradient sync.
131- local_head = _LocalGradientLMHead(head.weight, head._parameters["weight"])147+ local_head = _LocalGradientLMHead(head, weight, head._parameters["weight"])
132 self.lm_head = local_head148 self.lm_head = local_head
133 try:149 try:
134 return _original_call(self, pred, labels, global_valid_tokens, **loss_inputs)150 return _original_call(self, pred, labels, global_valid_tokens, **loss_inputs)
@@ -1,5 +1,6 @@
1# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/45291# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4529
2# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.2# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
3+# Copyright (c) Meta Platforms, Inc. and affiliates.
zhaowei1936xuyujun

证据**:该文件并非上游文件的逐字副本——_DROPPED_METADATA_KEYS(:38)、_restore_placeholder_shape_ids(:63)、_drop_attention_masks(:82)、_is_infinite_bound/_half_size_bound(:98-109)、fresh_unbacked_symbol_for_copy(:179) 都是本仓为 DSV4 packed/varlen metadata 写的自有逻辑(memory_policy.py:1-5 那种「逐字复制上游」的文件用 Meta 头是仓库既有约定,本文件不属此列)。 建议动作:由作者与合规(OAT.xml / scripts/ 合规流程)确认头部策略;若维持 Meta 头,请在文件 docstring 里声明「upstream-derived, contains Huawei modifications」,避免后续把本仓自有逻辑当作上游代码回推/删除。

likedislike
jizewei
jizewei
Nov 5 Comments:
likedislike
xuyujunxuyujunNov 4

版权头被从 Copyright (c) 2026 Huawei Technologies Co., Ltd. 改成了 Copyright (c) Meta Platforms, Inc. and affiliates.,但本文件是 NPU 侧的本地 patch 代码。建议改回华为版权头;若其中确有从上游直接复制的片段,请按仓库规范并列标注双版权,而不是整体替换。run #2177 的 SCA「no pass」很可能就指向这里。

likedislike
jizewei
jizewei
Nov 5 Comments:
likedislike
3#4#
4# This source code is licensed under the BSD-style license found in the5# 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# LICENSE file in the root directory of this source tree.
@@ -39,9 +40,9 @@ _DROPPED_METADATA_KEYS = frozenset({"attention_masks", "attention_metadata"})
39 40 
40def _owned_chunk_symbol_hints(gm: fx.GraphModule, mode: str) -> dict[object, int]:41def _owned_chunk_symbol_hints(gm: fx.GraphModule, mode: str) -> dict[object, int]:
41 """Collect symbols only from dimensions carrying the EP chunk shape ID."""42 """Collect symbols only from dimensions carrying the EP chunk shape ID."""
42- dim = {"batch": 0, "seq": 1}.get(mode)43+ if mode not in ("batch", "seq"):
43- if dim is None:
44 raise ValueError(f"Unknown chunk mode: {mode!r}")44 raise ValueError(f"Unknown chunk mode: {mode!r}")
45+ dim = 0
45 expected_shape_id = f"torchtitan_chunk_{mode}"46 expected_shape_id = f"torchtitan_chunk_{mode}"
46 hints: dict[object, int] = {}47 hints: dict[object, int] = {}
47 for node in gm.graph.nodes:48 for node in gm.graph.nodes:
@@ -134,7 +135,6 @@ def apply() -> None:
134 135 
135 original_symbol_hints = ep_pass_utils.chunk_symbol_hints_for_mode136 original_symbol_hints = ep_pass_utils.chunk_symbol_hints_for_mode
136 original_populate = ep_chunk_pass.populate_chunk_dim_metadata_pass137 original_populate = ep_chunk_pass.populate_chunk_dim_metadata_pass
137- original_mark_dynamic = ep_chunk_pass.mark_chunk_dynamic_dims
138 original_prepare_inputs = ep_chunk_pass.prepare_ep_overlap_trace_inputs138 original_prepare_inputs = ep_chunk_pass.prepare_ep_overlap_trace_inputs
139 original_fresh_symbol = ep_chunk_pass._fresh_unbacked_symbol_for_copy139 original_fresh_symbol = ep_chunk_pass._fresh_unbacked_symbol_for_copy
140 original_placeholder_hints = ep_pass_utils._placeholder_symbol_hints140 original_placeholder_hints = ep_pass_utils._placeholder_symbol_hints
@@ -165,35 +165,6 @@ def apply() -> None:
165 )165 )
166 return original_populate(gm, example_inputs, mode=mode)166 return original_populate(gm, example_inputs, mode=mode)
167 167 
zhangjianshe

升级之后的还支持在做ep_overlap的时候切batch吗

likedislike
jizewei
jizewei
Nov 4 Comments:
likedislike
168- @wraps(original_mark_dynamic)
169- def mark_chunk_dynamic_dims(tensor: torch.Tensor, *, mode: EpOverlapChunkDim) -> None:
170- from torch._dynamo.decorators import mark_unbacked
171- 
172- dim = {"batch": 0, "seq": 1}.get(mode)
173- if dim is None:
174- raise ValueError(f"Unknown chunk mode: {mode!r}")
175- if tensor.dim() <= dim:
176- raise ValueError(f"Cannot mark {mode} dim {dim} for shape {tuple(tensor.shape)}.")
177- extent = int(tensor.shape[dim])
178- if extent < 2 or extent % 2:
179- raise ValueError(
180- "EP overlap graph chunking requires an even selected dimension, "
181- f"got {mode} size {extent} for shape {tuple(tensor.shape)}."
182- )
183- lower, upper = extent // 2, extent
184- if mode == "batch":
185- lower = max(2, lower)
186- upper = max(upper, lower + 1)
187- mark_unbacked(
188- tensor,
189- dim,
190- hint_override=extent,
191- min=lower,
192- max=upper,
193- specialize_on=[lambda value, extent=extent: value == extent],
194- shape_id=f"torchtitan_chunk_{mode}",
195- )
196- 
197 @wraps(original_prepare_inputs)168 @wraps(original_prepare_inputs)
198 def prepare_ep_overlap_trace_inputs(169 def prepare_ep_overlap_trace_inputs(
199 compile_config: Any,170 compile_config: Any,
@@ -254,7 +225,6 @@ def apply() -> None:
254 ep_pass_utils._concretize_value = concretize_chunk_value225 ep_pass_utils._concretize_value = concretize_chunk_value
255 ep_chunk_pass.chunk_symbol_hints_for_mode = chunk_symbol_hints_for_mode226 ep_chunk_pass.chunk_symbol_hints_for_mode = chunk_symbol_hints_for_mode
256 ep_chunk_pass.populate_chunk_dim_metadata_pass = populate_chunk_dim_metadata_pass227 ep_chunk_pass.populate_chunk_dim_metadata_pass = populate_chunk_dim_metadata_pass
257- ep_chunk_pass.mark_chunk_dynamic_dims = mark_chunk_dynamic_dims
258 ep_chunk_pass.prepare_ep_overlap_trace_inputs = prepare_ep_overlap_trace_inputs228 ep_chunk_pass.prepare_ep_overlap_trace_inputs = prepare_ep_overlap_trace_inputs
259 ep_chunk_pass._fresh_unbacked_symbol_for_copy = fresh_unbacked_symbol_for_copy229 ep_chunk_pass._fresh_unbacked_symbol_for_copy = fresh_unbacked_symbol_for_copy
260 graph_passes.populate_chunk_dim_metadata_pass = populate_chunk_dim_metadata_pass230 graph_passes.populate_chunk_dim_metadata_pass = populate_chunk_dim_metadata_pass
@@ -59,7 +59,7 @@ def _force_boundary_saves(
59 continue59 continue
60 60 
61 if any(61 if any(
62- not _is_backward_node(user) and is_recomputable(user) and _get_layer_id(user) > produce_layer_id62+ not _is_backward_node(user) and is_recomputable(user) and _get_layer_id(user) != produce_layer_id
xuyujunYueGuoDora
xuyujunxuyujunNov 4

这里把 > 改成 !=,会多强制保存一类节点。上游 common_utils.py:258 的 _get_layer_id 对任何不在 layers.N 下的节点返回 _NOT_IN_LAYERS = -1(定义在 :187),因此边界层 N 的 producer 在其 user 为 -1(未标注节点,或 norm/output)时现在会被置为 MUST_SAVE,而原来的 > 不会。这会增加 saved activation 和 NPU HBM 占用。如果这是有意的,建议在 MR 描述里给出显存对比数据;如果只是想放行 epilogue,建议收紧为 user_layer is None or user_layer > produce_layer_id,并补一条「层内未标注消费者不被强制保存」的用例。

likedislike
jizewei
jizewei
Nov 5 Comments:
likedislike

_force_boundary_saves 从 > 改为 != 会扩大 MUST_SAVE 的判定集合,实际会增加 id为-1的层的强制保存

likedislike
jizewei
jizewei
Nov 5 Comments:
likedislike
63 for user in node.users63 for user in node.users
64 ):64 ):
65 node.meta["recompute"] = CheckpointPolicy.MUST_SAVE65 node.meta["recompute"] = CheckpointPolicy.MUST_SAVE