Skip to content

[graph_trainer] Reduce SimpleFSDP gradients in reduce_dtype, as FSDP2 does - #5171

Merged
pianpwk merged 6 commits into
mainfrom
gh/pianpwk/111/head
Oct 13, 2026
Merged

pianpwk merged 6 commits into
mainfrom
gh/pianpwk/111/head

Conversation

@pianpwk

@pianpwk pianpwk commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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:

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 Xfail dense AOT FX numerics tests #5110 and [graph_trainer] Fix Qwen3 MoE eager numerics config; xfail its test #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 [graph_trainer] Optimize HSDP gradient collective order #4859.
  • ufmt, flake8, codespell and pyrefly pass on the changed files.

[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label 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
pianpwk marked this pull request as ready for review October 8, 2026 21:04
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 8, 2026
@tianyu-l
tianyu-l requested a review from soulitzer October 8, 2026 22:39
return grad_weight, None


class _UnshardAndReduceGradFunction(torch.autograd.Function):

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.

question to @soulitzer -- if we are able to set grad dtype on non-leaf nodes, can we avoid this

unsharded_dtensor = sharded_dtensor.redistribute(
placements=[Replicate()] * dp_mesh.ndim, forward_dtype=param_dtype
)
return unsharded_dtensor.to_local()

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.

In the previous implementation we were doing spmd.convert_type(src=I, dst=R, ...) which ensures autograd does the all_reduce in the backward, but it also means the output from replicate_computation would have the spmd_types metadata annotation on the tensor.

In this new impl, we won't have the metadata annotations which could break downstream code that was expecting it? (agree, it is unlikely).

We probably don't want to do spmd.convert (I->R) inside the custom autograd function, but is there a different "set_type" method to just tag the annotation?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think graph trainer + spmd typecheck isn't a thing yet, but we can spmd_typecheck the autograd Fn

return output
# Re-wrap the TP/EP-local tensor as a DTensor on dp_mesh for an efficient
# FSDP all-gather.
# TODO: DTensor should support this mesh collapsing operation

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.

Is this TODO something we expect to act upon? File an Issue in that case and link here?

[ghstack-poisoned]
[ghstack-poisoned]
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
pianpwk changed the base branch from gh/pianpwk/111/base to main October 12, 2026 16:54
[ghstack-poisoned]
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
[ghstack-poisoned]
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
pianpwk merged commit c299183 into main Oct 13, 2026
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 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.

3 participants