Skip to content

[FSDP2] Separate sharded and unsharded gradient dtypes - #194434

Closed
weifengpy wants to merge 7 commits into
gh/weifengpy/174/basefrom
gh/weifengpy/174/head
Closed

weifengpy wants to merge 7 commits into
gh/weifengpy/174/basefrom
gh/weifengpy/174/head

Conversation

@weifengpy

@weifengpy weifengpy commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Fixes #170648

feature 0: when mp_policy.reduce_dtype is None, it follows orig model.parameters() .grad_dtype. .grad_dtype were silently ignored before this PR

  • if orig grad_dtype is set, mp_policy.reduce_dtype is resolved to orig grad_dtype (including explicit None)
  • if not set, mp_policy.reduce_dtype is resolved to orig param dtype

this is BC breaking: mp_policy.reduce_dtype=None no longer defaults to mp_policy.param_dtype

  • [popular case] fp32 params, mp_policy(param_dtype=bf16)
    • before: grad accumulation and reduce happen in bf16
    • after: grad accumulation and reduce happen in fp32 (2x reduce-scatter bytes)
  • [rare case] bf16 params, mp_policy(param_dtype=fp32)
    • before: grad accumulation and reduce happen in fp32
    • after: grad accumulation and reduce happen in bf16

how to deal with BC: explicitly set mp_policy.reduce_dtype

feature 1: in grad accumulation (no reduce-scatter), the unsharded param's .grad always holds the accumulated value, visible via model.parameters() while unsharded. Before this PR, .grad was None when reduce_dtype was set and differed from param_dtype (FSDP kept the sum in a hidden reduce_dtype buffer)

memory difference

  • we need to land PR 198668 to keep backward peak in 256MB
Screenshot 2026-09-27 at 6 49 30 PM

perf difference
this PR does per-param 16 casts: increasing copy-time by ~50% ( 124 / (58 + 124) )

  • per-param castto fp32 in autograd: 58 us
  • fp32 copy-in: 124 us
  • need to land PR 198668 to bring them on par

Co-authored-by: Arkadip Maitra [email protected]

@pytorch-bot

pytorch-bot Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (3 Unrelated Failures)

As of commit 55bb0a8 with merge base 7310405 (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

UNSTABLE - The following job is marked as unstable, possibly due to flakiness 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 Aug 22, 2026
weifengpy added a commit that referenced this pull request Aug 23, 2026
…y-in cost

Stacked on a duplicate of #172074, which propagates Tensor.grad_dtype through
fully_shard. The PR below it is an unmodified copy of that work, pushed only
so this change diffs cleanly; #172074 itself is untouched and is the one that
should be reviewed and landed. Fold these corrections into it, or land them
after it.

Four issues, found while reviewing #172074 and each reproduced on 2xH100.

Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one
that matters. to_accumulated_grad_if_needed casts the unsharded gradient to
reduce_dtype before summing microbatches. That was written as an upcast (bf16
compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype
wider than reduce_dtype it becomes a downcast: with bf16 parameters,
grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch
sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype
was fp32 as requested while the precision grad_dtype exists to provide was
gone, so nothing surfaced the loss. An explicit grad_dtype now takes
precedence; for that config the gradients simply stay on
_unsharded_param.grad, which is the path already taken when reduce_dtype is
unset.

grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype,
None meaning any gradient dtype is allowed, or never assigned, in which case
the getter mirrors param.dtype. In foreach_reduce a None read back off the
parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op
and leaves the gradient in reduce_dtype. With fp32 parameters and
reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been
fp32, with no error, because grad_dtype=None also disables the dtype check on
gradient assignment. Fixed by reading the construction-time snapshot rather
than the live parameter, since the snapshot is what was propagated onto the
parameter autograd produced these gradients for. An explicit None is treated
as unset: the only thing that relaxation buys is skipping the dtype check when
someone assigns param.grad, and FSDP always assigns a gradient it just cast to
orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype
gradient afterwards now gets a clear error from the setter instead of silent
divergence.

The reduce-scatter copy-in staging buffer is not needed. It was added on the
premise that _chunk_cat rejects narrowing casts. It does not:
torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is
canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real,
float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard
also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16)
recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a
full-size gradient copy to every reduce-scatter. Separately,
torch.promote_types raises on float8 rather than returning a result, so for
float8 gradients the guard itself would have thrown.

reset_sharded_param re-stamped unconditionally. grad_dtype lives on the
parameter's autograd metadata and survives an in-place .data swap, so the
re-stamp is only required when _apply or load_state_dict(assign=True) installs
a replacement Parameter object. Re-stamping unconditionally could also raise
from the grad_dtype setter when a gradient of a different dtype was already
present, in a function that previously never raised there. Moved inside the
object-replacement branch.

Review the _fsdp_param.py state change first (the two snapshot fields), then
its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the
accumulation fix, then the tests.

Test Plan:

Full mixed-precision suite on 2 GPUs:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 19 passed in 116.67s
```

FSDP gradient accumulation, the path the accumulation fix touches:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation
# 1 passed, 38 deselected in 45.66s
```

Confirming the new coverage fails without the fix, by reverting only the
torch/ changes:

```
git stash push -- torch/
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q
git stash pop
# 3 failed, 3 passed:
#   FAILED test_grad_dtype_none_keeps_orig_dtype
#   FAILED test_grad_dtype_numerics_grad_acc
#   FAILED test_grad_dtype_preserved_grad_acc
```

test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before
and after fully_shard; only the after case reproduces the stale live read, so
both are exercised. test_grad_dtype_preserved_across_apply passes either way;
it is added as coverage for the reset_sharded_param path, not as a regression
test.

Accumulation precision, measured against a reference that mirrors FSDP's
reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce,
cast back) so the residual error is attributable to the accumulation dtype
alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches,
2 ranks:

    before: max relative error 5.747e-03
    after:  max relative error 0.000e+00

Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no
grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations,
2 ranks:

    before: 37183 MiB allocated, 13.24 ms/iter
    after:  32052 MiB allocated, 12.75 ms/iter

Peak allocated memory is unchanged at 736.7 MiB either way; the cost was
allocator traffic and step time, not peak capacity.

Authored with assistance from Claude Code (Anthropic).

ghstack-source-id: 5b41084
Pull-Request: #194434
weifengpy added a commit that referenced this pull request Aug 23, 2026
…y-in cost

Stacked on a duplicate of #172074, which propagates Tensor.grad_dtype through
fully_shard. The PR below it is an unmodified copy of that work, pushed only
so this change diffs cleanly; #172074 itself is untouched and is the one that
should be reviewed and landed. Fold these corrections into it, or land them
after it.

Four issues, found while reviewing #172074 and each reproduced on 2xH100.

Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one
that matters. to_accumulated_grad_if_needed casts the unsharded gradient to
reduce_dtype before summing microbatches. That was written as an upcast (bf16
compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype
wider than reduce_dtype it becomes a downcast: with bf16 parameters,
grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch
sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype
was fp32 as requested while the precision grad_dtype exists to provide was
gone, so nothing surfaced the loss. An explicit grad_dtype now takes
precedence; for that config the gradients simply stay on
_unsharded_param.grad, which is the path already taken when reduce_dtype is
unset.

grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype,
None meaning any gradient dtype is allowed, or never assigned, in which case
the getter mirrors param.dtype. In foreach_reduce a None read back off the
parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op
and leaves the gradient in reduce_dtype. With fp32 parameters and
reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been
fp32, with no error, because grad_dtype=None also disables the dtype check on
gradient assignment. Fixed by reading the construction-time snapshot rather
than the live parameter, since the snapshot is what was propagated onto the
parameter autograd produced these gradients for. An explicit None is treated
as unset: the only thing that relaxation buys is skipping the dtype check when
someone assigns param.grad, and FSDP always assigns a gradient it just cast to
orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype
gradient afterwards now gets a clear error from the setter instead of silent
divergence.

The reduce-scatter copy-in staging buffer is not needed. It was added on the
premise that _chunk_cat rejects narrowing casts. It does not:
torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is
canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real,
float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard
also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16)
recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a
full-size gradient copy to every reduce-scatter. Separately,
torch.promote_types raises on float8 rather than returning a result, so for
float8 gradients the guard itself would have thrown.

reset_sharded_param re-stamped unconditionally. grad_dtype lives on the
parameter's autograd metadata and survives an in-place .data swap, so the
re-stamp is only required when _apply or load_state_dict(assign=True) installs
a replacement Parameter object. Re-stamping unconditionally could also raise
from the grad_dtype setter when a gradient of a different dtype was already
present, in a function that previously never raised there. Moved inside the
object-replacement branch.

Review the _fsdp_param.py state change first (the two snapshot fields), then
its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the
accumulation fix, then the tests.

Test Plan:

Full mixed-precision suite on 2 GPUs:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 19 passed in 116.67s
```

FSDP gradient accumulation, the path the accumulation fix touches:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation
# 1 passed, 38 deselected in 45.66s
```

Confirming the new coverage fails without the fix, by reverting only the
torch/ changes:

```
git stash push -- torch/
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q
git stash pop
# 3 failed, 3 passed:
#   FAILED test_grad_dtype_none_keeps_orig_dtype
#   FAILED test_grad_dtype_numerics_grad_acc
#   FAILED test_grad_dtype_preserved_grad_acc
```

test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before
and after fully_shard; only the after case reproduces the stale live read, so
both are exercised. test_grad_dtype_preserved_across_apply passes either way;
it is added as coverage for the reset_sharded_param path, not as a regression
test.

Accumulation precision, measured against a reference that mirrors FSDP's
reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce,
cast back) so the residual error is attributable to the accumulation dtype
alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches,
2 ranks:

    before: max relative error 5.747e-03
    after:  max relative error 0.000e+00

Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no
grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations,
2 ranks:

    before: 37183 MiB allocated, 13.24 ms/iter
    after:  32052 MiB allocated, 12.75 ms/iter

Peak allocated memory is unchanged at 736.7 MiB either way; the cost was
allocator traffic and step time, not peak capacity.

Authored with assistance from Claude Code (Anthropic).

ghstack-source-id: 5b41084
Pull-Request: #194434
weifengpy added a commit that referenced this pull request Aug 23, 2026
…y-in cost

Stacked on a duplicate of #172074, which propagates Tensor.grad_dtype through
fully_shard. The PR below it is an unmodified copy of that work, pushed only
so this change diffs cleanly; #172074 itself is untouched and is the one that
should be reviewed and landed. Fold these corrections into it, or land them
after it.

Four issues, found while reviewing #172074 and each reproduced on 2xH100.

Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one
that matters. to_accumulated_grad_if_needed casts the unsharded gradient to
reduce_dtype before summing microbatches. That was written as an upcast (bf16
compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype
wider than reduce_dtype it becomes a downcast: with bf16 parameters,
grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch
sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype
was fp32 as requested while the precision grad_dtype exists to provide was
gone, so nothing surfaced the loss. An explicit grad_dtype now takes
precedence; for that config the gradients simply stay on
_unsharded_param.grad, which is the path already taken when reduce_dtype is
unset.

grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype,
None meaning any gradient dtype is allowed, or never assigned, in which case
the getter mirrors param.dtype. In foreach_reduce a None read back off the
parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op
and leaves the gradient in reduce_dtype. With fp32 parameters and
reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been
fp32, with no error, because grad_dtype=None also disables the dtype check on
gradient assignment. Fixed by reading the construction-time snapshot rather
than the live parameter, since the snapshot is what was propagated onto the
parameter autograd produced these gradients for. An explicit None is treated
as unset: the only thing that relaxation buys is skipping the dtype check when
someone assigns param.grad, and FSDP always assigns a gradient it just cast to
orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype
gradient afterwards now gets a clear error from the setter instead of silent
divergence.

The reduce-scatter copy-in staging buffer is not needed. It was added on the
premise that _chunk_cat rejects narrowing casts. It does not:
torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is
canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real,
float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard
also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16)
recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a
full-size gradient copy to every reduce-scatter. Separately,
torch.promote_types raises on float8 rather than returning a result, so for
float8 gradients the guard itself would have thrown.

reset_sharded_param re-stamped unconditionally. grad_dtype lives on the
parameter's autograd metadata and survives an in-place .data swap, so the
re-stamp is only required when _apply or load_state_dict(assign=True) installs
a replacement Parameter object. Re-stamping unconditionally could also raise
from the grad_dtype setter when a gradient of a different dtype was already
present, in a function that previously never raised there. Moved inside the
object-replacement branch.

Review the _fsdp_param.py state change first (the two snapshot fields), then
its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the
accumulation fix, then the tests.

Test Plan:

Full mixed-precision suite on 2 GPUs:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 19 passed in 116.67s
```

FSDP gradient accumulation, the path the accumulation fix touches:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation
# 1 passed, 38 deselected in 45.66s
```

Confirming the new coverage fails without the fix, by reverting only the
torch/ changes:

```
git stash push -- torch/
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q
git stash pop
# 3 failed, 3 passed:
#   FAILED test_grad_dtype_none_keeps_orig_dtype
#   FAILED test_grad_dtype_numerics_grad_acc
#   FAILED test_grad_dtype_preserved_grad_acc
```

test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before
and after fully_shard; only the after case reproduces the stale live read, so
both are exercised. test_grad_dtype_preserved_across_apply passes either way;
it is added as coverage for the reset_sharded_param path, not as a regression
test.

Accumulation precision, measured against a reference that mirrors FSDP's
reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce,
cast back) so the residual error is attributable to the accumulation dtype
alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches,
2 ranks:

    before: max relative error 5.747e-03
    after:  max relative error 0.000e+00

Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no
grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations,
2 ranks:

    before: 37183 MiB allocated, 13.24 ms/iter
    after:  32052 MiB allocated, 12.75 ms/iter

Peak allocated memory is unchanged at 736.7 MiB either way; the cost was
allocator traffic and step time, not peak capacity.

Authored with assistance from Claude Code (Anthropic).

ghstack-source-id: 5b41084
Pull-Request: #194434
@weifengpy weifengpy changed the title [FSDP2] Fix grad_dtype accumulation precision, None handling, and copy-in cost [FSDP2] Fix grad_dtype propagation through fully_shard Aug 23, 2026
weifengpy added a commit that referenced this pull request Aug 23, 2026
Supersedes and includes #172074 by @arkadip-maitra, which propagates
Tensor.grad_dtype through fully_shard, plus four corrections found while
reviewing it. #172074 is the original change and remains open; this PR carries
its commit verbatim as the first half of the diff so the whole feature can be
reviewed and landed as one unit. If #172074 lands first, only the corrections
below are needed and this PR should be rebased down to them.

Four issues, found while reviewing #172074 and each reproduced on 2xH100.

Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one
that matters. to_accumulated_grad_if_needed casts the unsharded gradient to
reduce_dtype before summing microbatches. That was written as an upcast (bf16
compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype
wider than reduce_dtype it becomes a downcast: with bf16 parameters,
grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch
sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype
was fp32 as requested while the precision grad_dtype exists to provide was
gone, so nothing surfaced the loss. An explicit grad_dtype now takes
precedence; for that config the gradients simply stay on
_unsharded_param.grad, which is the path already taken when reduce_dtype is
unset.

grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype,
None meaning any gradient dtype is allowed, or never assigned, in which case
the getter mirrors param.dtype. In foreach_reduce a None read back off the
parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op
and leaves the gradient in reduce_dtype. With fp32 parameters and
reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been
fp32, with no error, because grad_dtype=None also disables the dtype check on
gradient assignment. Fixed by reading the construction-time snapshot rather
than the live parameter, since the snapshot is what was propagated onto the
parameter autograd produced these gradients for. An explicit None is treated
as unset: the only thing that relaxation buys is skipping the dtype check when
someone assigns param.grad, and FSDP always assigns a gradient it just cast to
orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype
gradient afterwards now gets a clear error from the setter instead of silent
divergence.

The reduce-scatter copy-in staging buffer is not needed. It was added on the
premise that _chunk_cat rejects narrowing casts. It does not:
torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is
canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real,
float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard
also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16)
recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a
full-size gradient copy to every reduce-scatter. Separately,
torch.promote_types raises on float8 rather than returning a result, so for
float8 gradients the guard itself would have thrown.

reset_sharded_param re-stamped unconditionally. grad_dtype lives on the
parameter's autograd metadata and survives an in-place .data swap, so the
re-stamp is only required when _apply or load_state_dict(assign=True) installs
a replacement Parameter object. Re-stamping unconditionally could also raise
from the grad_dtype setter when a gradient of a different dtype was already
present, in a function that previously never raised there. Moved inside the
object-replacement branch.

Review the _fsdp_param.py state change first (the two snapshot fields), then
its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the
accumulation fix, then the tests.

Test Plan:

Full mixed-precision suite on 2 GPUs:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 19 passed in 116.67s
```

FSDP gradient accumulation, the path the accumulation fix touches:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation
# 1 passed, 38 deselected in 45.66s
```

Confirming the new coverage fails without the fix, by reverting only the
torch/ changes:

```
git stash push -- torch/
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q
git stash pop
# 3 failed, 3 passed:
#   FAILED test_grad_dtype_none_keeps_orig_dtype
#   FAILED test_grad_dtype_numerics_grad_acc
#   FAILED test_grad_dtype_preserved_grad_acc
```

test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before
and after fully_shard; only the after case reproduces the stale live read, so
both are exercised. test_grad_dtype_preserved_across_apply passes either way;
it is added as coverage for the reset_sharded_param path, not as a regression
test.

Accumulation precision, measured against a reference that mirrors FSDP's
reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce,
cast back) so the residual error is attributable to the accumulation dtype
alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches,
2 ranks:

    before: max relative error 5.747e-03
    after:  max relative error 0.000e+00

Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no
grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations,
2 ranks:

    before: 37183 MiB allocated, 13.24 ms/iter
    after:  32052 MiB allocated, 12.75 ms/iter

Peak allocated memory is unchanged at 736.7 MiB either way; the cost was
allocator traffic and step time, not peak capacity.

Authored with assistance from Claude Code (Anthropic).

Co-authored-by: Arkadip Maitra <[email protected]>

ghstack-source-id: f04402d
Pull-Request: #194434
weifengpy added a commit that referenced this pull request Aug 23, 2026
Supersedes and includes #172074 by @arkadip-maitra, which propagates
Tensor.grad_dtype through fully_shard, plus four corrections found while
reviewing it. #172074 is the original change and remains open; this PR carries
its commit verbatim as the first half of the diff so the whole feature can be
reviewed and landed as one unit. If #172074 lands first, only the corrections
below are needed and this PR should be rebased down to them.

Four issues, found while reviewing #172074 and each reproduced on 2xH100.

Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one
that matters. to_accumulated_grad_if_needed casts the unsharded gradient to
reduce_dtype before summing microbatches. That was written as an upcast (bf16
compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype
wider than reduce_dtype it becomes a downcast: with bf16 parameters,
grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch
sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype
was fp32 as requested while the precision grad_dtype exists to provide was
gone, so nothing surfaced the loss. An explicit grad_dtype now takes
precedence; for that config the gradients simply stay on
_unsharded_param.grad, which is the path already taken when reduce_dtype is
unset.

grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype,
None meaning any gradient dtype is allowed, or never assigned, in which case
the getter mirrors param.dtype. In foreach_reduce a None read back off the
parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op
and leaves the gradient in reduce_dtype. With fp32 parameters and
reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been
fp32, with no error, because grad_dtype=None also disables the dtype check on
gradient assignment. Fixed by reading the construction-time snapshot rather
than the live parameter, since the snapshot is what was propagated onto the
parameter autograd produced these gradients for. An explicit None is treated
as unset: the only thing that relaxation buys is skipping the dtype check when
someone assigns param.grad, and FSDP always assigns a gradient it just cast to
orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype
gradient afterwards now gets a clear error from the setter instead of silent
divergence.

The reduce-scatter copy-in staging buffer is not needed. It was added on the
premise that _chunk_cat rejects narrowing casts. It does not:
torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is
canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real,
float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard
also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16)
recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a
full-size gradient copy to every reduce-scatter. Separately,
torch.promote_types raises on float8 rather than returning a result, so for
float8 gradients the guard itself would have thrown.

reset_sharded_param re-stamped unconditionally. grad_dtype lives on the
parameter's autograd metadata and survives an in-place .data swap, so the
re-stamp is only required when _apply or load_state_dict(assign=True) installs
a replacement Parameter object. Re-stamping unconditionally could also raise
from the grad_dtype setter when a gradient of a different dtype was already
present, in a function that previously never raised there. Moved inside the
object-replacement branch.

Review the _fsdp_param.py state change first (the two snapshot fields), then
its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the
accumulation fix, then the tests.

Test Plan:

Full mixed-precision suite on 2 GPUs:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 19 passed in 116.67s
```

FSDP gradient accumulation, the path the accumulation fix touches:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation
# 1 passed, 38 deselected in 45.66s
```

Confirming the new coverage fails without the fix, by reverting only the
torch/ changes:

```
git stash push -- torch/
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q
git stash pop
# 3 failed, 3 passed:
#   FAILED test_grad_dtype_none_keeps_orig_dtype
#   FAILED test_grad_dtype_numerics_grad_acc
#   FAILED test_grad_dtype_preserved_grad_acc
```

test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before
and after fully_shard; only the after case reproduces the stale live read, so
both are exercised. test_grad_dtype_preserved_across_apply passes either way;
it is added as coverage for the reset_sharded_param path, not as a regression
test.

Accumulation precision, measured against a reference that mirrors FSDP's
reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce,
cast back) so the residual error is attributable to the accumulation dtype
alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches,
2 ranks:

    before: max relative error 5.747e-03
    after:  max relative error 0.000e+00

Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no
grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations,
2 ranks:

    before: 37183 MiB allocated, 13.24 ms/iter
    after:  32052 MiB allocated, 12.75 ms/iter

Peak allocated memory is unchanged at 736.7 MiB either way; the cost was
allocator traffic and step time, not peak capacity.

Authored with assistance from Claude Code (Anthropic).

Co-authored-by: Arkadip Maitra <[email protected]>

ghstack-source-id: f04402d
Pull-Request: #194434
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from 2cc5d46 to b1060f9 Compare August 23, 2026 18:51
weifengpy added a commit that referenced this pull request Aug 23, 2026
Supersedes and includes #172074 by @arkadip-maitra, which propagates
Tensor.grad_dtype through fully_shard, plus four corrections found while
reviewing it. #172074 is the original change and remains open; this PR carries
its commit verbatim as the first half of the diff so the whole feature can be
reviewed and landed as one unit. If #172074 lands first, only the corrections
below are needed and this PR should be rebased down to them.

Four issues, found while reviewing #172074 and each reproduced on 2xH100.

Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one
that matters. to_accumulated_grad_if_needed casts the unsharded gradient to
reduce_dtype before summing microbatches. That was written as an upcast (bf16
compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype
wider than reduce_dtype it becomes a downcast: with bf16 parameters,
grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch
sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype
was fp32 as requested while the precision grad_dtype exists to provide was
gone, so nothing surfaced the loss. An explicit grad_dtype now takes
precedence; for that config the gradients simply stay on
_unsharded_param.grad, which is the path already taken when reduce_dtype is
unset.

grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype,
None meaning any gradient dtype is allowed, or never assigned, in which case
the getter mirrors param.dtype. In foreach_reduce a None read back off the
parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op
and leaves the gradient in reduce_dtype. With fp32 parameters and
reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been
fp32, with no error, because grad_dtype=None also disables the dtype check on
gradient assignment. Fixed by reading the construction-time snapshot rather
than the live parameter, since the snapshot is what was propagated onto the
parameter autograd produced these gradients for. An explicit None is treated
as unset: the only thing that relaxation buys is skipping the dtype check when
someone assigns param.grad, and FSDP always assigns a gradient it just cast to
orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype
gradient afterwards now gets a clear error from the setter instead of silent
divergence.

The reduce-scatter copy-in staging buffer is not needed. It was added on the
premise that _chunk_cat rejects narrowing casts. It does not:
torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is
canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real,
float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard
also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16)
recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a
full-size gradient copy to every reduce-scatter. Separately,
torch.promote_types raises on float8 rather than returning a result, so for
float8 gradients the guard itself would have thrown.

reset_sharded_param re-stamped unconditionally. grad_dtype lives on the
parameter's autograd metadata and survives an in-place .data swap, so the
re-stamp is only required when _apply or load_state_dict(assign=True) installs
a replacement Parameter object. Re-stamping unconditionally could also raise
from the grad_dtype setter when a gradient of a different dtype was already
present, in a function that previously never raised there. Moved inside the
object-replacement branch.

Review the _fsdp_param.py state change first (the two snapshot fields), then
its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the
accumulation fix, then the tests.

Test Plan:

Full mixed-precision suite on 2 GPUs:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 19 passed in 116.67s
```

FSDP gradient accumulation, the path the accumulation fix touches:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation
# 1 passed, 38 deselected in 45.66s
```

Confirming the new coverage fails without the fix, by reverting only the
torch/ changes:

```
git stash push -- torch/
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q
git stash pop
# 3 failed, 3 passed:
#   FAILED test_grad_dtype_none_keeps_orig_dtype
#   FAILED test_grad_dtype_numerics_grad_acc
#   FAILED test_grad_dtype_preserved_grad_acc
```

test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before
and after fully_shard; only the after case reproduces the stale live read, so
both are exercised. test_grad_dtype_preserved_across_apply passes either way;
it is added as coverage for the reset_sharded_param path, not as a regression
test.

Accumulation precision, measured against a reference that mirrors FSDP's
reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce,
cast back) so the residual error is attributable to the accumulation dtype
alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches,
2 ranks:

    before: max relative error 5.747e-03
    after:  max relative error 0.000e+00

Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no
grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations,
2 ranks:

    before: 37183 MiB allocated, 13.24 ms/iter
    after:  32052 MiB allocated, 12.75 ms/iter

Peak allocated memory is unchanged at 736.7 MiB either way; the cost was
allocator traffic and step time, not peak capacity.

Authored with assistance from Claude Code (Anthropic).

ghstack-source-id: f04402d
Pull-Request: #194434
Co-authored-by: Arkadip Maitra <[email protected]>
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from b1060f9 to 6d0ca81 Compare August 23, 2026 18:54
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from 6d0ca81 to 823a593 Compare August 23, 2026 21:46
weifengpy added a commit that referenced this pull request Aug 23, 2026
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the
reduce-scatter still runs every microbatch and the partial sums are held in
partial_reduce_output across backward calls until the deferred all-reduce.
That buffer is allocated at reduce_dtype, so each microbatch's contribution is
rounded into it and the error compounds with the microbatch count, even when
the user asked for a wider grad_dtype.

This is distinct from the accumulation fix in #194434, which covers
set_requires_gradient_sync(False) -- the mode that runs no collectives at all.
The two no-sync modes take different paths and only the first was addressed.

An explicit grad_dtype now widens the partial buffer so only the final
all-reduce rounds. The buffer is never narrowed below reduce_dtype, which
would make accumulation worse than ignoring grad_dtype entirely; the guard
compares itemsize rather than calling torch.promote_types, which raises for
float8. When grad_dtype is unset or is not wider than reduce_dtype this is a
no-op, so nobody who did not ask for the precision pays the extra memory --
the buffer is sharded-gradient sized and held for the whole accumulation
window, so widening it is not free.

The all-reduce still runs at reduce_dtype, so one rounding remains by design;
widening it would contradict an explicit reduce_dtype.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 20 passed in 126.12s
```

The new test fails without the torch/ change (`git stash push -- torch/`):

```
AssertionError: Set comparison failed: Items in the first set but not the second
1 failed, 19 deselected
```

Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16,
against a reference that mirrors the reduce pipeline but accumulates in fp32:

    microbatches    before        after
     8              7.143e-03     5.814e-03
    32              1.143e-02     5.714e-03

The point is not the ratio but the shape: after the change the error no longer
grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch
reduce-scatter rounding, which is inherent to reduce_dtype=bf16.

Authored with assistance from Claude Code (Anthropic).
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from 823a593 to 41ddee0 Compare August 23, 2026 21:47
weifengpy added a commit that referenced this pull request Aug 23, 2026
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the
reduce-scatter still runs every microbatch and the partial sums are held in
partial_reduce_output across backward calls until the deferred all-reduce.
That buffer is allocated at reduce_dtype, so each microbatch's contribution is
rounded into it and the error compounds with the microbatch count, even when
the user asked for a wider grad_dtype.

This is distinct from the accumulation fix in #194434, which covers
set_requires_gradient_sync(False) -- the mode that runs no collectives at all.
The two no-sync modes take different paths and only the first was addressed.

An explicit grad_dtype now widens the partial buffer so only the final
all-reduce rounds. The buffer is never narrowed below reduce_dtype, which
would make accumulation worse than ignoring grad_dtype entirely; the guard
compares itemsize rather than calling torch.promote_types, which raises for
float8. When grad_dtype is unset or is not wider than reduce_dtype this is a
no-op, so nobody who did not ask for the precision pays the extra memory --
the buffer is sharded-gradient sized and held for the whole accumulation
window, so widening it is not free.

The all-reduce still runs at reduce_dtype, so one rounding remains by design;
widening it would contradict an explicit reduce_dtype.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 20 passed in 126.12s
```

The new test fails without the torch/ change (`git stash push -- torch/`):

```
AssertionError: Set comparison failed: Items in the first set but not the second
1 failed, 19 deselected
```

Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16,
against a reference that mirrors the reduce pipeline but accumulates in fp32:

    microbatches    before        after
     8              7.143e-03     5.814e-03
    32              1.143e-02     5.714e-03

The point is not the ratio but the shape: after the change the error no longer
grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch
reduce-scatter rounding, which is inherent to reduce_dtype=bf16.

Authored with assistance from Claude Code (Anthropic).
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from 41ddee0 to a214515 Compare August 23, 2026 22:32
weifengpy added a commit that referenced this pull request Aug 23, 2026
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the
reduce-scatter still runs every microbatch and the partial sums are held in
partial_reduce_output across backward calls until the deferred all-reduce.
That buffer is allocated at reduce_dtype, so each microbatch's contribution is
rounded into it and the error compounds with the microbatch count, even when
the user asked for a wider grad_dtype.

This is distinct from the accumulation fix in #194434, which covers
set_requires_gradient_sync(False) -- the mode that runs no collectives at all.
The two no-sync modes take different paths and only the first was addressed.

An explicit grad_dtype now widens the partial buffer so only the final
all-reduce rounds. The buffer is never narrowed below reduce_dtype, which
would make accumulation worse than ignoring grad_dtype entirely; the guard
compares itemsize rather than calling torch.promote_types, which raises for
float8. When grad_dtype is unset or is not wider than reduce_dtype this is a
no-op, so nobody who did not ask for the precision pays the extra memory --
the buffer is sharded-gradient sized and held for the whole accumulation
window, so widening it is not free.

The all-reduce still runs at reduce_dtype, so one rounding remains by design;
widening it would contradict an explicit reduce_dtype.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 20 passed in 126.12s
```

The new test fails without the torch/ change (`git stash push -- torch/`):

```
AssertionError: Set comparison failed: Items in the first set but not the second
1 failed, 19 deselected
```

Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16,
against a reference that mirrors the reduce pipeline but accumulates in fp32:

    microbatches    before        after
     8              7.143e-03     5.814e-03
    32              1.143e-02     5.714e-03

The point is not the ratio but the shape: after the change the error no longer
grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch
reduce-scatter rounding, which is inherent to reduce_dtype=bf16.

Authored with assistance from Claude Code (Anthropic).
weifengpy added a commit that referenced this pull request Aug 24, 2026
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the
reduce-scatter still runs every microbatch and the partial sums are held in
partial_reduce_output across backward calls until the deferred all-reduce.
That buffer is allocated at reduce_dtype, so each microbatch's contribution is
rounded into it and the error compounds with the microbatch count, even when
the user asked for a wider grad_dtype.

This is distinct from the accumulation fix in #194434, which covers
set_requires_gradient_sync(False) -- the mode that runs no collectives at all.
The two no-sync modes take different paths and only the first was addressed.

An explicit grad_dtype now widens the partial buffer so only the final
all-reduce rounds. It reuses FSDPParam._accumulate_grad_dtype, the same rule the
no-collectives no-sync path uses, so the two accumulators cannot drift apart:
the buffer is never narrowed below reduce_dtype, which would make accumulation
worse than ignoring grad_dtype entirely. When grad_dtype is unset or is not wider than reduce_dtype this is a
no-op, so nobody who did not ask for the precision pays the extra memory --
the buffer is sharded-gradient sized and held for the whole accumulation
window, so widening it is not free.

The all-reduce still runs at reduce_dtype, so one rounding remains by design;
widening it would contradict an explicit reduce_dtype.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
# 20 passed in 126.12s
```

The new test fails without the torch/ change (`git stash push -- torch/`):

```
AssertionError: Set comparison failed: Items in the first set but not the second
1 failed, 19 deselected
```

Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16,
against a reference that mirrors the reduce pipeline but accumulates in fp32:

    microbatches    before        after
     8              7.143e-03     5.814e-03
    32              1.143e-02     5.714e-03

The point is not the ratio but the shape: after the change the error no longer
grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch
reduce-scatter rounding, which is inherent to reduce_dtype=bf16.

Authored with assistance from Claude Code (Anthropic).
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from a214515 to 80bbeeb Compare August 24, 2026 06:27
weifengpy added a commit that referenced this pull request Aug 24, 2026
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the
reduce-scatter still runs every microbatch and the partial sums are held in
partial_reduce_output across backward calls until the deferred all-reduce.
That buffer is allocated at reduce_dtype, so each microbatch's contribution is
rounded into it and the error compounds with the microbatch count, even when
the user asked for a wider grad_dtype.

This is distinct from the accumulation fix in #194434, which covers
set_requires_gradient_sync(False) -- the mode that runs no collectives at all.
The two no-sync modes take different paths and only the first was addressed.

An explicit grad_dtype now widens the partial buffer so only the final
all-reduce rounds. It reuses FSDPParam._accumulate_grad_dtype, the same rule the
no-collectives no-sync path uses, so the two accumulators cannot drift apart:
the buffer is never narrowed below reduce_dtype, which would make accumulation
worse than ignoring grad_dtype entirely. When grad_dtype is unset or is not wider than reduce_dtype this is a
no-op, so nobody who did not ask for the precision pays the extra memory --
the buffer is sharded-gradient sized and held for the whole accumulation
window, so widening it is not free.

The all-reduce still runs at reduce_dtype, so one rounding remains by design;
widening it would contradict an explicit reduce_dtype.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
```

The new test fails without the torch/ change (`git stash push -- torch/`):

```
AssertionError: Set comparison failed: Items in the first set but not the second
1 failed, 19 deselected
```

Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16,
against a reference that mirrors the reduce pipeline but accumulates in fp32:

    microbatches    before        after
     8              7.143e-03     5.814e-03
    32              1.143e-02     5.714e-03

The point is not the ratio but the shape: after the change the error no longer
grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch
reduce-scatter rounding, which is inherent to reduce_dtype=bf16.

Authored with assistance from Claude Code (Anthropic).
weifengpy added a commit that referenced this pull request Aug 24, 2026
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the
reduce-scatter still runs every microbatch and the partial sums are held in
partial_reduce_output across backward calls until the deferred all-reduce.
That buffer is allocated at reduce_dtype, so each microbatch's contribution is
rounded into it and the error compounds with the microbatch count, even when
the user asked for a wider grad_dtype.

This is distinct from the accumulation fix in #194434, which covers
set_requires_gradient_sync(False) -- the mode that runs no collectives at all.
The two no-sync modes take different paths and only the first was addressed.

An explicit grad_dtype now widens the partial buffer so only the final
all-reduce rounds. It reuses FSDPParam._accumulate_grad_dtype, the same rule the
no-collectives no-sync path uses, so the two accumulators cannot drift apart:
the buffer is never narrowed below reduce_dtype, which would make accumulation
worse than ignoring grad_dtype entirely. When grad_dtype is unset or is not wider than reduce_dtype this is a
no-op, so nobody who did not ask for the precision pays the extra memory --
the buffer is sharded-gradient sized and held for the whole accumulation
window, so widening it is not free.

The all-reduce still runs at reduce_dtype, so one rounding remains by design;
widening it would contradict an explicit reduce_dtype.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
```

The new test fails without the torch/ change (`git stash push -- torch/`):

```
AssertionError: Set comparison failed: Items in the first set but not the second
1 failed, 19 deselected
```

Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16,
against a reference that mirrors the reduce pipeline but accumulates in fp32:

    microbatches    before        after
     8              7.143e-03     5.814e-03
    32              1.143e-02     5.714e-03

The point is not the ratio but the shape: after the change the error no longer
grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch
reduce-scatter rounding, which is inherent to reduce_dtype=bf16.

Authored with assistance from Claude Code (Anthropic).
Pull-Request: #194546
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from 80bbeeb to e6a9054 Compare August 24, 2026 06:40
weifengpy added a commit that referenced this pull request Aug 24, 2026
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the
reduce-scatter still runs every microbatch and the partial sums are held in
partial_reduce_output across backward calls until the deferred all-reduce.
That buffer is allocated at reduce_dtype, so each microbatch's contribution is
rounded into it and the error compounds with the microbatch count, even when
the user asked for a wider grad_dtype.

This is distinct from the accumulation fix in #194434, which covers
set_requires_gradient_sync(False) -- the mode that runs no collectives at all.
The two no-sync modes take different paths and only the first was addressed.

An explicit grad_dtype now widens the partial buffer so only the final
all-reduce rounds. It reuses FSDPParam._accumulate_grad_dtype, the same rule the
no-collectives no-sync path uses, so the two accumulators cannot drift apart:
the buffer is never narrowed below reduce_dtype, which would make accumulation
worse than ignoring grad_dtype entirely. When grad_dtype is unset or is not wider than reduce_dtype this is a
no-op, so nobody who did not ask for the precision pays the extra memory --
the buffer is sharded-gradient sized and held for the whole accumulation
window, so widening it is not free.

The all-reduce still runs at reduce_dtype, so one rounding remains by design;
widening it would contradict an explicit reduce_dtype.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q
```

The new test fails without the torch/ change (`git stash push -- torch/`):

```
AssertionError: Set comparison failed: Items in the first set but not the second
1 failed, 19 deselected
```

Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16,
against a reference that mirrors the reduce pipeline but accumulates in fp32:

    microbatches    before        after
     8              7.143e-03     5.814e-03
    32              1.143e-02     5.714e-03

The point is not the ratio but the shape: after the change the error no longer
grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch
reduce-scatter rounding, which is inherent to reduce_dtype=bf16.

Authored with assistance from Claude Code (Anthropic).
Pull-Request: #194546
@weifengpy
weifengpy force-pushed the gh/weifengpy/174/head branch from e6a9054 to 338a55b Compare August 24, 2026 18:05
@weifengpy weifengpy changed the title [FSDP2] Fix grad_dtype propagation through fully_shard [FSDP2] Preserve Tensor.grad_dtype through fully_shard Aug 24, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 29, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/rocm.
Currently recognized labels are

  • ciflow/b200
  • ciflow/b200-distributed
  • ciflow/b200-symm-mem
  • ciflow/binaries
  • ciflow/binaries_libtorch
  • ciflow/binaries_wheel
  • ciflow/docker
  • ciflow/dtensor
  • ciflow/h100
  • ciflow/h100-cutlass-backend
  • ciflow/h100-distributed
  • ciflow/h100-symm-mem
  • ciflow/inductor
  • ciflow/inductor-cu126
  • ciflow/inductor-micro-benchmark
  • ciflow/inductor-micro-benchmark-cpu-x86
  • ciflow/inductor-pallas
  • ciflow/inductor-perf-compare
  • ciflow/inductor-perf-test-nightly-rocm-mi300
  • ciflow/inductor-perf-test-nightly-rocm-mi350
  • ciflow/inductor-perf-test-nightly-x86-zen
  • ciflow/inductor-perf-test-nightly-xpu
  • ciflow/inductor-periodic
  • ciflow/inductor-rocm-mi200
  • ciflow/inductor-rocm-mi300
  • ciflow/mps
  • ciflow/native-aot
  • ciflow/nightly
  • ciflow/op-benchmark
  • ciflow/periodic
  • ciflow/periodic-rocm-mi200
  • ciflow/periodic-rocm-mi300
  • ciflow/periodic-strict
  • ciflow/pull
  • ciflow/riscv64
  • ciflow/rocm-mi200
  • ciflow/rocm-mi300
  • ciflow/rocm-nightly
  • ciflow/rocm-preview
  • ciflow/rocm-rx7900
  • ciflow/s390
  • ciflow/slow
  • ciflow/slow-rocm-mi200
  • ciflow/torchtitan
  • ciflow/triton_binaries
  • ciflow/trunk
  • ciflow/tsan
  • ciflow/unstable
  • ciflow/win-arm64
  • ciflow/xpu

Please add the new label to .github/pytorch-probot.yml

[ghstack-poisoned]
@weifengpy

Copy link
Copy Markdown
Contributor Author

Reviewed this with AI assistance while reading through the grad_dtype plumbing. Disclosure: everything inside the quote block is AI-generated.

what's fixed in this PR

  • fix unit tests test_replicate_mixed_precision.py::test_compute_dtype
  • docstring for reduce_dtype

I took the risk of nccl hang because i don't want to hard error on existing callsites of .grad_dtype = None

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #198668

[ghstack-poisoned]
@weifengpy

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge

@weifengpy

Copy link
Copy Markdown
Contributor Author

fixed rocm unit test error and landing again

@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #198668

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/dtensor Run DTensor specific tests ciflow/h100-symm-mem ciflow/inductor ciflow/rocm ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (dtensor) release notes category release notes: distributed (fsdp2) release notes category topic: bc breaking topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants