Repository navigation
[spmd_types] remove DTensor FWD/BWD usage - #4419
Merged
Merged
Conversation
[ghstack-poisoned]
This was referenced Sep 2, 2026
[ghstack-poisoned]
pianpwk
added a commit
that referenced
this pull request
Sep 2, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0) (oldest at bottom): * #4419 * #4416 * __->__ #4325 ## human-written section Enables graph trainer for spmd_types backend - simple FSDP is kept in DTensor, we just unwrap to plain tensor params (spmd_types) for fwd/bwd. DTensor-less FSDP is doable and prototyped, but needs more orthogonal support (padding uneven params, DCP, grad norm clipping, etc.) - precompile in DTensor backend would (tensor subclass) unflatten DTensor inputs/params, accessing PGs for collectives from their DeviceMesh attributes. In spmd_types the PGs are from ambient state, and precompile graph patterns are different when the owning meshes aren't graph inputs (PGs become opaque objects). To match patterns & make bucketing happy, I preregister the meshes as graph inputs - generally tested through perf/numerics, not sure if any features missed - typechecking is WIP ## Changes - Reuse GraphTrainer's DTensor-backed SimpleFSDP implementation with an `spmd_types` model-parallel backend. - Preserve each parameter's `SpmdType` through FSDP wrapping and materialize replicated non-DP axes with `spmd.redistribute`. - Pass concrete mesh inputs through tracing and precompile so functional collectives resolve runtime process groups. ## Test environment | Item | Value | | --- | --- | | Test commit | This temporary commit | | Baseline | `main` (`partial_dtensor`) | | GPUs | 8x NVIDIA H100 80 GB | | Numerics | `--debug.seed=42 --debug.deterministic` | | Performance | 8-GPU sweep: 20 steps, discard 1-5, 3 repeats; Qwen control: 100 steps, discard 1-20 | ## Backend parity Both backends loaded the same seed checkpoint and ran with `--debug.seed=42 --debug.deterministic`. Full-precision TensorBoard values were compared rather than rounded stdout. | Model | Parallelism | Steps | Max loss diff | Max grad-norm diff | Result | | --- | --- | ---: | ---: | ---: | --- | | Llama3 | FSDP4 + TP2 | 10 | 0 | 0 | Bitwise equal | | Qwen3 MoE | FSDP4 + TP2 + EP4 | 10 | 0 | 0 | Bitwise equal | | DeepSeek V3 | FSDP4 + TP2 + EP4 | 10 | `6.198883e-05` | `1.537800e-04` | Small EP all-to-all variation | DeepSeek parity disabled the bucketing and CUDA-graph passes on both backends. The focused deterministic suite also completed with 16 passed and 9 skipped. ## Activation checkpointing Configuration: Llama3 debug model, 8 GPUs, FSDP4 + TP2, `aot_fx_trace`, regional Inductor, CUDA graphs disabled, 20 steps, and one run per backend. TPS is the rank-0 median over steps 6-20, and memory is the maximum reported peak across ranks. Only `compile.memory_policy` changed between rows. The `partial_dtensor` and `spmd_types` graphs made identical save/recompute decisions for every tested policy and every one of the six Llama layers. | Policy | Forced boundary saves | Non-layer save/recompute | Per-layer save/recompute | Partial TPS | SPMD TPS | Delta | Partial peak | SPMD peak | | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | | Default SAC | 6 | 2 / 21 | 13 / 79 | 130,058 | 132,557 | +1.92% | 0.45 GiB | 0.45 GiB | | Eager-equivalent SAC | 6 | 2 / 21 | 11 / 81 | 126,280 | 134,145 | +6.23% | 0.39 GiB | 0.39 GiB | | Full recompute | 7 | 1 / 22 | 1 / 91 | 129,144 | 127,320 | -1.41% | 0.24 GiB | 0.24 GiB | | SAC + CPU offload | 6 | 2 / 21 | 13 / 79 | 122,871 | 121,882 | -0.80% | 0.33 GiB | 0.33 GiB | CPU offload matched exactly as well: both backends tagged 35 activations (282.5 MB), offloaded 20 tensors (142.5 MB), replayed five views, and moved 20 reloads one layer earlier. ## Precompile Artifacts were generated independently for each backend, then loaded by a fresh 8-GPU process for a 20-step run. CUDA graphs were disabled so these numbers isolate the precompiled regional-Inductor path. TPS is the rank-0 median over steps 6-20; memory is the maximum reported peak across ranks. | Model | Parallelism | Partial TPS | Partial peak | SPMD TPS | SPMD peak | Delta | | --- | --- | ---: | ---: | ---: | ---: | ---: | | Llama3 SDPA | FSDP4 + TP2 | 110,019 | 0.45 GiB | 110,993 | 0.45 GiB | +0.89% | | Llama3 FlexAttention | FSDP4 + TP2 | 110,891 | 0.45 GiB | 108,441 | 0.45 GiB | -2.21% | | DeepSeek V3 | FSDP4 + TP2 + EP4 | Artifact generation fails | -- | 67,709 | 1.59 GiB | -- | DeepSeek used `--training.disable_cuda_graphs` because its default token dispatcher is rejected by CUDA-graph configuration validation. Its `partial_dtensor` artifact generation reaches the same `stable topological sort of region failed` limitation as the direct-trace default-bucketing path; `spmd_types` generates, loads, and runs the artifact. ## CUDA graphs CUDA graphs are not blocked for the `spmd_types` backend as a whole. They work on the precompiled Llama FlexAttention path: the artifact loaded, the pass logged `Applied cudagraph pass`, and training completed for 10 steps. Over steps 6-10, median throughput was 246,007 TPS with CUDA graphs versus 116,855 TPS from the same precompiled artifact with the pass disabled; peak memory was 0.46 versus 0.45 GiB. This is a single short run. The direct-trace Llama FSDP4 + TP2 path remains blocked from CUDA graph capture on both backends. The pass is invoked but logs `Skipping cudagraph: graph is not compatible`, so direct-trace runs with the pass enabled are not CUDA graph performance measurements. ## Inductor | Mode | Partial TPS | SPMD TPS | Delta | Partial memory | SPMD memory | | --- | ---: | ---: | ---: | ---: | ---: | | Regional | 130,058 | 132,557 | +1.92% | 0.45 GiB | 0.45 GiB | | Full | 181,628 | 187,040 | +2.98% | 0.48 GiB | 0.48 GiB | Both modes completed 20 steps. Full Inductor was the fastest tested direct trace configuration for both backends. ## FSDP SimpleFSDP unit coverage passed (`2 passed`). Llama FSDP4 + TP2 completed under both backends, and the optional AG/RS overlap pass found the same 22 overlap dependencies in each graph. | Configuration | Partial TPS | SPMD TPS | Delta | Partial peak | SPMD peak | | --- | ---: | ---: | ---: | ---: | ---: | | Regional Inductor, no CUDA graph | 130,058 | 132,557 | +1.92% | 0.45 GiB | 0.45 GiB | | Regional Inductor + FSDP AG/RS overlap | 131,768 | 136,092 | +3.28% | 0.45 GiB | 0.45 GiB | For DeepSeek FSDP4 + TP2 + EP4 with the default bucketing pass, `partial_dtensor` fails with `stable topological sort of region failed`, while `spmd_types` completes. This is a baseline limitation rather than an `spmd_types` blocker. ## DCP Llama FSDP4 + TP2 with `spmd_types` trained for 10 steps, saved a full DCP checkpoint at step 10, then loaded it in a fresh process and resumed at step 11 through step 12. Model, optimizer, scheduler, dataloader, and trainer state were restored through the normal checkpoint path. ## GraphPP Configuration: DeepSeek V3 debug model, 8 GPUs, FSDP4 + PP2 + EP2, TP1, eight pipeline microbatches, 2,048 tokens per microbatch per DP rank, full Inductor, CUDA graphs disabled, and 20 training steps. All three schedules completed under both backends. TPS is the rank-0 median over steps 6-20; memory is the maximum reported peak across ranks. | Schedule | Partial TPS | SPMD TPS | Delta | Partial peak | SPMD peak | | --- | ---: | ---: | ---: | ---: | ---: | | Interleaved1F1B | 40,897 | 42,180 | +3.14% | 0.69 GiB | 0.69 GiB | | ZBVZeroBubble | 42,952 | 40,724 | -5.19% | 0.81 GiB | 0.81 GiB | | DualPipeV | 42,752 | 42,255 | -1.16% | 0.87 GiB | 0.87 GiB | ## Other coverage | Test | Result | | --- | --- | | MuseGlimmer FSDP4 + TP2 integration | Pass, 10 steps, 0.65 GiB peak | | Supported MoE-level graph EP chunking | Pass | | Supported MoE-level eager EP chunking | Pass | | `test_bitwise_deterministic.py` | 16 passed, 9 skipped | | `test_simple_fsdp.py` | 2 passed | | Formatter, pydoclint, codespell, CI Pyrefly | Pass | | Standard DeepSeek FSDP + TP + EP | Both 10-step parity runs passed; the integration test remains disabled for a recorded intermittent all-to-all failure | The formatter-only changes requested by lint are included in `simple_fsdp.py`. A local all-files Pyrefly invocation is not representative of CI in this dirty workspace because it scans unrelated untracked scripts and generated `torch_compile_debug` files; the clean CI result supplied for this commit passes. ## Unsupported GraphTrainer configurations | Area | `partial_dtensor` | `spmd_types` | Scope | | --- | --- | --- | --- | | CP + FlexAttention | Rejected by GraphTrainer configuration validation | Rejected by GraphTrainer configuration validation | Unsupported by GraphTrainer | | Runtime SPMD typechecking | Flag rejected as unsupported | Flag rejected as unsupported | Unsupported by GraphTrainer | | Direct-trace CUDA graphs, Llama FSDP4 + TP2 | Compatibility gate skips capture | Compatibility gate skips capture | Shared | | MoE EP overlap + dense-region FSDP scheduling | Fails on alias users of reduce-scatter wait sinks | Same failure | Shared (`#4052`) | | Transformer-level EP chunking | Graph mode hits a CUDA device assertion | Same failure; eager mode also produces an invalid attention mask | Shared, obsolete configuration (`#4342`) | ## Reproduction commands Backend parity used `scripts/loss_compare.py` with 10 steps, the same seed checkpoint, and backend-specific `--parallelism.spmd_backend` values. The common Llama options were FSDP4 + TP2; Qwen and DeepSeek additionally used EP4. DeepSeek disabled `joint_transformer_block_bucketing_reordering_pass`. Feature performance used: ```bash NGPU=8 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel \ ./run_train.sh --training.steps 20 --metrics.log_freq 1 \ --compile.mode aot_fx_trace --training.disable_cuda_graphs \ --compile.disable_passes cudagraph_pass \ --parallelism.spmd_backend <partial_dtensor|spmd_types> \ --parallelism.data_parallel_shard_degree 4 \ --parallelism.tensor_parallel_degree 2 \ <feature options> ``` `<feature options>` was one of `--compile.memory_policy eager`, `--compile.memory_policy full`, `--compile.memory_policy sac_and_offload`, `--compile.inductor_compilation full`, or `--compile.enable_fsdp_ag_rs_overlap`. The paired GraphPP and precompile performance runs used the same options as their checked-in integration cases, with 20 steps and a separate launch or artifact for each backend.
[ghstack-poisoned]
[ghstack-poisoned]
pianpwk
added a commit
that referenced
this pull request
Sep 3, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0) (oldest at bottom): * #4427 * #4419 * __->__ #4416
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Sep 3, 2026
ghstack-source-id: 7a609b9 Pull Request resolved: pytorch/torchtitan#4419
[ghstack-poisoned]
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Sep 3, 2026
ghstack-source-id: 4197078 Pull Request resolved: pytorch/torchtitan#4419
[ghstack-poisoned]
pianpwk
marked this pull request as ready for review
September 4, 2026 18:20
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
tianyu-l
reviewed
Sep 11, 2026
Comment on lines
+70
to
+75
| "PartialBiasRowwiseLinear", | ||
| "QKVLinear", | ||
| "RMSNorm", | ||
| "RoPE", | ||
| "RouterGateLinear", | ||
| "ScaledBiasRowwiseLinear", | ||
| "PartialBiasRowwiseLinear", |
Comment on lines
+134
to
+142
| if ( | ||
| self._parallelized | ||
| and self._sharding_config is not None | ||
| and current_spmd_mesh() is None | ||
| ): | ||
| raise RuntimeError( | ||
| "PartialBiasRowwiseLinear requires an ambient DeviceMesh after " | ||
| "parallelize()." | ||
| ) |
Contributor
There was a problem hiding this comment.
why do we need this code? Even if we need some error msg, we should error out somewhere else. O/w every module that accesses spmd_mesh_group would need this.
[ghstack-poisoned]
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Sep 15, 2026
Job 8829185 got past import, past the tokenizer, built the model, and died in FSDP setup on all three arms / 23 ranks each: ValueError: When dp_mesh_dims is provided, all parameters must be DTensors on the full SPMD mesh. Got plain tensor for parameter 'weight'. This is the failure both config registries flagged as UNVERIFIED before the run. Pre-registered, then reproduced. Mechanism measured directly rather than inferred: Aurora's torch 2.13.0.dev20260520+xpu has _fsdp_param.py at 1093 lines with ZERO occurrences of _resolve_spmd_types_for_storage / self.is_spmd_types / get_local_type. pytorch #181519 added that conversion block; our build predates it, so an annotated plain tensor falls through to the raise. Perlmutter's 2.13.0 shows the same gap at 1095 lines -- two independent builds agreeing. So this is a TORCH VERSION FLOOR exposed by pytorch#4419 deleting the partial_dtensor escape hatch, not a defect in the sync ports. Baseline 8829243 (same machine, venv and script; differs only in still pinning partial_dtensor at config_registry.py:252) is running to discriminate. Records the three ways to unblock and notes that everything else in the sync is verified.
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Sep 15, 2026
8829243 on the pre-merge tree: all three arms rc=0, zero DTensor errors, real losses (agpt TP=1 10.88382->10.48337, agpt TP=2 10.88071->10.56243, moe 12.90379->11.45320). Same machine, venv, script and seed as 8829185, which died in FSDP setup on all three arms. The trees differ on one line: config_registry.py:252 pins partial_dtensor pre-merge; pytorch#4419 deleted the pin and the backend. So pytorch#4419 is the cause and the sync ports are clean -- the merged tree reached FSDP setup, well past import, tokenizer and model construction. Also records that no configuration workaround exists: merged core has ZERO references to partial_dtensor and ZERO to spmd_backend, the config field included. The backend is deleted, not unselected. The TP=2 arm passing is worth its own note -- that is the configuration the pytorch#4533 local_map contract asserts under, so there is now a known-good reference to diff against once a torch carrying #181519 lands.
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Sep 16, 2026
Now that the question is closed at four builds, the request is the remaining action. Drafted but NOT sent -- outward-facing, so it is the user's call. Leads with what is blocked (post-pytorch#4419 torchtitan cannot run on Aurora at all, raises before step 1) rather than with our internal history. Carries the four-build table, the symbol-vs-prose detection note so ALCF can reproduce it, and the pre-merge-vs-merged loss comparison showing the trees differ on one line and nothing else in the upgrade is implicated. Scoped as affecting any Aurora user tracking torchtitan past pytorch#4419, not just this project, and states the three acceptable outcomes including 'not planned' so we can decide on a local shim.
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Sep 16, 2026
8831522 on next-eval: all three arms rc=143, 72 ranks, byte-for-byte the same DTensor ValueError as 8829185 on the prod bkc. Different image, different torch build, different venv, same failure -- and it reached IMPORT_OK and built the model first, so this is the FSDP path rather than packaging. The test bkc was the last place the blocker could plausibly have been absent. It is not. Together with the pre-merge control that trains on the same hardware (8829243, VERDICT: ok), the attribution is complete: pytorch#4419 removed the partial_dtensor escape hatch and no reachable torch carries #181519.
saforem2
added a commit
to saforem2/torchtitan
that referenced
this pull request
Sep 16, 2026
…f findings The page had become unreadable. I had been prepending each new finding to the top, so it ran newest-first with five mutually contradictory headings stacked: line 1 'NOT blocked -- retracted' line 103 'the blocker holds on BOTH bkc images' line 179 'ANSWERED: #181519 LIFTS THE BLOCKER' line 308 'THE REAL FINDING: pytorch#4419 blocks the merge' line 379 'CLOSED: #181519 is ABSENT on all FOUR builds' line 501 'Original (WRONG) analysis, retained' Each was true when written. Together they were a running log of my own changing understanding, not a document -- a reader had no way to tell which heading was current. Rewritten to state what is true now: the result, the controlled A/B, why the patch matters, the six-build table, the two genuine sync-84 bugs, the environment issues as a lookup table, what is open, and how to reproduce. Superseded conclusions are in git log rather than inline.
meta-codesync Bot
pushed a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 8, 2026
…anges Summary: Recent TorchTitan syncs changed several APIs that `experiments/fb/flex_shard` depends on, so `flex_shard_tests` now fails at import time (`unittest` `loadTestsFromName` ImportError). This diff moves the fb FlexShard code to the new APIs, fixes the EP>1 DistMuon break from #4419, and ports the Qwen3 recipe. - pytorch/torchtitan#4904 (optimizer config refactor): `build_dist_muon(...)` is replaced by the `DistMuon(...)` class, which takes the same arguments. `comm_free_adapter.build_local_dist_muon` now constructs `DistMuon` directly. - pytorch/torchtitan#4660 (`components.optimizer` -> `components.optim`, `Trainer.Config.optim`): - Imports now come from `torchtitan.components.optim`. - DSV3 Muon configs set `config.optim.optimizer`. - `FlexShardDistMuonOptimizers` accepts the new `enable_cuda_graph` kwarg. It raises if the flag is set, the same way upstream `OptimizersContainer` rejects optimizers that can't be captured. - `_log_optimizer` now takes a pattern string. - pytorch/torchtitan#4617: `ParallelismConfig` now lives in `torchtitan.config.parallelism`. - pytorch/torchtitan#4905: - `ParallelDims` is now `ParallelismContext`, and the `parallel_dims=` kwarg is now `parallelism_context=`. - `get_spmd_context(...)` is replaced by `parallelism_context.activate_spmd()`. - The `efsdp` mesh axis is now `edp_shard`. This also covers the `partition_rank_axis_name` passed to the DistMuon bucket planner. - Tests build the context with `ParallelismContext.from_config(config, DistributedTopology(world_size=...))`. - pytorch/torchtitan#4840: `BlockShard(block_size=R)` is now `BlockShard(block_sizes=(R,))`. - pytorch/torchtitan#4878: the DSV3 `model_registry` now requires `enable_sp`. The FlexShard wrapper passes `enable_sp=False`. FlexShard rejects TP, and `False` keeps the shared-expert `w2` as a plain `Linear`, as it was before #4878. - pytorch/torchtitan#4419 (EP without DTensor): `Module._parallelize` now leaves EP-sharded routed experts as plain local `nn.Parameter` shards. It records their layouts in each module's `_sharding_config` instead of returning DTensors. With EP>1, DistMuon failed with "Partitioned block parameters must be DTensors", and `dtensor_to_global_layout` no longer found anything to declare. - flex_shard `dist_muon/placement.py` and `storage_layout.py` now read the FlexShard `GlobalLayout` contract (`get_global_layout`) instead of DTensor placements. `get_dim0_block_partitions` no longer takes `partition_axis_name`. - The new `experiments/fb/flex_shard/spmd_layouts.py` `declare_spmd_global_layouts(model, mesh)` collects `_sharding_config.state_shardings` and declares them through `spmd_types_to_global_layout`. The DSV3 recipes and tests call it where they used to call `dtensor_to_global_layout`. - EP>1 configs now need `training.disable_cuda_graphs`: upstream config validation rejects CUDA graphs with the all-to-all token dispatcher. `flex_shard_deepseek_v3_debug_muon` sets EP=2 after construction, so it skipped that check and would fail when launched from the CLI. It now disables CUDA graphs, as upstream EP configs do. - Qwen3 recipe port. It was broken before these syncs, by `protocols.model_spec`, `FusedQKVLinear`, `components.metrics`, `tools.logging`, `default_adamw` and `set_spmd_backend`. - It follows the DSV3 pattern: `FlexShardQwen3Model(Qwen3Model)` with `Config.muon_pattern`, and `parallelize()` runs `parallelize_qwen3_muon` under `activate_spmd()`. - Configs are rebuilt on the current `Trainer.Config` fields with the same hyperparameters. - Q/K/V BlockShard plans use the fused `QKVLinear.wqkv`: one `head_dim`-row matrix per Q/K/V head. - `parallelize_qwen3_muon` uses `dp_shard`, always calls `_parallelize` (as DSV3 does), and declares the EP layouts. - DSV3 `test_debug_muon_train_step` now disables autograd multithreading, as upstream `init_distributed` does. The SPMD mesh is thread-local, and FSDPTest skips `init_distributed`. So selective-AC recompute ran on an autograd device thread with no mesh set, the MoE token dispatch skipped EP there, and backward failed in `torch._grouped_mm` with "matrix batch sizes have to match". The upstream Trainer is not affected: the DSV3 debug model with EP=2 + SAC trains normally. The `comm_free_adapter` change is the same as the one in D122391176, the auto-generated Test Blame fix. This diff also covers the other breakages in fb/flex_shard. The DistMuon tests (DSV3 `test_shard0_owned_mixed` and `test_debug_muon_train_step`, and Qwen3 `test_debug_muon_train_step`) now get past every API break. They still fail on the fused `w13` weights, which the next diff (D122443668) fixes. Reviewed By: weifengpy Differential Revision: D122692766 Pull Request resolved: #50
3 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):