Repository navigation
[graph_trainer] Reduce SimpleFSDP gradients in reduce_dtype, as FSDP2 does - #5171
Conversation
[ghstack-poisoned]
… 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
| return grad_weight, None | ||
|
|
||
|
|
||
| class _UnshardAndReduceGradFunction(torch.autograd.Function): |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Is this TODO something we expect to act upon? File an Issue in that case and link here?
[ghstack-poisoned]
… 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
… 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
… 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
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_dtypeis not specified: they now default toreduce_dtypeinstead ofparam_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, whichHiMidLoLinearcomputes 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:
param_dtypetraining.mixed_precision_paramreduce_dtypetraining.mixed_precision_reducegrad_dtypeon the paramIssue 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.
Issue 2: MoE router gate (HiMidLoLinear, also R on TP)
HiMidLoLinear's backward computesgrad_weightin fp32 by design.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
_UnshardAndReduceGradFunctioncovers one parameter's unshard and gradient reduction:param_dtype, all-gather (no-op for DDP), and return the unsharded weight. Same ops as before.ctx.set_output_grad_dtype(reduce_dtype), the same value FSDP2 gives its unsharded parameter'sgrad_dtype. An fp32 gradient flowing in is kept, and a bf16 one is cast up exactly.reduce_dtype, in one node with no bf16 intermediate.Both branches of
ReplicateComputation.replicate_compute(with and without TP/EP axes) use it, replacing theredistribute -> to_local -> spmd.convertchain.Dynamo cannot trace
ctx.set_output_grad_dtypeyet, so the call is skipped undertorch.compile. GraphTrainer traces withmake_fxand is unaffected; only the SimpleFSDP unit tests that usetorch.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_dense_llama3_aot_fx_trace_vs_eagertest_dense_qwen3_aot_fx_trace_vs_eagertest_moe_qwen3_aot_fx_trace_vs_eagertest_dense_llama3_hsdp_gradient_accumulation_aot_fx_trace_vs_eagertest_dense_llama3_hsdp_graph_pp_vs_eagerTest 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 bitwiserun_loss_compareinstead ofrun_loss_compare_close.TestSimpleFSDPtests, 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.pyandtest_passes.py+test_graph_pp_passes.pypassed before rebasing onto [graph_trainer] Optimize HSDP gradient collective order #4859.