Skip to content

[FSDP2] Keep the unsharded grad_dtype fixed across forward and backward - #200196

Closed
weifengpy wants to merge 5 commits into
gh/weifengpy/221/basefrom
gh/weifengpy/221/head
Closed

weifengpy wants to merge 5 commits into
gh/weifengpy/221/basefrom
gh/weifengpy/221/head

Conversation

@weifengpy

@weifengpy weifengpy commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):


  • accumulation across backwards without gradient sync stays in FP32
  • TP grad reduction stays in FP32

Authored with Claude Code.

#198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. #199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of #199856's table), undoing #198668 under compile. This PR is the FSDP-side prerequisite for #199856.

The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it. Parameters whose sharded tensor implements FSDP's all-gather extension (fsdp_pre_all_gather) never defer: an extension runs its own compute, which may read grad_dtype to pick the dtype its backward produces, so grad_dtype stays the unsharded gradient dtype for them. torchtitan's MXFP8 linear reads it in forward and writes its weight gradient in that dtype; under the pre_forward choice alone it would see None and write BF16.

Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral.

Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Extension-backed parameters no longer defer. For one whose backward writes grad_dtype, such as torchtitan's MXFP8 linear, nothing changes. One that hard-codes a BF16 weight gradient, such as torchtitan's NVFP4 linear, now gets autograd's per-parameter cast to FP32 and holds the FP32 gradient until the copy-in; pytorch/torchtitan#5180 makes NVFP4 write its weight gradient in grad_dtype, which removes the cast. Other code that reads grad_dtype during forward sees None in a forward that defers. Once #199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since #199856 guards on grad_dtype. Extension-backed parameters keep a fixed grad_dtype, so they add no recompiles. FSDP only sets None or the wider dtype, so #199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs.

The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms.

Test Plan

test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations. test_grad_dtype_fixed_for_all_gather_extensions attaches a plain all-gather extension and checks that the forward sees FP32 in two microbatches without gradient sync and a synced one, that autograd delivers FP32 gradients each time, and that 256 + 1 - 256 accumulates to 1. test_grad_dtype_seen_by_all_gather_extension_compute uses a custom autograd Function that, like torchtitan's MXFP8 linear, picks its weight gradient's dtype in forward; it sees FP32, and the reduced gradient keeps (1 + 2^-7)^2 exactly. Both fail without the extension rule, where the forward sees None.

At this revision on B200 GPUs, the mixed precision file (31 tests), the all-gather extensions file (7), and the training and pipeline-with-FSDP mixed precision selections (3 and 8, including the zero-bubble schedules) pass, and lint passes. The compile selection (7) passed on the previous revision; the extension rule doesn't change those tests. The zero-bubble, chunked-loss, interleaved-microbatch and multi-use claims above come from a single-rank CPU (gloo) script, run before the extension rule, which doesn't affect those scenarios.

PY=/home/weif/.conda/envs/code-review/bin/python
$PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
$PY test/distributed/_composable/fsdp/test_fully_shard_extensions.py
$PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision"
$PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp"
$PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP"
PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/200196

Note: Links to docs will display an error until the docs builds have been completed.

⏳ 1 Pending, 1 Unrelated Failure

As of commit 90bb492 with merge base 2eb7361 (image):

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • Numerics
    • init_unsharded_param now sets grad_dtype=None for the parameter's lifetime when defers_grad_upcast holds, so autograd no longer casts gradients to FP32
    • The PR body says multi-use params are now accumulated in BF16 inside autograd, a change in accumulation precision
    • Test now expects grad_dtypes == [torch.bfloat16] * 3 instead of an FP32 first gradient
  • Behavior change in FSDP2 mixed precision
    • Removes _set_unsharded_grad_dtypes from pre_backward and _reset_iter_state, replacing it with _upcast_unreduced_grads in post_backward
    • User-visible unsharded_param.grad_dtype changes from torch.float32 to None, per the updated asserts in test_fully_shard_mixed_precision.py
  • Triviality
    • A redesign of when gradients get upcast, not a single-cause bugfix or a mechanical refactor; an FSDP owner should review it

reason: not_trivial
Reviewed commit: a84eb9d (NOT the current head 90bb492)

Inference job

🐛 Report a wrong verdict

FLAKY - The following job failed but was likely due to flakiness present on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Oct 7, 2026
weifengpy added a commit that referenced this pull request Oct 7, 2026
> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph.
>
> This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral.
>
> Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype.
>
> Test Plan
>
> test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct.
>
> On B200s, with this revision's Python on a PyTorch build from a few days earlier, test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 29 s) and on four (80 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> T=test/distributed/_composable/fsdp
> for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> git diff HEAD~1 --check
> ```

ghstack-source-id: a5a3242
Pull-Request: #200196
weifengpy added a commit that referenced this pull request Oct 7, 2026
> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph.
>
> This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral.
>
> Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype.
>
> Test Plan
>
> test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct.
>
> On B200s, with PyTorch built at this change's base (2eb7361), test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 37 s) and on four (65 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> T=test/distributed/_composable/fsdp
> for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> git diff HEAD~1 --check
> ```

ghstack-source-id: a5a3242
Pull-Request: #200196
weifengpy added a commit that referenced this pull request Oct 7, 2026
> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph.
>
> This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral.
>
> Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype.
>
> Test Plan
>
> test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct.
>
> On B200s, with PyTorch built at this change's base (2eb7361), test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 37 s) and on four (65 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> T=test/distributed/_composable/fsdp
> for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> git diff HEAD~1 --check
> ```

ghstack-source-id: a5a3242
Pull-Request: #200196
weifengpy added a commit that referenced this pull request Oct 7, 2026
> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph.
>
> This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral.
>
> Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype.
>
> Test Plan
>
> test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct.
>
> On B200s, with PyTorch built at this change's base (2eb7361), test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 37 s) and on four (65 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes.
>
> Benchmarks ran on two B200s with one build of the base, the base's runs loading its _fsdp_param.py and _fsdp_param_group.py, with FP32 parameters, param_dtype=torch.bfloat16 and reduce_dtype=torch.float32. Each step runs two backwards without gradient sync, then one that reduces; times are the wall time of loss.backward(), the median of 30 steps after 5 warmup steps. For 3000 parameters from 1500 Linear(256, 256) in 30 groups, the first backward, where the upcast moves from autograd to post_backward, takes 6.7 ms less than in the base (median over six alternating runs; per-run differences from +1.1 to -19.7 ms, out of about 160-195 ms). The second and the final backward, which defer in both, differ by -2.8 and +0.8 ms, within the runs' noise of about 15 ms. For 8 Linear(2048, 2048) layers in one group, the two backwards without gradient sync take 1.07-1.16 ms versus 1.32-1.51 ms in the base, over two runs each, and the one that reduces 3.19-3.20 ms versus 3.18 ms. Peak memory above each backward's start is unchanged, except in the first backward for the 3000 parameters: 385.1 MiB versus 391.2 MiB, since fresh gradients stay BF16 until post_backward.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> T=test/distributed/_composable/fsdp
> for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> git diff HEAD~1 --check
> ```

ghstack-source-id: a5a3242
Pull-Request: #200196
@weifengpy
weifengpy marked this pull request as ready for review October 8, 2026 00:08
@weifengpy weifengpy added release notes: distributed (fsdp2) release notes category and removed release notes: distributed (fsdp) release notes category labels Oct 8, 2026
self._take_unsharded_grads_to_reduce()
)
self._set_unsharded_grad_dtypes(defer_upcast=False)
self._upcast_unreduced_grads()

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.

nit: isn't this dead code because _take_unsharded_grads_to_reduce() just above iterates over every param via _reduce_scatter_param_indices and sets unsharded_param.grad = None for each grad it takes. This means every param.grad in the group is None, so _upcast_unreduced_grads() will take the continue branch for all params?

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.

good catch! updated the PR

[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Oct 8, 2026
sets grad_dtype=None once, when the unsharded parameter is created
* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

the numeric change is multi-use param in autograd are accumualted in bf16, which trunk already does for 1D with reduce-scatter

this simplifies #199856

ghstack-source-id: e22d589
Pull-Request: #200196
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Oct 8, 2026
sets grad_dtype=None once, when the unsharded parameter is created
* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

the numeric change is multi-use param in autograd are accumualted in bf16, which trunk already does for 1D with reduce-scatter

this simplifies #199856

ghstack-source-id: b7be99a
Pull-Request: #200196
@weifengpy
weifengpy marked this pull request as draft October 8, 2026 07:46
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Oct 8, 2026
* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. #199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of #199856's table), undoing #198668 under compile. This PR is the FSDP-side prerequisite for #199856.
>
> The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it.
>
> Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral.
>
> Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Code that reads grad_dtype during forward, such as torchtitan's MXFP8 linear, sees None in a forward that defers and produces BF16 weight gradients there instead of FP32. Once #199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since #199856 guards on grad_dtype. FSDP only sets None or the wider dtype, so #199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs.
>
> The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms.
>
> Test Plan
>
> test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations.
>
> On B200 GPUs, the mixed precision file (29 tests), the training and compile selections (3 and 7) and the pipeline-with-FSDP mixed precision cases, including the zero-bubble schedules (8), pass on the previous local revision, which differs from this one only in the list's name and two comments. At this revision lint passes, and a single-rank CPU (gloo) run of the zero-bubble, chunked-loss, interleaved-microbatch and multi-use scenarios gives the results described above.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision"
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp"
> $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP"
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> ```

ghstack-source-id: 231c3e8
Pull-Request: #200196
@weifengpy weifengpy added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 8, 2026
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Oct 8, 2026
* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

> Authored with Claude Code.
>
> #198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. #199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of #199856's table), undoing #198668 under compile. This PR is the FSDP-side prerequisite for #199856.
>
> The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it. Parameters whose sharded tensor implements FSDP's all-gather extension (fsdp_pre_all_gather) never defer: an extension runs its own compute, which may read grad_dtype to pick the dtype its backward produces, so grad_dtype stays the unsharded gradient dtype for them. torchtitan's MXFP8 linear reads it in forward and writes its weight gradient in that dtype; under the pre_forward choice alone it would see None and write BF16.
>
> Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral.
>
> Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Extension-backed parameters no longer defer. For one whose backward writes grad_dtype, such as torchtitan's MXFP8 linear, nothing changes. One that hard-codes a BF16 weight gradient, such as torchtitan's NVFP4 linear, now gets autograd's per-parameter cast to FP32 and holds the FP32 gradient until the copy-in; pytorch/torchtitan#5180 makes NVFP4 write its weight gradient in grad_dtype, which removes the cast. Other code that reads grad_dtype during forward sees None in a forward that defers. Once #199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since #199856 guards on grad_dtype. Extension-backed parameters keep a fixed grad_dtype, so they add no recompiles. FSDP only sets None or the wider dtype, so #199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs.
>
> The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms.
>
> Test Plan
>
> test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations. test_grad_dtype_fixed_for_all_gather_extensions attaches a plain all-gather extension and checks that the forward sees FP32 in two microbatches without gradient sync and a synced one, that autograd delivers FP32 gradients each time, and that 256 + 1 - 256 accumulates to 1. test_grad_dtype_seen_by_all_gather_extension_compute uses a custom autograd Function that, like torchtitan's MXFP8 linear, picks its weight gradient's dtype in forward; it sees FP32, and the reduced gradient keeps (1 + 2^-7)^2 exactly. Both fail without the extension rule, where the forward sees None.
>
> At this revision on B200 GPUs, the mixed precision file (31 tests), the all-gather extensions file (7), and the training and pipeline-with-FSDP mixed precision selections (3 and 8, including the zero-bubble schedules) pass, and lint passes. The compile selection (7) passed on the previous revision; the extension rule doesn't change those tests. The zero-bubble, chunked-loss, interleaved-microbatch and multi-use claims above come from a single-rank CPU (gloo) script, run before the extension rule, which doesn't affect those scenarios.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> $PY test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision"
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp"
> $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP"
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> ```

ghstack-source-id: 28eaeed
Pull-Request: #200196
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 8, 2026
> Authored with Claude Code.
>
> NVFP4Linear's backward always wrote its weight gradient in BF16. Under FSDP2 with an FP32 reduce dtype, that gradient has already lost its low bits before it is widened, either by autograd (one cast kernel per weight per backward, plus a BF16 temporary) or by the reduce-scatter copy-in. This records the parameter's grad_dtype in forward, as MXFP8Linear does, and has the WGRAD scaled_mm write that dtype directly. The GEMM accumulates in FP32, so its FP32 output is the BF16 one before rounding. Without FSDP, or with a BF16 reduce dtype, grad_dtype is BF16 and nothing changes.
>
> pytorch/pytorch#200196 makes FSDP2 keep grad_dtype at the unsharded gradient dtype for parameters backed by its all-gather extension, as NVFP4 and MXFP8 weights are, because their compute may read it. Without this change, NVFP4 weights then pay autograd's FP32 cast on every backward; with it, the GEMM writes FP32 and there is nothing to cast. On current PyTorch trunk, FSDP's forward also sees the FP32 grad_dtype, so this removes the BF16 rounding there too, at the cost of holding NVFP4 weight gradients in FP32 instead of BF16 until the reduce-scatter.
>
> Test Plan
>
> test_nvfp4_linear_wgrad_follows_grad_dtype runs the same NVFP4Linear with grad_dtype BF16 and FP32, for a plain weight and for FSDP's unsharded-weight holder, and checks that the FP32 weight gradient is FP32 and rounds exactly to the BF16 one. On a B200, a standalone NVFP4 x NVFP4 scaled_mm with two-level scales accepts output_dtype=torch.float32, and its output rounded to BF16 equals the BF16 output. Lint passes except for 7 pyrefly errors in other files, which main also has. On B200, with a torchao developer build (0.19.0+gitcff77b46e) and a PyTorch build of pytorch/pytorch#200196 plus #199856: test_nvfp4_linear.py and test_nvfp4_fsdp.py give 9 passed and 1 failed with this change, versus 7 passed and the same failure on main. The failure is test_nvfp4_linear_runs_outside_plain_eager[compile], which can't find the cutlass (CuTeDSL) package in that environment. The environment also lacks attn-gym's optional CuTeDSL backend, which torchtitan.models.common imports at load, so these runs stub attn_gym.linear.short_conv with a sitecustomize. The MXFP8 tests, test_mxfp8_fsdp.py and test_mxfp8_linear.py, pass (32 tests), including the fused WGRAD accumulation with an FP32 reduce dtype under #200196's rule.
>
> ```bash
> PYTHONPATH=<dir with the attn_gym stub sitecustomize.py>:$PWD pytest tests/unit_tests/gpu/test_nvfp4_linear.py tests/unit_tests/gpu/test_nvfp4_fsdp.py
> PYTHONPATH=$PWD pytest tests/unit_tests/gpu/test_mxfp8_fsdp.py tests/unit_tests/gpu/test_mxfp8_linear.py
> pre-commit run --files torchtitan/quantization/nvfp4/linear.py tests/unit_tests/gpu/test_nvfp4_linear.py
> ```

ghstack-source-id: 3f46a55
Pull-Request: #5180
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Oct 8, 2026
> Authored with Claude Code.
>
> NVFP4Linear's backward always wrote its weight gradient in BF16. Under FSDP2 with an FP32 reduce dtype, that gradient has already lost its low bits before it is widened, either by autograd (one cast kernel per weight per backward, plus a BF16 temporary) or by the reduce-scatter copy-in. This records the parameter's grad_dtype in forward, as MXFP8Linear does, and has the WGRAD scaled_mm write that dtype directly. The GEMM accumulates in FP32, so its FP32 output is the BF16 one before rounding. Without FSDP, or with a BF16 reduce dtype, grad_dtype is BF16 and nothing changes.
>
> pytorch/pytorch#200196 makes FSDP2 keep grad_dtype at the unsharded gradient dtype for parameters backed by its all-gather extension, as NVFP4 and MXFP8 weights are, because their compute may read it. Without this change, NVFP4 weights then pay autograd's FP32 cast on every backward; with it, the GEMM writes FP32 and there is nothing to cast. On current PyTorch trunk, FSDP's forward also sees the FP32 grad_dtype, so this removes the BF16 rounding there too, at the cost of holding NVFP4 weight gradients in FP32 instead of BF16 until the reduce-scatter.
>
> Test Plan
>
> test_nvfp4_linear_wgrad_follows_grad_dtype runs the same NVFP4Linear with grad_dtype BF16 and FP32, for a plain weight and for FSDP's unsharded-weight holder, and checks that the FP32 weight gradient is FP32 and rounds exactly to the BF16 one. On a B200, a standalone NVFP4 x NVFP4 scaled_mm with two-level scales accepts output_dtype=torch.float32, and its output rounded to BF16 equals the BF16 output. Lint passes except for 7 pyrefly errors in other files, which main also has. On B200, with a torchao developer build (0.19.0+gitcff77b46e), attn-gym[linear] installed (CuTeDSL, so NVFP4's KernelPreference.AUTO runs the CuTeDSL kernels), and a PyTorch build of pytorch/pytorch#200196: test_nvfp4_linear.py and test_nvfp4_fsdp.py pass with this change (10 tests, including the two new ones), as they do on main (8). The MXFP8 tests, test_mxfp8_fsdp.py and test_mxfp8_linear.py, pass (32 tests), including the fused WGRAD accumulation with an FP32 reduce dtype under #200196's rule.
>
> ```bash
> PYTHONPATH=$PWD pytest tests/unit_tests/gpu/test_nvfp4_linear.py tests/unit_tests/gpu/test_nvfp4_fsdp.py
> PYTHONPATH=$PWD pytest tests/unit_tests/gpu/test_mxfp8_fsdp.py tests/unit_tests/gpu/test_mxfp8_linear.py
> pre-commit run --files torchtitan/quantization/nvfp4/linear.py tests/unit_tests/gpu/test_nvfp4_linear.py
> ```

ghstack-source-id: 3f46a55
Pull-Request: #5180
@weifengpy
weifengpy marked this pull request as ready for review October 9, 2026 00:35
@weifengpy

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

anijain2305 added a commit that referenced this pull request Oct 9, 2026
Summary (human written only)
----------------------------

grad_dtype is a recent PyTorch feature. This PR adds plumbing for compile.

There was a parallel effort in #197381. Some parts in this PR are borrowed from that PR, but that PR does more than necessary.

This PR raises exception when the `grad_dtype` changes between the compiled forward and backward but only when its narrowing

Under compile, a leaf's grad goes through two casts, while eager applies only one:
>
> ```
> compiled:  formula -> [A: in the graph, to the trace-time grad_dtype] -> [B: autograd engine, to the live grad_dtype] -> .grad
> eager:     formula ----------------------------------------------------> [B: autograd engine, to the live grad_dtype] -> .grad
> ```
>
> Cast A is baked into the traced backward (skipped when the formula already produces the trace-time grad_dtype). Cast B is the engine's normal cast into AccumulateGrad, using the grad_dtype set when backward runs. Compiled matches eager whenever A followed by B gives the same result as B alone, which holds unless A discarded bits that B would have kept. Only a narrowing cast discards bits:
>
> | Formula | Trace-time grad_dtype (cast A) | Live grad_dtype (cast B) | Compiled vs eager |
> |---|---|---|---|
> | fp32 (custom) | fp32 (none) | bf16 (narrow) | same |
> | fp32 (custom) | fp32 (none) | None (none) | same |
> | bf16 (normal mm) | bf16 (none) | fp32 (widen) | same |
> | bf16 (normal mm) | fp32 (widen) | None (none) | same values; fp32 instead of bf16 |
> | fp32 (custom) | bf16 (narrow) | fp32 or None | compiled is bf16-rounded |
>
> Only the last row loses precision through the cast: A narrowed fp32 to bf16 in the graph, and B can't restore the bits. A custom backward that reads grad_dtype (e.g. to pick its kernel) also bakes in the trace-time value. So the runtime records the trace-time grad_dtype of each grad-requiring leaf input and raises if it changes before backward. Inputs traced with None are not checked: their grads leave the graph uncast, and the engine applies the grad_dtype set at backward time, as in eager. FSDP2 (#200196) relies on this when an earlier microbatch's post_backward restores grad_dtype under a forward that chose None.

BC-breaking?
------------

No.

Agent details (if applicable)
-----------------------------
Claude (AI assistant) wrote the following analysis and test summary:

> **Bug:** a bf16 leaf with `grad_dtype=torch.float32` (set by FSDP2 for `reduce_dtype=torch.float32`) keeps a custom backward's fp32 gradient in eager. Under torch.compile the gradient is rounded to bf16: `.grad` is still fp32, but the low bits are gone.
>
> **Root cause:** the autograd engine casts each gradient to the receiving node's `InputMetadata.grad_dtype`, which defaults to the tensor's own dtype. When AOTAutograd traces the joint graph it wraps inputs (FunctionalTensor, and for subclasses a rebuilt subclass plus its functional wrapper) and calls `_mirror_autograd_meta_to`, which copies `requires_grad` but not `grad_dtype`. The wrapper's dummy grad_fn records bf16, so the engine bakes a `_to_copy(..., bfloat16)` into the traced backward.
>
> **Fix:** `copy_grad_dtype_override` copies the effective `grad_dtype` onto each wrapper before it gets a grad_fn, at all three wrapping sites: `FunctionalTensor.to_functional`, the subclass branch of `to_fun`, and `SubclassCreationMeta.creation_fn`. For non-leaves the `grad_dtype` getter returns the grad_fn's input metadata, so the same check works when the source is an already-mirrored wrapper. Copying the real value (rather than tracing with "accept any dtype") also keeps code that reads `grad_dtype` while AOTAutograd traces it correct, e.g. a custom op's `setup_context` choosing its GEMM output dtype.
>
> Because the backward graph depends on `grad_dtype`:
> - `TENSOR_MATCH` (C++ `TensorCheck`) checks `grad_dtype` for tensors that require grad. DTensor skips the outer `TENSOR_MATCH`, so it gets an explicit `grad_dtype` guard next to its `requires_grad` guard.
> - The AOTAutograd cache key includes `grad_dtype`, for plain tensors and for subclasses (whose stable hashes don't cover it).
> - Changing `grad_dtype` between forward and backward is checked at runtime as described in the Summary.
> - An existing `.grad` whose dtype differs from the param's no longer graph-breaks when the leaf's `grad_dtype` permits it, and meta conversion sets `grad_dtype` on the fake leaf before attaching the fake `.grad` (the gradient-accumulation case). These two pieces are adapted from #197381.
>
> **Alternative considered:** tracing the joint graph with `grad_dtype=None` on the input wrappers and letting the engine do the only cast at runtime. That matches eager for late `grad_dtype` changes and needs no guards, but code that reads `grad_dtype` during the AOTAutograd trace (custom-op `setup_context`, `allow_in_graph` Functions) then sees `None` and silently picks the narrower dtype.
>
> **Test Plan:**
>
> ```
> python -m pytest -q test/functorch/test_aotdispatch.py -k test_custom_autograd_grad_dtype
> python -m pytest -q test/distributed/tensor/test_dtensor_compile.py -k "test_custom_autograd_grad_dtype or test_aot_cache_key_grad_dtype"
> ```
>
> The DTensor tests call the same compiled callable with bf16 and then fp32 `grad_dtype` (it must recompile and match eager), and check that the DTensor cache key differs per `grad_dtype`. Both fail without the DTensor guard and cache-key fixes. The aotdispatch tests cover the original rounding, `grad_dtype` changes between forward and backward (raising when traced with a concrete dtype, matching eager when traced with None), and a custom backward that picks its kernel by reading `grad_dtype`.

ghstack-source-id: f45d7a1
Pull-Request: #199856
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…rd (pytorch#200196)

----

* accumulation across backwards without gradient sync stays in FP32
* TP grad reduction stays in FP32

> Authored with Claude Code.
>
> pytorch#198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. pytorch#199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of pytorch#199856's table), undoing pytorch#198668 under compile. This PR is the FSDP-side prerequisite for pytorch#199856.
>
> The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it. Parameters whose sharded tensor implements FSDP's all-gather extension (fsdp_pre_all_gather) never defer: an extension runs its own compute, which may read grad_dtype to pick the dtype its backward produces, so grad_dtype stays the unsharded gradient dtype for them. torchtitan's MXFP8 linear reads it in forward and writes its weight gradient in that dtype; under the pre_forward choice alone it would see None and write BF16.
>
> Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral.
>
> Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Extension-backed parameters no longer defer. For one whose backward writes grad_dtype, such as torchtitan's MXFP8 linear, nothing changes. One that hard-codes a BF16 weight gradient, such as torchtitan's NVFP4 linear, now gets autograd's per-parameter cast to FP32 and holds the FP32 gradient until the copy-in; pytorch/torchtitan#5180 makes NVFP4 write its weight gradient in grad_dtype, which removes the cast. Other code that reads grad_dtype during forward sees None in a forward that defers. Once pytorch#199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since pytorch#199856 guards on grad_dtype. Extension-backed parameters keep a fixed grad_dtype, so they add no recompiles. FSDP only sets None or the wider dtype, so pytorch#199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs.
>
> The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms.
>
> Test Plan
>
> test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations. test_grad_dtype_fixed_for_all_gather_extensions attaches a plain all-gather extension and checks that the forward sees FP32 in two microbatches without gradient sync and a synced one, that autograd delivers FP32 gradients each time, and that 256 + 1 - 256 accumulates to 1. test_grad_dtype_seen_by_all_gather_extension_compute uses a custom autograd Function that, like torchtitan's MXFP8 linear, picks its weight gradient's dtype in forward; it sees FP32, and the reduced gradient keeps (1 + 2^-7)^2 exactly. Both fail without the extension rule, where the forward sees None.
>
> At this revision on B200 GPUs, the mixed precision file (31 tests), the all-gather extensions file (7), and the training and pipeline-with-FSDP mixed precision selections (3 and 8, including the zero-bubble schedules) pass, and lint passes. The compile selection (7) passed on the previous revision; the extension rule doesn't change those tests. The zero-bubble, chunked-loss, interleaved-microbatch and multi-use claims above come from a single-rank CPU (gloo) script, run before the extension rule, which doesn't affect those scenarios.
>
> ```bash
> PY=/home/weif/.conda/envs/code-review/bin/python
> $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> $PY test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision"
> $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp"
> $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP"
> PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d)
> ```
Pull Request resolved: pytorch#200196
Approved by: https://github.com/anshul-si, https://github.com/anijain2305
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (fsdp2) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants