Skip to content

Xfail dense AOT FX numerics tests - #5110

Merged
aditvenk merged 1 commit into
mainfrom
xfail-dense-aot-fx-numerics
Oct 7, 2026
Merged

aditvenk merged 1 commit into
mainfrom
xfail-dense-aot-fx-numerics

Conversation

@aditvenk

@aditvenk aditvenk commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

The dense Llama3 and Qwen3 AOT FX trace comparisons currently diverge from eager on PyTorch nightly. Mark them as strict expected failures until the underlying issue is fixed.

Track the proper fix in #5109.

The dense Llama3 and Qwen3 AOT FX trace comparisons currently diverge from eager on PyTorch nightly. Mark them as strict expected failures until the underlying issue is fixed.

Track the proper fix in #5109.
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 7, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 7, 2026
@aditvenk

aditvenk commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

looks like there is another failing test, which we can address in next PR.

@aditvenk
aditvenk merged commit 0024eae into main Oct 7, 2026
aditvenk added a commit that referenced this pull request Oct 8, 2026
…5133)

test_moe_qwen3_aot_fx_trace_vs_eager fails on the H100 GraphTrainer CI
(AssertionError: False is not true). It runs after the GraphTrainer H100
integration tests, in the same workflow step under bash -eo pipefail.
Those integration tests failed on main until #5109, so this test only
started running once they passed.

This change makes the test's eager baseline config match GraphTrainer,
then marks the test as a strict expected failure, like the dense tests
in #5110. Two gradient mismatches remain. In both, eager FSDP2 keeps a
gradient in fp32 where SimpleFSDP rounds it to bf16.

Eager config fix
----------------

qwen3_moe_eager_numerics compiled the model's local compile regions
(loss, fused_binary_activation, cos_sin_rope, fp32_to_bf16_split).
GraphTrainer requires model.local_compile_regions = [] and runs that
code uncompiled. The dense eager configs already set it to [] to match
GraphTrainer; the MoE one did not. As a result, the step-1 loss differed
by 3.9e-5 before any gradient was involved. With the regions off, step 1
matches eager bitwise and the losses diverge from step 2, which isolates
the two gradient issues below.

Issue 1: TP-reduced norm weight gradients (same as the dense tests)
-------------------

This is the issue #5106 identified for the dense Llama3 and Qwen3 tests.

- Each RMSNorm weight is replicated over TP (typed spmd.R), while its
input is sharded over TP: on the sequence for attention_norm, ffn_norm
and the final norm (sequence parallel), and on heads for the Qwen3 QK
norms (q_norm, k_norm). So each TP rank computes a partial gradient, and
the partials are summed over TP.
- Since the dev20261002 nightly, PyTorch sets grad_dtype = reduce_dtype
(fp32) on FSDP2's unsharded parameter (pytorch 38d3f6fd0d6e, "[FSDP2]
Separate sharded and unsharded gradient dtypes", per #5106). Eager FSDP2
therefore sums the partials in fp32 and reduce-scatters the fp32 sum.
- SimpleFSDP also sums them in fp32, in the backward of spmd.convert(I
-> R). But the sum flows into the bf16 all-gathered weight, and autograd
casts a gradient to its tensor's dtype, so it is rounded to bf16 before
the reduce-scatter.

Evidence, comparing every parameter's gradient after step 1 (eager vs
GraphTrainer, dp_shard=4, tp=2, ep=2, eager regions off):

- The 33 norm weights (attention_norm, ffn_norm, q_norm and k_norm in
each of the 8 layers, plus the final norm) differ by about 1e-3
relative. Every matmul weight is bitwise equal.
- Locally applying the #5106 workaround makes all 33 match bitwise. The
workaround all-gathers parameters that have an R axis outside DP in fp32
and lets spmd.convert cast them to bf16, so the TP-reduced gradient
stays fp32. With it, the dense Llama3 and Qwen3 tests also match eager
bitwise for all 20 steps on 8 GPUs.

Issue 2: router gate grad_weight
--------------------------------

- The MoE router gate is a HiMidLoLinear, whose backward returns
grad_weight in fp32 by design.
- In eager FSDP2 the gate weight is the unsharded parameter itself: an
autograd leaf whose grad_dtype is fp32 (the same FSDP2 change). So the
fp32 grad_weight is kept.
- In SimpleFSDP the gate weight is computed from the parameter (it is
all-gathered and cast to bf16), so it is a bf16 non-leaf. Autograd
therefore rounds the fp32 grad_weight to bf16. This is
pytorch/pytorch#189633, also noted in HiMidLoLinear's TODO and in
_run_qwen3_moe_loss_compare.
- The rounding happens on each TP rank's partial gradient, before the TP
sum, so the #5106 approach does not reach it. With the workaround
applied, the 8 router gate weights (one per layer) still differ in every
element, by about 1e-3 relative, and they are the only gradients that
still differ.

Since #4923, this test compares losses with run_loss_compare_close
(rtol=1e-4) to tolerate the router difference. Together, the two issues
now push the losses past that tolerance.

Results (8x H100, torch 2.16.0.dev20261007, 20 steps, eager vs
GraphTrainer):

  config                                  first diff   max |loss diff|
  MoE, eager regions on (before)          step 1       1.39e-3
  MoE, eager regions off (this change)    step 2       1.50e-3
  MoE, regions off + #5106 workaround     step 2       1.86e-3
  dense Llama3 / Qwen3 + #5106 workaround bitwise      0

Test Plan:

- Ran _run_qwen3_moe_loss_compare on this branch (8x H100, torch
2.16.0.dev20261007): step 1 matches eager bitwise, and the losses
diverge from step 2 (max 1.50e-3 at step 19, above rtol=1e-4). The test
still fails, so the strict xfail holds.
- The gradient comparisons and #5106 workaround runs above were local
experiments and are not part of this change.
- ufmt, flake8 and codespell pass on the changed files.
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 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.

2 participants