| @@ -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 | ||
| 41 | 1. 对 MoE 的 dispatch / combine / compute 区域与各子模块 FQN 附加图节点标注(`annotate_moe_ep_regions` + `annotate_module_fqns`),供 bucketing、区域编译等下游 pass 消费。 | 41 | 1. 对 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 模型并行轴下也需要类型标注。 |
| 43 | 3. 无条件应用 `apply_simple_fsdp`:fsdp mesh 在 degree 1 时也存在(`ParallelDims._mesh_exist`),因此单卡下 MixedPrecisionPolicy 的 param_dtype cast 仍然生效。 | 43 | 3. 无条件应用 `apply_simple_fsdp`:fsdp mesh 在 degree 1 时也存在(`ParallelDims._mesh_exist`),因此单卡下 MixedPrecisionPolicy 的 param_dtype cast 仍然生效。 |
| 44 | 4. 按模式应用 `apply_graph_trainer_compile`。 | 44 | 4. 按模式应用 `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 操作) | | ||
| 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 | ||
| 25 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \ | 25 | exec 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 | ||
| 29 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a5.sh" \ | 29 | exec 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 | ||
| 29 | exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \ | 29 | exec 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 \ |
这里把默认 SPMD 后端从 ![]() ![]() | |||
| 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}"] = output | 103 | nodes[f"out{layer_id}"] = output |
| 104 | previous = output | 104 | 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_SAVE | 168 | assert nodes[f"moe{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_SAVE |
| 162 | assert nodes[f"pre{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_RECOMPUTE | 169 | assert nodes[f"pre{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_RECOMPUTE |
| 163 | assert nodes[f"post{layer_id}"].meta["recompute"] == CheckpointPolicy.MUST_SAVE | 170 | 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_SAVE | 172 | 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 names | 178 | assert f"pre{layer_id}_recomputed" in names |
| 171 | assert f"post{layer_id}_recomputed" not in names | 179 | 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_tokens | 40 | / 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.3 | 60 | 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] = -100 | 63 | + labels[0, 1] = -100 |
| 66 | - labels[1, 0, 12] = -100 | 64 | + 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 = 8 | 67 | cfg.loss.num_chunks = 8 |
| @@ -3,6 +3,7 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 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. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | +import pytest | ||
| 6 | import sympy | 7 | import sympy |
| 7 | import torch | 8 | import torch |
| 8 | from torch.fx.experimental.symbolic_shapes import free_symbols, ShapeEnv | 9 | from 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_meta | 58 | inputs.meta["val"] = inputs_meta |
| 57 | metadata.meta["val"] = packed_meta | 59 | 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 | + | ||
| 65 | def test_unrelated_packed_symbol_is_not_concretized() -> None: | 76 | def 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 set | 147 | # 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 a | 165 | # 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 | ||
| 16 | from functools import wraps | 16 | from functools import wraps |
| 17 | -from inspect import getclosurevars, isfunction | 17 | +from inspect import isfunction, signature |
| 18 | 18 | ||
| 19 | import torch | 19 | import torch |
| 20 | import torch.nn as nn | 20 | import torch.nn as nn |
| 21 | -import torch.nn.functional as F | ||
| 22 | import torchtitan.experiments.graph_trainer.chunked_loss | 21 | import torchtitan.experiments.graph_trainer.chunked_loss |
| 22 | +from torch._subclasses.fake_tensor import FakeTensor | ||
| 23 | from torch.distributed.tensor import DTensor, Partial, Shard | 23 | from torch.distributed.tensor import DTensor, Partial, Shard |
| 24 | from torchtitan.experiments.graph_trainer.chunked_loss import ChunkedLossWrapperWithParamGrads | 24 | from torchtitan.experiments.graph_trainer.chunked_loss import ChunkedLossWrapperWithParamGrads |
| 25 | -from torchtitan.experiments.graph_trainer.simple_fsdp import ReplicateComputation | 25 | +from torchtitan.experiments.graph_trainer.simple_fsdp import ReplicateComputation, disable_active_parametrization |
| 26 | from torchtitan.tools.logging import logger | 26 | from 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 | ||
| 32 | class _LocalGradientLMHead(nn.Module): | 32 | class _LocalGradientLMHead(nn.Module): |
| 33 | + _head: nn.Linear | ||
| 33 | sharded_weight: DTensor | 34 | 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 = None | 42 | 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 None | 51 | assert weight.grad is not None |
| @@ -101,12 +105,15 @@ def _can_coalesce(head, pred) -> bool: | |||
| 101 | ): | 105 | ): |
| 102 | return False | 106 | 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 False | 111 | 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: | ||
启用 位置:
证据链(全部读自 pin 的上游源码):
影响:本 PR 把 3 个 graphtrainer 脚本与文档示例的默认后端从 ![]() ![]() | |||
| 110 | return False | 117 | return False |
| 111 | reduce_dtype = parametrization.reduce_dtype or parametrization.param_dtype or weight.dtype | 118 | reduce_dtype = parametrization.reduce_dtype or parametrization.param_dtype or weight.dtype |
| 112 | return reduce_dtype == torch.float32 | 119 | 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_head | 148 | 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/4529 | 1 | # 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. | ||
证据**:该文件并非上游文件的逐字副本—— ![]() ![]() 版权头被从 ![]() ![]() | |||
| 3 | # | 4 | # |
| 4 | # This source code is licensed under the BSD-style license found in the | 5 | # 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 | ||
| 40 | def _owned_chunk_symbol_hints(gm: fx.GraphModule, mode: str) -> dict[object, int]: | 41 | def _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_mode | 136 | original_symbol_hints = ep_pass_utils.chunk_symbol_hints_for_mode |
| 136 | original_populate = ep_chunk_pass.populate_chunk_dim_metadata_pass | 137 | 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_inputs | 138 | original_prepare_inputs = ep_chunk_pass.prepare_ep_overlap_trace_inputs |
| 139 | original_fresh_symbol = ep_chunk_pass._fresh_unbacked_symbol_for_copy | 139 | original_fresh_symbol = ep_chunk_pass._fresh_unbacked_symbol_for_copy |
| 140 | original_placeholder_hints = ep_pass_utils._placeholder_symbol_hints | 140 | 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 | ||
升级之后的还支持在做ep_overlap的时候切batch吗 ![]() ![]() | |||
| 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_value | 225 | ep_pass_utils._concretize_value = concretize_chunk_value |
| 255 | ep_chunk_pass.chunk_symbol_hints_for_mode = chunk_symbol_hints_for_mode | 226 | 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_pass | 227 | 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_inputs | 228 | 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_copy | 229 | 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_pass | 230 | graph_passes.populate_chunk_dim_metadata_pass = populate_chunk_dim_metadata_pass |
| @@ -59,7 +59,7 @@ def _force_boundary_saves( | |||
| 59 | continue | 59 | 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_id | 62 | + not _is_backward_node(user) and is_recomputable(user) and _get_layer_id(user) != produce_layer_id |
这里把 ![]() ![]() _force_boundary_saves 从 > 改为 != 会扩大 MUST_SAVE 的判定集合,实际会增加 id为-1的层的强制保存 ![]() ![]() | |||
| 63 | for user in node.users | 63 | for user in node.users |
| 64 | ): | 64 | ): |
| 65 | node.meta["recompute"] = CheckpointPolicy.MUST_SAVE | 65 | node.meta["recompute"] = CheckpointPolicy.MUST_SAVE |


文档能力矩阵删掉了
spmd_types不支持项,但没有说明「哪个后端被验证过」位置:
docs/feature_guides/deepseek_v4_graph_trainer.md(diffpr1178.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 合并失效。