Skip to content

[graph_trainer] Optimize HSDP gradient collective order - #4859

Merged
aditvenk merged 1 commit into
mainfrom
graph-trainer-hsdp-collective-reorder
Oct 8, 2026
Merged

aditvenk merged 1 commit into
mainfrom
graph-trainer-hsdp-collective-reorder

Conversation

@aditvenk

@aditvenk aditvenk commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

DTensor lowers HSDP gradient redistribution in mesh-axis order, producing a replicate-axis all-reduce before the shard-axis reduce-scatter. This sends the full gradient through the expensive all-reduce.

Add a joint graph pass that recognizes the direct backward all-reduce/wait/reduce-scatter/wait chain on the exact configured HSDP process groups and reverses it. Running reduce-scatter first shrinks the subsequent all-reduce payload by the shard degree. Preserve operation provenance while rebuilding shape metadata with independent FakeTensor storage, and support compile-on-one-rank process-group nodes.

Install the pass in GraphTrainer's shared compile-time pipeline before process-group reassignment and bucketing. Extend overlap scheduling to handle bucketed all-reduces without introducing dependency cycles.

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 24, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 24, 2026
@aditvenk aditvenk added the ciflow/h100.8 Trigger H100.8 CI label Sep 24, 2026
@aditvenk
aditvenk force-pushed the graph-trainer-hsdp-collective-reorder branch from ca2fc15 to 2ff9cfd Compare September 24, 2026 03:48

@sanketpurandare sanketpurandare left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we also cover dp_replicate + efsdp in the pass and validate using efsdp for the dsv3 model? dp_replicate and dp_shard look correct.

@aditvenk
aditvenk force-pushed the graph-trainer-hsdp-collective-reorder branch 2 times, most recently from eb6f8c7 to 677d888 Compare October 6, 2026 23:13
@aditvenk

aditvenk commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Can we also cover dp_replicate + efsdp in the pass and validate using efsdp for the dsv3 model? dp_replicate and dp_shard look correct.

Resolved.

@IvanKobzarev

Copy link
Copy Markdown
Contributor

Looks like this optimization will not be applied for gradient accumulation microbatches > 1.
It should not be hard to support this, according to agent just some plumbing with parallelism_context in grad accumulation graph_builder.

DTensor lowers HSDP gradient redistribution in mesh-axis order, producing a replicate-axis all-reduce before a shard-axis reduce-scatter. This sends the full gradient through the expensive all-reduce.

Add a joint graph pass that recognizes the exact backward all-reduce/wait/reduce-scatter/wait chain and reverses it so the all-reduce operates on the already-sharded gradient. Match process-group pairs for both dense (dp_replicate, flattened fsdp) parameters and routed-expert (dp_replicate, efsdp) parameters, including compile-on-one-rank group nodes. Preserve collective provenance and update tensor metadata to reflect the reordered values.

Install the pass before process-group reassignment and manual bucketing. Thread the parallelism context through SPMD gradient-accumulation and GraphPP graph construction so the pass can resolve process groups before FSDP reduction extraction. Rely on PyTorch manual bucketing for full-graph collective reachability and on its optimized mover for conditional topological repair. Treat the reduce-scatter as the only HSDP prefetch boundary, recompute ancestry after bucketing, and avoid overlap edges that oppose existing data dependencies.

Apply eager HSDP reduction controls only to composable FSDP modules. SimpleFSDP and AutoParallel materialize gradient collectives inside the traced microbatch and do not expose that API, so external accumulation communicates each microbatch. Keep GraphPP action bucketing acyclic when extraction contains both reordered and unreordered HSDP chains.

Add matcher, process-group, pipeline, bucketing, scheduling, and compile-on-one-rank tests; a real four-GPU SimpleFSDP rewrite test; a two-microbatch Llama HSDP eager-vs-GraphTrainer numerical comparison; an eight-GPU Llama HSDP eager-PP-vs-GraphPP numerical comparison; and an enabled DeepSeek-v3 HSDP+eFSDP integration test.
@aditvenk
aditvenk force-pushed the graph-trainer-hsdp-collective-reorder branch from 677d888 to 3af5f2f Compare October 8, 2026 02:23
@aditvenk

aditvenk commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

The last failure in 8xH100 CI is the qwen test that was xfailed in a separate PR. merging.

@aditvenk
aditvenk merged commit e0fbc7f into main Oct 8, 2026
pianpwk added a commit that referenced this pull request Oct 8, 2026
… does

This fixes a numerics mismatch between eager FSDP2 and SimpleFSDP (GraphTrainer).

pytorch/pytorch#194434 ("[FSDP2] Separate sharded and unsharded gradient dtypes", 38d3f6fd0d6e, in the 2026-10-02 nightly) changes the dtype of FSDP2's unsharded-parameter gradients when `grad_dtype` is not specified: they now default to `reduce_dtype` instead of `param_dtype`. With torchtitan's mixed-precision policy, that is fp32 instead of bf16.

This changes the backward all-reduce of TP-replicated parameters (typed R on TP, e.g. sequence-parallel norm weights and the MoE router gate): eager FSDP2 now sums the per-TP-rank partial gradients in fp32 and reduce-scatters the fp32 sum. SimpleFSDP also sums them in fp32, but the sum is rounded back down to bf16 to match the dtype of SimpleFSDP's unsharded weight, a bf16 autograd intermediate, before the reduce-scatter. The router gate's `grad_weight`, which `HiMidLoLinear` computes in fp32, is rounded the same way. As a result the dense Llama3/Qwen3 and the Qwen3 MoE numerics tests diverge from eager at step 2, and are xfailed in #5110 and #5133.

This PR adds a custom autograd Function that runs SimpleFSDP's gradient reductions the way FSDP2 does. All of those tests match eager bitwise again, and their xfails are removed.

Both sides use torchtitan's default mixed-precision settings:

| Field | Value | Source |
|---|---|---|
| master (sharded) param dtype | fp32 | |
| `param_dtype` | bf16 | `training.mixed_precision_param` |
| `reduce_dtype` | fp32 | `training.mixed_precision_reduce` |
| `grad_dtype` on the param | unset | |

What differs is where the unsharded weight sits in autograd:

- **Eager FSDP2:** the unsharded weight is `FSDPParam._unsharded_param`, a leaf `nn.Parameter` built outside autograd, and FSDP2 sets its `grad_dtype = reduce_dtype` (fp32). The TP all-reduce and the reduce-scatter run afterwards, in FSDP2's post-backward, on that leaf's `.grad`.
- **SimpleFSDP:** the unsharded weight is computed from the sharded parameter by the parametrization, so it is a bf16 intermediate. Its gradient dtype defaults to its own dtype (bf16), and autograd casts every gradient flowing into it to bf16. SimpleFSDP cannot simply set `grad_dtype = reduce_dtype` like FSDP2, because `grad_dtype` can only be set on leaf tensors: FSDP2's autograd graph starts at the unsharded parameter, while SimpleFSDP's includes the all-gather, the TP all-reduce and the reduce-scatter. Hence the custom autograd Function below, whose output declares its gradient dtype with `ctx.set_output_grad_dtype`, the non-leaf equivalent.

Each TP rank computes a partial gradient (over its tokens), which must be summed over TP before the FSDP reduce-scatter.

```
Eager FSDP2
  compute -> wgrad bf16
  -> LEAF .grad: unsharded param, grad_dtype = reduce_dtype       -> fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  compute -> wgrad bf16
  -> spmd.convert(I -> R) bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- rounds the TP sum
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  compute -> wgrad bf16
  -> output grad dtype declared fp32                              -> cast up (exact)
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

`HiMidLoLinear`'s backward computes `grad_weight` in fp32 by design.

```
Eager FSDP2
  HiMidLo bwd -> grad_weight fp32
  -> LEAF .grad: grad_dtype = reduce_dtype                        -> kept fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  HiMidLo bwd -> grad_weight fp32
  -> autograd casts to convert output's dtype (bf16)              <- issue 2
  -> convert bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- issue 1
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  HiMidLo bwd -> grad_weight fp32
  -> output grad dtype declared fp32                              -> kept fp32
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

For every other parameter, the bf16 wgrad reaches the reduce-scatter with no reduction in between, and the bf16 -> fp32 cast is exact wherever it happens, so those gradients already matched eager.

`_UnshardAndReduceGradFunction` covers one parameter's unshard and gradient reduction:

- **Forward:** wrap the TP/EP-local shard as a DTensor on the DP mesh, cast to `param_dtype`, all-gather (no-op for DDP), and return the unsharded weight. Same ops as before.
- **Output gradient dtype:** `ctx.set_output_grad_dtype(reduce_dtype)`, the same value FSDP2 gives its unsharded parameter's `grad_dtype`. An fp32 gradient flowing in is kept, and a bf16 one is cast up exactly.
- **Backward:** all-reduce (P -> I) over the non-DP axes where the parameter is R, then Partial -> the DP placements (reduce-scatter for FSDP, all-reduce for DDP, both for HSDP), all in `reduce_dtype`, in one node with no bf16 intermediate.

Both branches of `ReplicateComputation.replicate_compute` (with and without TP/EP axes) use it, replacing the `redistribute -> to_local -> spmd.convert` chain.

Dynamo cannot trace `ctx.set_output_grad_dtype` yet, so the call is skipped under `torch.compile`. GraphTrainer traces with `make_fx` and is unaffected; only the SimpleFSDP unit tests that use `torch.compile(backend="aot_eager")` take this path, and none uses mixed precision. The guard can go once the Dynamo support (pytorch PR, TODO: link) is in the nightly.

**Compared to #5106**, which all-gathers R parameters in fp32 so the TP sum stays fp32:
- the all-gather stays in bf16, so there are no extra fp32 all-gather buckets (#5106: 15 -> 28 in the Llama3 debug model);
- it also fixes issue 2, which #5106 cannot reach because the router's rounding happens before the TP sum.

8x H100, torch 2.16.0a0+gitbe3a22f (includes pytorch#194434), 20 steps, eager vs GraphTrainer:

| Test | main | this PR |
|---|---|---|
| `test_dense_llama3_aot_fx_trace_vs_eager` | diverges at step 2 (xfail) | bitwise |
| `test_dense_qwen3_aot_fx_trace_vs_eager` | diverges (xfail) | bitwise |
| `test_moe_qwen3_aot_fx_trace_vs_eager` | diverges from step 2 (xfail) | bitwise (loss and grad_norm) |
| `test_dense_llama3_hsdp_gradient_accumulation_aot_fx_trace_vs_eager` | | bitwise |
| `test_dense_llama3_hsdp_graph_pp_vs_eager` | | bitwise |

- `test_numerics.py`: the five tests above pass. The strict xfails from #5110 and #5133 are removed, and the MoE test now uses the bitwise `run_loss_compare` instead of `run_loss_compare_close`.
- New `TestSimpleFSDP` tests, both failing on main by exactly the rounded-off amount:
  - `test_tp_reduced_grad_stays_in_reduce_dtype`: per-TP-rank grads 1 and 2**-9 (exact in bf16, but their sum is not) must reach the reduce-scatter as 1 + 2**-9.
  - `test_wide_grad_reaches_reduce_scatter`: an fp32 wgrad with a sub-bf16 term must keep it.
- `TestSimpleFSDP` + `test_simple_fsdp.py`: pass (uneven/transposed shards, DDP/HSDP + TP, EP + TP, compiled variants).
- `test_bitwise_deterministic.py` and `test_passes.py` + `test_graph_pp_passes.py` passed before rebasing onto #4859.
- ufmt, flake8, codespell and pyrefly pass on the changed files.

ghstack-source-id: 2a78edf
Pull Request resolved: #5171
pianpwk added a commit that referenced this pull request Oct 12, 2026
… does

This fixes a numerics mismatch between eager FSDP2 and SimpleFSDP (GraphTrainer).

pytorch/pytorch#194434 ("[FSDP2] Separate sharded and unsharded gradient dtypes", 38d3f6fd0d6e, in the 2026-10-02 nightly) changes the dtype of FSDP2's unsharded-parameter gradients when `grad_dtype` is not specified: they now default to `reduce_dtype` instead of `param_dtype`. With torchtitan's mixed-precision policy, that is fp32 instead of bf16.

This changes the backward all-reduce of TP-replicated parameters (typed R on TP, e.g. sequence-parallel norm weights and the MoE router gate): eager FSDP2 now sums the per-TP-rank partial gradients in fp32 and reduce-scatters the fp32 sum. SimpleFSDP also sums them in fp32, but the sum is rounded back down to bf16 to match the dtype of SimpleFSDP's unsharded weight, a bf16 autograd intermediate, before the reduce-scatter. The router gate's `grad_weight`, which `HiMidLoLinear` computes in fp32, is rounded the same way. As a result the dense Llama3/Qwen3 and the Qwen3 MoE numerics tests diverge from eager at step 2, and are xfailed in #5110 and #5133.

This PR adds a custom autograd Function that runs SimpleFSDP's gradient reductions the way FSDP2 does. All of those tests match eager bitwise again, and their xfails are removed.

Both sides use torchtitan's default mixed-precision settings:

| Field | Value | Source |
|---|---|---|
| master (sharded) param dtype | fp32 | |
| `param_dtype` | bf16 | `training.mixed_precision_param` |
| `reduce_dtype` | fp32 | `training.mixed_precision_reduce` |
| `grad_dtype` on the param | unset | |

What differs is where the unsharded weight sits in autograd:

- **Eager FSDP2:** the unsharded weight is `FSDPParam._unsharded_param`, a leaf `nn.Parameter` built outside autograd, and FSDP2 sets its `grad_dtype = reduce_dtype` (fp32). The TP all-reduce and the reduce-scatter run afterwards, in FSDP2's post-backward, on that leaf's `.grad`.
- **SimpleFSDP:** the unsharded weight is computed from the sharded parameter by the parametrization, so it is a bf16 intermediate. Its gradient dtype defaults to its own dtype (bf16), and autograd casts every gradient flowing into it to bf16. SimpleFSDP cannot simply set `grad_dtype = reduce_dtype` like FSDP2, because `grad_dtype` can only be set on leaf tensors: FSDP2's autograd graph starts at the unsharded parameter, while SimpleFSDP's includes the all-gather, the TP all-reduce and the reduce-scatter. Hence the custom autograd Function below, whose output declares its gradient dtype with `ctx.set_output_grad_dtype`, the non-leaf equivalent.

Each TP rank computes a partial gradient (over its tokens), which must be summed over TP before the FSDP reduce-scatter.

```
Eager FSDP2
  compute -> wgrad bf16
  -> LEAF .grad: unsharded param, grad_dtype = reduce_dtype       -> fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  compute -> wgrad bf16
  -> spmd.convert(I -> R) bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- rounds the TP sum
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  compute -> wgrad bf16
  -> output grad dtype declared fp32                              -> cast up (exact)
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

`HiMidLoLinear`'s backward computes `grad_weight` in fp32 by design.

```
Eager FSDP2
  HiMidLo bwd -> grad_weight fp32
  -> LEAF .grad: grad_dtype = reduce_dtype                        -> kept fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  HiMidLo bwd -> grad_weight fp32
  -> autograd casts to convert output's dtype (bf16)              <- issue 2
  -> convert bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- issue 1
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  HiMidLo bwd -> grad_weight fp32
  -> output grad dtype declared fp32                              -> kept fp32
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

For every other parameter, the bf16 wgrad reaches the reduce-scatter with no reduction in between, and the bf16 -> fp32 cast is exact wherever it happens, so those gradients already matched eager.

`_UnshardAndReduceGradFunction` covers one parameter's unshard and gradient reduction:

- **Forward:** wrap the TP/EP-local shard as a DTensor on the DP mesh, cast to `param_dtype`, all-gather (no-op for DDP), and return the unsharded weight. Same ops as before.
- **Output gradient dtype:** `ctx.set_output_grad_dtype(reduce_dtype)`, the same value FSDP2 gives its unsharded parameter's `grad_dtype`. An fp32 gradient flowing in is kept, and a bf16 one is cast up exactly.
- **Backward:** all-reduce (P -> I) over the non-DP axes where the parameter is R, then Partial -> the DP placements (reduce-scatter for FSDP, all-reduce for DDP, both for HSDP), all in `reduce_dtype`, in one node with no bf16 intermediate.

Both branches of `ReplicateComputation.replicate_compute` (with and without TP/EP axes) use it, replacing the `redistribute -> to_local -> spmd.convert` chain.

Dynamo cannot trace `ctx.set_output_grad_dtype` yet, so the call is skipped under `torch.compile`. GraphTrainer traces with `make_fx` and is unaffected; only the SimpleFSDP unit tests that use `torch.compile(backend="aot_eager")` take this path, and none uses mixed precision. The guard can go once the Dynamo support (pytorch PR, TODO: link) is in the nightly.

**Compared to #5106**, which all-gathers R parameters in fp32 so the TP sum stays fp32:
- the all-gather stays in bf16, so there are no extra fp32 all-gather buckets (#5106: 15 -> 28 in the Llama3 debug model);
- it also fixes issue 2, which #5106 cannot reach because the router's rounding happens before the TP sum.

8x H100, torch 2.16.0a0+gitbe3a22f (includes pytorch#194434), 20 steps, eager vs GraphTrainer:

| Test | main | this PR |
|---|---|---|
| `test_dense_llama3_aot_fx_trace_vs_eager` | diverges at step 2 (xfail) | bitwise |
| `test_dense_qwen3_aot_fx_trace_vs_eager` | diverges (xfail) | bitwise |
| `test_moe_qwen3_aot_fx_trace_vs_eager` | diverges from step 2 (xfail) | bitwise (loss and grad_norm) |
| `test_dense_llama3_hsdp_gradient_accumulation_aot_fx_trace_vs_eager` | | bitwise |
| `test_dense_llama3_hsdp_graph_pp_vs_eager` | | bitwise |

- `test_numerics.py`: the five tests above pass. The strict xfails from #5110 and #5133 are removed, and the MoE test now uses the bitwise `run_loss_compare` instead of `run_loss_compare_close`.
- New `TestSimpleFSDP` tests, both failing on main by exactly the rounded-off amount:
  - `test_tp_reduced_grad_stays_in_reduce_dtype`: per-TP-rank grads 1 and 2**-9 (exact in bf16, but their sum is not) must reach the reduce-scatter as 1 + 2**-9.
  - `test_wide_grad_reaches_reduce_scatter`: an fp32 wgrad with a sub-bf16 term must keep it.
- `TestSimpleFSDP` + `test_simple_fsdp.py`: pass (uneven/transposed shards, DDP/HSDP + TP, EP + TP, compiled variants).
- `test_bitwise_deterministic.py` and `test_passes.py` + `test_graph_pp_passes.py` passed before rebasing onto #4859.
- ufmt, flake8, codespell and pyrefly pass on the changed files.

ghstack-source-id: 7472784
Pull Request resolved: #5171
pianpwk added a commit that referenced this pull request Oct 12, 2026
… does

This fixes a numerics mismatch between eager FSDP2 and SimpleFSDP (GraphTrainer).

pytorch/pytorch#194434 ("[FSDP2] Separate sharded and unsharded gradient dtypes", 38d3f6fd0d6e, in the 2026-10-02 nightly) changes the dtype of FSDP2's unsharded-parameter gradients when `grad_dtype` is not specified: they now default to `reduce_dtype` instead of `param_dtype`. With torchtitan's mixed-precision policy, that is fp32 instead of bf16.

This changes the backward all-reduce of TP-replicated parameters (typed R on TP, e.g. sequence-parallel norm weights and the MoE router gate): eager FSDP2 now sums the per-TP-rank partial gradients in fp32 and reduce-scatters the fp32 sum. SimpleFSDP also sums them in fp32, but the sum is rounded back down to bf16 to match the dtype of SimpleFSDP's unsharded weight, a bf16 autograd intermediate, before the reduce-scatter. The router gate's `grad_weight`, which `HiMidLoLinear` computes in fp32, is rounded the same way. As a result the dense Llama3/Qwen3 and the Qwen3 MoE numerics tests diverge from eager at step 2, and are xfailed in #5110 and #5133.

This PR adds a custom autograd Function that runs SimpleFSDP's gradient reductions the way FSDP2 does. All of those tests match eager bitwise again, and their xfails are removed.

Both sides use torchtitan's default mixed-precision settings:

| Field | Value | Source |
|---|---|---|
| master (sharded) param dtype | fp32 | |
| `param_dtype` | bf16 | `training.mixed_precision_param` |
| `reduce_dtype` | fp32 | `training.mixed_precision_reduce` |
| `grad_dtype` on the param | unset | |

What differs is where the unsharded weight sits in autograd:

- **Eager FSDP2:** the unsharded weight is `FSDPParam._unsharded_param`, a leaf `nn.Parameter` built outside autograd, and FSDP2 sets its `grad_dtype = reduce_dtype` (fp32). The TP all-reduce and the reduce-scatter run afterwards, in FSDP2's post-backward, on that leaf's `.grad`.
- **SimpleFSDP:** the unsharded weight is computed from the sharded parameter by the parametrization, so it is a bf16 intermediate. Its gradient dtype defaults to its own dtype (bf16), and autograd casts every gradient flowing into it to bf16. SimpleFSDP cannot simply set `grad_dtype = reduce_dtype` like FSDP2, because `grad_dtype` can only be set on leaf tensors: FSDP2's autograd graph starts at the unsharded parameter, while SimpleFSDP's includes the all-gather, the TP all-reduce and the reduce-scatter. Hence the custom autograd Function below, whose output declares its gradient dtype with `ctx.set_output_grad_dtype`, the non-leaf equivalent.

Each TP rank computes a partial gradient (over its tokens), which must be summed over TP before the FSDP reduce-scatter.

```
Eager FSDP2
  compute -> wgrad bf16
  -> LEAF .grad: unsharded param, grad_dtype = reduce_dtype       -> fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  compute -> wgrad bf16
  -> spmd.convert(I -> R) bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- rounds the TP sum
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  compute -> wgrad bf16
  -> output grad dtype declared fp32                              -> cast up (exact)
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

`HiMidLoLinear`'s backward computes `grad_weight` in fp32 by design.

```
Eager FSDP2
  HiMidLo bwd -> grad_weight fp32
  -> LEAF .grad: grad_dtype = reduce_dtype                        -> kept fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  HiMidLo bwd -> grad_weight fp32
  -> autograd casts to convert output's dtype (bf16)              <- issue 2
  -> convert bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- issue 1
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  HiMidLo bwd -> grad_weight fp32
  -> output grad dtype declared fp32                              -> kept fp32
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

For every other parameter, the bf16 wgrad reaches the reduce-scatter with no reduction in between, and the bf16 -> fp32 cast is exact wherever it happens, so those gradients already matched eager.

`_UnshardAndReduceGradFunction` covers one parameter's unshard and gradient reduction:

- **Forward:** wrap the TP/EP-local shard as a DTensor on the DP mesh, cast to `param_dtype`, all-gather (no-op for DDP), and return the unsharded weight. Same ops as before.
- **Output gradient dtype:** `ctx.set_output_grad_dtype(reduce_dtype)`, the same value FSDP2 gives its unsharded parameter's `grad_dtype`. An fp32 gradient flowing in is kept, and a bf16 one is cast up exactly.
- **Backward:** all-reduce (P -> I) over the non-DP axes where the parameter is R, then Partial -> the DP placements (reduce-scatter for FSDP, all-reduce for DDP, both for HSDP), all in `reduce_dtype`, in one node with no bf16 intermediate.

Both branches of `ReplicateComputation.replicate_compute` (with and without TP/EP axes) use it, replacing the `redistribute -> to_local -> spmd.convert` chain.

Dynamo cannot trace `ctx.set_output_grad_dtype` yet, so the call is skipped under `torch.compile`. GraphTrainer traces with `make_fx` and is unaffected; only the SimpleFSDP unit tests that use `torch.compile(backend="aot_eager")` take this path, and none uses mixed precision. The guard can go once the Dynamo support (pytorch PR, TODO: link) is in the nightly.

**Compared to #5106**, which all-gathers R parameters in fp32 so the TP sum stays fp32:
- the all-gather stays in bf16, so there are no extra fp32 all-gather buckets (#5106: 15 -> 28 in the Llama3 debug model);
- it also fixes issue 2, which #5106 cannot reach because the router's rounding happens before the TP sum.

8x H100, torch 2.16.0a0+gitbe3a22f (includes pytorch#194434), 20 steps, eager vs GraphTrainer:

| Test | main | this PR |
|---|---|---|
| `test_dense_llama3_aot_fx_trace_vs_eager` | diverges at step 2 (xfail) | bitwise |
| `test_dense_qwen3_aot_fx_trace_vs_eager` | diverges (xfail) | bitwise |
| `test_moe_qwen3_aot_fx_trace_vs_eager` | diverges from step 2 (xfail) | bitwise (loss and grad_norm) |
| `test_dense_llama3_hsdp_gradient_accumulation_aot_fx_trace_vs_eager` | | bitwise |
| `test_dense_llama3_hsdp_graph_pp_vs_eager` | | bitwise |

- `test_numerics.py`: the five tests above pass. The strict xfails from #5110 and #5133 are removed, and the MoE test now uses the bitwise `run_loss_compare` instead of `run_loss_compare_close`.
- New `TestSimpleFSDP` tests, both failing on main by exactly the rounded-off amount:
  - `test_tp_reduced_grad_stays_in_reduce_dtype`: per-TP-rank grads 1 and 2**-9 (exact in bf16, but their sum is not) must reach the reduce-scatter as 1 + 2**-9.
  - `test_wide_grad_reaches_reduce_scatter`: an fp32 wgrad with a sub-bf16 term must keep it.
- `TestSimpleFSDP` + `test_simple_fsdp.py`: pass (uneven/transposed shards, DDP/HSDP + TP, EP + TP, compiled variants).
- `test_bitwise_deterministic.py` and `test_passes.py` + `test_graph_pp_passes.py` passed before rebasing onto #4859.
- ufmt, flake8, codespell and pyrefly pass on the changed files.

ghstack-source-id: 8a4165a
Pull Request resolved: #5171
pianpwk added a commit that referenced this pull request Oct 12, 2026
… does

This fixes a numerics mismatch between eager FSDP2 and SimpleFSDP (GraphTrainer).

pytorch/pytorch#194434 ("[FSDP2] Separate sharded and unsharded gradient dtypes", 38d3f6fd0d6e, in the 2026-10-02 nightly) changes the dtype of FSDP2's unsharded-parameter gradients when `grad_dtype` is not specified: they now default to `reduce_dtype` instead of `param_dtype`. With torchtitan's mixed-precision policy, that is fp32 instead of bf16.

This changes the backward all-reduce of TP-replicated parameters (typed R on TP, e.g. sequence-parallel norm weights and the MoE router gate): eager FSDP2 now sums the per-TP-rank partial gradients in fp32 and reduce-scatters the fp32 sum. SimpleFSDP also sums them in fp32, but the sum is rounded back down to bf16 to match the dtype of SimpleFSDP's unsharded weight, a bf16 autograd intermediate, before the reduce-scatter. The router gate's `grad_weight`, which `HiMidLoLinear` computes in fp32, is rounded the same way. As a result the dense Llama3/Qwen3 and the Qwen3 MoE numerics tests diverge from eager at step 2, and are xfailed in #5110 and #5133.

This PR adds a custom autograd Function that runs SimpleFSDP's gradient reductions the way FSDP2 does. All of those tests match eager bitwise again, and their xfails are removed.

Both sides use torchtitan's default mixed-precision settings:

| Field | Value | Source |
|---|---|---|
| master (sharded) param dtype | fp32 | |
| `param_dtype` | bf16 | `training.mixed_precision_param` |
| `reduce_dtype` | fp32 | `training.mixed_precision_reduce` |
| `grad_dtype` on the param | unset | |

What differs is where the unsharded weight sits in autograd:

- **Eager FSDP2:** the unsharded weight is `FSDPParam._unsharded_param`, a leaf `nn.Parameter` built outside autograd, and FSDP2 sets its `grad_dtype = reduce_dtype` (fp32). The TP all-reduce and the reduce-scatter run afterwards, in FSDP2's post-backward, on that leaf's `.grad`.
- **SimpleFSDP:** the unsharded weight is computed from the sharded parameter by the parametrization, so it is a bf16 intermediate. Its gradient dtype defaults to its own dtype (bf16), and autograd casts every gradient flowing into it to bf16. SimpleFSDP cannot simply set `grad_dtype = reduce_dtype` like FSDP2, because `grad_dtype` can only be set on leaf tensors: FSDP2's autograd graph starts at the unsharded parameter, while SimpleFSDP's includes the all-gather, the TP all-reduce and the reduce-scatter. Hence the custom autograd Function below, whose output declares its gradient dtype with `ctx.set_output_grad_dtype`, the non-leaf equivalent.

Each TP rank computes a partial gradient (over its tokens), which must be summed over TP before the FSDP reduce-scatter.

```
Eager FSDP2
  compute -> wgrad bf16
  -> LEAF .grad: unsharded param, grad_dtype = reduce_dtype       -> fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  compute -> wgrad bf16
  -> spmd.convert(I -> R) bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- rounds the TP sum
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  compute -> wgrad bf16
  -> output grad dtype declared fp32                              -> cast up (exact)
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

`HiMidLoLinear`'s backward computes `grad_weight` in fp32 by design.

```
Eager FSDP2
  HiMidLo bwd -> grad_weight fp32
  -> LEAF .grad: grad_dtype = reduce_dtype                        -> kept fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  HiMidLo bwd -> grad_weight fp32
  -> autograd casts to convert output's dtype (bf16)              <- issue 2
  -> convert bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- issue 1
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  HiMidLo bwd -> grad_weight fp32
  -> output grad dtype declared fp32                              -> kept fp32
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

For every other parameter, the bf16 wgrad reaches the reduce-scatter with no reduction in between, and the bf16 -> fp32 cast is exact wherever it happens, so those gradients already matched eager.

`_UnshardAndReduceGradFunction` covers one parameter's unshard and gradient reduction:

- **Forward:** wrap the TP/EP-local shard as a DTensor on the DP mesh, cast to `param_dtype`, all-gather (no-op for DDP), and return the unsharded weight. Same ops as before.
- **Output gradient dtype:** `ctx.set_output_grad_dtype(reduce_dtype)`, the same value FSDP2 gives its unsharded parameter's `grad_dtype`. An fp32 gradient flowing in is kept, and a bf16 one is cast up exactly.
- **Backward:** all-reduce (P -> I) over the non-DP axes where the parameter is R, then Partial -> the DP placements (reduce-scatter for FSDP, all-reduce for DDP, both for HSDP), all in `reduce_dtype`, in one node with no bf16 intermediate.

Both branches of `ReplicateComputation.replicate_compute` (with and without TP/EP axes) use it, replacing the `redistribute -> to_local -> spmd.convert` chain.

Dynamo cannot trace `ctx.set_output_grad_dtype` yet, so the call is skipped under `torch.compile`. GraphTrainer traces with `make_fx` and is unaffected; only the SimpleFSDP unit tests that use `torch.compile(backend="aot_eager")` take this path, and none uses mixed precision. The guard can go once the Dynamo support (pytorch PR, TODO: link) is in the nightly.

**Compared to #5106**, which all-gathers R parameters in fp32 so the TP sum stays fp32:
- the all-gather stays in bf16, so there are no extra fp32 all-gather buckets (#5106: 15 -> 28 in the Llama3 debug model);
- it also fixes issue 2, which #5106 cannot reach because the router's rounding happens before the TP sum.

8x H100, torch 2.16.0a0+gitbe3a22f (includes pytorch#194434), 20 steps, eager vs GraphTrainer:

| Test | main | this PR |
|---|---|---|
| `test_dense_llama3_aot_fx_trace_vs_eager` | diverges at step 2 (xfail) | bitwise |
| `test_dense_qwen3_aot_fx_trace_vs_eager` | diverges (xfail) | bitwise |
| `test_moe_qwen3_aot_fx_trace_vs_eager` | diverges from step 2 (xfail) | bitwise (loss and grad_norm) |
| `test_dense_llama3_hsdp_gradient_accumulation_aot_fx_trace_vs_eager` | | bitwise |
| `test_dense_llama3_hsdp_graph_pp_vs_eager` | | bitwise |

- `test_numerics.py`: the five tests above pass. The strict xfails from #5110 and #5133 are removed, and the MoE test now uses the bitwise `run_loss_compare` instead of `run_loss_compare_close`.
- New `TestSimpleFSDP` tests, both failing on main by exactly the rounded-off amount:
  - `test_tp_reduced_grad_stays_in_reduce_dtype`: per-TP-rank grads 1 and 2**-9 (exact in bf16, but their sum is not) must reach the reduce-scatter as 1 + 2**-9.
  - `test_wide_grad_reaches_reduce_scatter`: an fp32 wgrad with a sub-bf16 term must keep it.
- `TestSimpleFSDP` + `test_simple_fsdp.py`: pass (uneven/transposed shards, DDP/HSDP + TP, EP + TP, compiled variants).
- `test_bitwise_deterministic.py` and `test_passes.py` + `test_graph_pp_passes.py` passed before rebasing onto #4859.
- ufmt, flake8, codespell and pyrefly pass on the changed files.

ghstack-source-id: 50d1561
Pull Request resolved: #5171
pianpwk added a commit that referenced this pull request Oct 13, 2026
… does (#5171)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* __->__ #5171

This fixes a numerics mismatch between eager FSDP2 and SimpleFSDP
(GraphTrainer).

pytorch/pytorch#194434 ("[FSDP2] Separate sharded and unsharded gradient
dtypes", 38d3f6fd0d6e, in the 2026-10-02 nightly) changes the dtype of
FSDP2's unsharded-parameter gradients when `grad_dtype` is not
specified: they now default to `reduce_dtype` instead of `param_dtype`.
With torchtitan's mixed-precision policy, that is fp32 instead of bf16.

This changes the backward all-reduce of TP-replicated parameters (typed
R on TP, e.g. sequence-parallel norm weights and the MoE router gate):
eager FSDP2 now sums the per-TP-rank partial gradients in fp32 and
reduce-scatters the fp32 sum. SimpleFSDP also sums them in fp32, but the
sum is rounded back down to bf16 to match the dtype of SimpleFSDP's
unsharded weight, a bf16 autograd intermediate, before the
reduce-scatter. The router gate's `grad_weight`, which `HiMidLoLinear`
computes in fp32, is rounded the same way. As a result the dense
Llama3/Qwen3 and the Qwen3 MoE numerics tests diverge from eager at step
2, and are xfailed in #5110 and #5133.

This PR adds a custom autograd Function that runs SimpleFSDP's gradient
reductions the way FSDP2 does. All of those tests match eager bitwise
again, and their xfails are removed.

## Backward, before and after

Both sides use torchtitan's default mixed-precision settings:

| Field | Value | Source |
|---|---|---|
| master (sharded) param dtype | fp32 | |
| `param_dtype` | bf16 | `training.mixed_precision_param` |
| `reduce_dtype` | fp32 | `training.mixed_precision_reduce` |
| `grad_dtype` on the param | unset | |

### Issue 1: R-on-TP parameters (e.g. sequence-parallel norm weights)

Each TP rank computes a partial gradient (over its tokens), which must
be summed over TP before the FSDP reduce-scatter.

```
Eager FSDP2
  compute -> wgrad bf16
  -> LEAF .grad: unsharded param, grad_dtype = reduce_dtype       -> fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  compute -> wgrad bf16
  -> spmd.convert(I -> R) bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- rounds the TP sum
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  compute -> wgrad bf16
  -> output grad dtype declared fp32                              -> cast up (exact)
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

### Issue 2: MoE router gate (HiMidLoLinear, also R on TP)

`HiMidLoLinear`'s backward computes `grad_weight` in fp32 by design.

```
Eager FSDP2
  HiMidLo bwd -> grad_weight fp32
  -> LEAF .grad: grad_dtype = reduce_dtype                        -> kept fp32
     ---- autograd ends; FSDP2 post-backward ----
  -> TP all-reduce (fp32) -> reduce-scatter (fp32)

SimpleFSDP on main
  HiMidLo bwd -> grad_weight fp32
  -> autograd casts to convert output's dtype (bf16)              <- issue 2
  -> convert bwd: cast fp32, TP all-reduce (fp32)
  -> autograd casts to the bf16 all-gathered weight's dtype       <- issue 1
  -> redistribute bwd: cast fp32, reduce-scatter (fp32)

SimpleFSDP, this PR
  HiMidLo bwd -> grad_weight fp32
  -> output grad dtype declared fp32                              -> kept fp32
  -> _UnshardAndReduceGradFunction bwd: TP all-reduce (fp32), reduce-scatter (fp32)
```

For every other parameter, the bf16 wgrad reaches the reduce-scatter
with no reduction in between, and the bf16 -> fp32 cast is exact
wherever it happens, so those gradients already matched eager.

## Fix

`_UnshardAndReduceGradFunction` covers one parameter's unshard and
gradient reduction:

- **Forward:** wrap the TP/EP-local shard as a DTensor on the DP mesh,
cast to `param_dtype`, all-gather (no-op for DDP), and return the
unsharded weight. Same ops as before.
- **Output gradient dtype:** `ctx.set_output_grad_dtype(reduce_dtype)`,
the same value FSDP2 gives its unsharded parameter's `grad_dtype`. An
fp32 gradient flowing in is kept, and a bf16 one is cast up exactly.
- **Backward:** all-reduce (P -> I) over the non-DP axes where the
parameter is R, then Partial -> the DP placements (reduce-scatter for
FSDP, all-reduce for DDP, both for HSDP), all in `reduce_dtype`, in one
node with no bf16 intermediate.

Both branches of `ReplicateComputation.replicate_compute` (with and
without TP/EP axes) use it, replacing the `redistribute -> to_local ->
spmd.convert` chain.

Dynamo cannot trace `ctx.set_output_grad_dtype` yet, so the call is
skipped under `torch.compile`. GraphTrainer traces with `make_fx` and is
unaffected; only the SimpleFSDP unit tests that use
`torch.compile(backend="aot_eager")` take this path, and none uses mixed
precision. The guard can go once the Dynamo support (pytorch PR,
pytorch/pytorch#200311) is in the nightly.

**Compared to #5106**, which all-gathers R parameters in fp32 so the TP
sum stays fp32:
- the all-gather stays in bf16, so there are no extra fp32 all-gather
buckets (#5106: 15 -> 28 in the Llama3 debug model);
- it also fixes issue 2, which #5106 cannot reach because the router's
rounding happens before the TP sum.

## Results

8x H100, torch 2.16.0a0+gitbe3a22f (includes pytorch#194434), 20 steps,
eager vs GraphTrainer:

| Test | main | this PR |
|---|---|---|
| `test_dense_llama3_aot_fx_trace_vs_eager` | diverges at step 2 (xfail)
| bitwise |
| `test_dense_qwen3_aot_fx_trace_vs_eager` | diverges (xfail) | bitwise
|
| `test_moe_qwen3_aot_fx_trace_vs_eager` | diverges from step 2 (xfail)
| bitwise (loss and grad_norm) |
| `test_dense_llama3_hsdp_gradient_accumulation_aot_fx_trace_vs_eager` |
| bitwise |
| `test_dense_llama3_hsdp_graph_pp_vs_eager` | | bitwise |

## Test plan

- `test_numerics.py`: the five tests above pass. The strict xfails from
#5110 and #5133 are removed, and the MoE test now uses the bitwise
`run_loss_compare` instead of `run_loss_compare_close`.
- New `TestSimpleFSDP` tests, both failing on main by exactly the
rounded-off amount:
- `test_tp_reduced_grad_stays_in_reduce_dtype`: per-TP-rank grads 1 and
2**-9 (exact in bf16, but their sum is not) must reach the
reduce-scatter as 1 + 2**-9.
- `test_wide_grad_reaches_reduce_scatter`: an fp32 wgrad with a sub-bf16
term must keep it.
- `TestSimpleFSDP` + `test_simple_fsdp.py`: pass (uneven/transposed
shards, DDP/HSDP + TP, EP + TP, compiled variants).
- `test_bitwise_deterministic.py` and `test_passes.py` +
`test_graph_pp_passes.py` passed before rebasing onto #4859.
- ufmt, flake8, codespell and pyrefly pass on the changed files.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/h100.8 Trigger H100.8 CI CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants