Repository navigation
Fixes grad_dtype property being lost in fsdp - #172074
arkadip-maitra wants to merge 2 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/172074
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (1 Unrelated Failure)As of commit 3cd145c with merge base a7ff569 ( BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
| for param in model.parameters(): | ||
| self.assertIsNotNone(param.grad) | ||
| self.assertEqual(param.grad.dtype, desired_grad_dtype) | ||
|
|
There was a problem hiding this comment.
- The parameters before sharding have grad_dtype set,
fully_shard()shall preserve the property on sharded params. - In fsdp-allgather, the all-gathered full param shall preserve grad_dtype property.
I think both are expected behavior. (1) is covered by the test, but could you also check (2) ? This would be an assertion in the layer's forward() to check that the full param is (i) no longer a DTensor and (i) has the correct grad_dtype.
There was a problem hiding this comment.
Thanks for the suggestion! I looked into this.
The issue is that grad_dtype causes autograd to compute gradients in that dtype. This makes reduce-scatter operate in grad_dtype (float32) instead of param_dtype (bfloat16), which breaks test_compute_dtype and test_clamp_reduce_dtype.
Modified the test slightly, so that it verifies grad_dtype is preserved on sharded params after fully_shard() and gradients have correct grad_dtype after backward.
There was a problem hiding this comment.
we expect same autograd behavior aross single-device and FSDP multi-device
from claude on what's different right now, this is related to @ppwwyyxx 's point on "the all-gathered full param shall preserve grad_dtype property"
Single-device grad_dtype semantics:
At engine.cpp:951-953, the cast happens in validate_outputs on the edge leading to AccumulateGrad. This runs
after backward computation, before gradient storage:
backward ops (dtype determined by ops, NOT grad_dtype)
→ validate_outputs: cast to grad_dtype ← HERE
→ AccumulateGrad: store/accumulate .grad
grad_dtype does not affect backward compute dtype. It only affects the final .grad dtype. The author's claim
that "grad_dtype causes autograd to compute gradients in that dtype" is incorrect.
Now, does FSDP preserve this?
The final .grad dtype — yes. The foreach_reduce cast at line 698 ensures sharded_param.grad.dtype ==
grad_dtype.
But there's a subtle difference in the gradient accumulation path. Consider: float32 param,
grad_dtype=bfloat16, no mixed precision, 3 microbatches:
Single-device:
1. Backward → float32 grad → AccumulateGrad casts to bfloat16 → stores .grad
2. Backward → float32 grad → cast to bfloat16 → += in bfloat16
3. Same. Final .grad is bfloat16, accumulated in bfloat16.
FSDP (HEAD):
1. Backward → float32 grad → AccumulateGrad stores float32 (no cast, _unsharded_param.grad_dtype is default
float32)
2. accumulate_unsharded_grad_if_needed → += in float32
3. Final reduce-scatter → cast to bfloat16 in foreach_reduce.
Same final dtype, but accumulation happened in float32 instead of bfloat16. Numerically different.
The fix ppwwyyxx suggested — setting grad_dtype on _unsharded_param — would make AccumulateGrad cast before
FSDP sees the gradient, matching single-device accumulation semantics. It wouldn't change backward compute
dtype (that's determined by the ops, not grad_dtype). But it would change the dtype of the gradient FSDP feeds
into reduce-scatter, which is why existing tests break — the reduce-scatter dtype logic assumes the gradient
is in param_dtype, not grad_dtype.
There was a problem hiding this comment.
Hey wei, thanks for the comment. Updated the code.
Propagated grad_dtype to _unsharded_param, so AccumulateGrad casts gradients before FSDP sees them.
Also casted grad_dtype to reduce_dtype before copy_in and reduce_dtype to grad_dtype on the sharded output.
Also added test to verify numerical parity with single device behavior.
|
Is it feasible to implement inheritance of grad_dtype in _setattr_on_modules? |
The current approach of saving |
|
@weifengpy can you take a look at this pls |
| param_grad_dtype is not None | ||
| and new_sharded_grad.dtype != param_grad_dtype | ||
| ): | ||
| new_sharded_grad = new_sharded_grad.to(param_grad_dtype) |
There was a problem hiding this comment.
maybe do the casting before line 617? it makes sure accurate grad dtype before offload_to_cpu
| self.sharded_param = nn.Parameter( | ||
| self.to_sharded_dtensor(sharded_param), requires_grad=param.requires_grad | ||
| ) | ||
| if should_restore_grad_dtype and self.sharded_param.requires_grad: |
There was a problem hiding this comment.
maybe this would be more compact? it removes the need for line 266-267
if param.is_leaf and param.requires_grad:
self.sharded_param.grad_dtype = param.grad_dtype
| ref_param_compute.detach().copy_(ref_param) | ||
|
|
||
| @skip_if_lt_x_gpu(2) | ||
| def test_grad_dtype_preserved(self): |
There was a problem hiding this comment.
need to extend the unit tests
- input model: bf16 model with .grad_dtype fp32, fp32 model with .grad_dtype bf16
- fsdp2 config: no mixed preicison with reduce_dtype != .grad_dtype, enable mixed precision with reduce_dtype != .grad_dtype
- cover hsdp2, where reduce-scatter and all-reduce both happens
- cover gradient accumulation
|
@pytorchbot rebase |
|
@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here |
|
Successfully rebased |
e4645c7 to
92605ec
Compare
|
@pytorchbot rebase |
|
@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here |
|
Rebase failed due to Command |
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > - Preserve each parameter's pre-FSDP `grad_dtype` for reduced shards; use `reduce_dtype` as autograd's unsharded `grad_dtype`. > - Accumulate without FSDP casts and expose pending `Partial` gradients through `model.parameters().grad`. > - Use one flat output cast for uniform shard dtypes, or foreach for mixed dtypes. > - Clear reduced gradients to `None` before FP16 no-sync accumulation or incompatible non-DP `spmd_types` transitions. > > Test Plan > > Mixed precision (24 cases across the full suite and targeted reruns), FSDP/HSDP accumulation with CPU offload, DTensor/unused parameters, collective packing, and CPU SPMD checks passed. The threaded test fixture emits `pg_flight_recorder_hooks` teardown errors despite reporting passing results. > > ```bash > CUDA_VISIBLE_DEVICES=4,5,6,7 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardShareCommContext -v > python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py -v > ``` > > H100 microbenchmarks: autograd casting remains per parameter (6.21 ms backward/packing versus 4.71 ms with fused cast/packing); mixed output casts use 2 foreach kernels instead of 42 individual casts. These are isolated timings, not end-to-end training results. Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 9ae2147
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > - Preserve each parameter's pre-FSDP `grad_dtype` for reduced shards; use `reduce_dtype` as autograd's unsharded `grad_dtype`. > - Accumulate without FSDP casts and expose pending `Partial` gradients through `model.parameters().grad`. > - Use one flat output cast for uniform shard dtypes, or foreach for mixed dtypes. > - Clear reduced gradients to `None` before FP16 no-sync accumulation or incompatible non-DP `spmd_types` transitions. > > Test Plan > > Mixed precision (24 cases across the full suite and targeted reruns), FSDP/HSDP accumulation with CPU offload, DTensor/unused parameters, collective packing, and CPU SPMD checks passed. The threaded test fixture emits `pg_flight_recorder_hooks` teardown errors despite reporting passing results. > > ```bash > CUDA_VISIBLE_DEVICES=4,5,6,7 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardShareCommContext -v > python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py -v > ``` > > H100 microbenchmarks: autograd casting remains per parameter (6.21 ms backward/packing versus 4.71 ms with fused cast/packing); mixed output casts use 2 foreach kernels instead of 42 individual casts. These are isolated timings, not end-to-end training results. Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 313cd80
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > - Preserve each parameter's pre-FSDP `grad_dtype` for reduced shards; use `reduce_dtype` as autograd's unsharded `grad_dtype`. > - Accumulate without FSDP casts and expose pending `Partial` gradients through `model.parameters().grad`. > - Use one flat output cast for uniform shard dtypes, or foreach for mixed dtypes. > - Clear reduced gradients to `None` before FP16 no-sync accumulation or incompatible non-DP `spmd_types` transitions. > > Test Plan > > Mixed precision (24 cases across the full suite and targeted reruns), FSDP/HSDP accumulation with CPU offload, DTensor/unused parameters, collective packing, and CPU SPMD checks passed. The threaded test fixture emits `pg_flight_recorder_hooks` teardown errors despite reporting passing results. > > ```bash > CUDA_VISIBLE_DEVICES=4,5,6,7 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardShareCommContext -v > python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py -v > ``` > > H100 microbenchmarks: autograd casting remains per parameter (6.21 ms backward/packing versus 4.71 ms with fused cast/packing); mixed output casts use 2 foreach kernels instead of 42 individual casts. These are isolated timings, not end-to-end training results. Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: d2b9867
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > - Preserve each parameter's pre-FSDP `grad_dtype` for reduced shards; use `reduce_dtype` as autograd's unsharded `grad_dtype`. > - Accumulate without FSDP casts and expose pending `Partial` gradients through `model.parameters().grad`. > - Use one flat output cast for uniform shard dtypes, or foreach for mixed dtypes. > - Clear reduced gradients to `None` before FP16 no-sync accumulation or incompatible non-DP `spmd_types` transitions. > > Test Plan > > Mixed precision (24 cases across the full suite and targeted reruns), FSDP/HSDP accumulation with CPU offload, DTensor/unused parameters, collective packing, and CPU SPMD checks passed. The threaded test fixture emits `pg_flight_recorder_hooks` teardown errors despite reporting passing results. > > ```bash > CUDA_VISIBLE_DEVICES=4,5,6,7 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardShareCommContext -v > python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py -v > ``` > > H100 microbenchmarks: autograd casting remains per parameter (6.21 ms backward/packing versus 4.71 ms with fused cast/packing); mixed output casts use 2 foreach kernels instead of 42 individual casts. These are isolated timings, not end-to-end training results. Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 4cfc52d
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > - Preserve each parameter's pre-FSDP `grad_dtype` for reduced shards; use `reduce_dtype` as autograd's unsharded `grad_dtype`. > - Accumulate without FSDP casts and expose pending `Partial` gradients through `model.parameters().grad`. > - Use one flat output cast for uniform shard dtypes, or foreach for mixed dtypes. > - Clear reduced gradients to `None` before FP16 no-sync accumulation or incompatible non-DP `spmd_types` transitions. > > Test Plan > > Mixed precision (24 cases across the full suite and targeted reruns), FSDP/HSDP accumulation with CPU offload, DTensor/unused parameters, collective packing, and CPU SPMD checks passed. The threaded test fixture emits `pg_flight_recorder_hooks` teardown errors despite reporting passing results. > > ```bash > CUDA_VISIBLE_DEVICES=4,5,6,7 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardShareCommContext -v > python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py -v > ``` > > H100 microbenchmarks: autograd casting remains per parameter (6.21 ms backward/packing versus 4.71 ms with fused cast/packing); mixed output casts use 2 foreach kernels instead of 42 individual casts. These are isolated timings, not end-to-end training results. Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: dc0cc23
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > - Preserve each parameter's pre-FSDP `grad_dtype` for reduced shards; use `reduce_dtype` as autograd's unsharded `grad_dtype`. > - Accumulate without FSDP casts and expose pending `Partial` gradients through `model.parameters().grad`. > - Use one flat output cast for uniform shard dtypes, or foreach for mixed dtypes. > - Clear reduced gradients to `None` before FP16 no-sync accumulation or incompatible non-DP `spmd_types` transitions. > > Test Plan > > Mixed precision (24 cases across the full suite and targeted reruns), FSDP/HSDP accumulation with CPU offload, DTensor/unused parameters, collective packing, and CPU SPMD checks passed. The threaded test fixture emits `pg_flight_recorder_hooks` teardown errors despite reporting passing results. > > ```bash > CUDA_VISIBLE_DEVICES=4,5,6,7 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardShareCommContext -v > python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py -v > ``` > > H100 microbenchmarks: autograd casting remains per parameter (6.21 ms backward/packing versus 4.71 ms with fused cast/packing); mixed output casts use 2 foreach kernels instead of 42 individual casts. These are isolated timings, not end-to-end training results. Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: dc0cc23
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > - Preserve each parameter's pre-FSDP `grad_dtype` for reduced shards; use `reduce_dtype` as autograd's unsharded `grad_dtype`. > - Accumulate without FSDP casts and expose pending `Partial` gradients through `model.parameters().grad`. > - Use one flat output cast for uniform shard dtypes, or foreach for mixed dtypes. > - Clear reduced gradients to `None` before FP16 no-sync accumulation or incompatible non-DP `spmd_types` transitions. > > Module conversion uses the ordinary gradient-policy setter and requires `zero_grad(set_to_none=True)` when converted gradients would conflict with the policy or replacement parameter dtype, or when pending unreduced gradients would change dtype. FSDP checks the affected subtree before conversion, including grouped/shared parameters. Configure parameter dtypes before the first forward; this does not add general support for changing initialized compute dtypes. The native override getter and its tests live in a separate prerequisite. > > Test Plan > > After removing the native conversion helper, 44 CPU/CUDA conversion cases and six two-GPU mixed-precision regression cases passed. Conversion tests cover unchanged state on rejection and retry after clearing gradients, including already-BF16 weights with FP32 gradients and device-only conversion. > > ```bash > CUDA_VISIBLE_DEVICES=6 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype_after_to -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py TestFullyShardMixedPrecisionTraining.test_reduce_dtype_after_frozen_first_forward_reshard_after_backward_False TestFullyShardMixedPrecisionTraining.test_reduce_dtype_after_frozen_first_forward_reshard_after_backward_True TestFullyShardMixedPrecisionTraining.test_grad_dtype_to_with_existing_grad -v > ``` > > Mixed precision (24 cases across the full suite and targeted reruns), FSDP/HSDP accumulation with CPU offload, DTensor/unused parameters, collective packing, and CPU SPMD checks passed. The threaded test fixture emits `pg_flight_recorder_hooks` teardown errors despite reporting passing results. > > ```bash > CUDA_VISIBLE_DEVICES=4,5,6,7 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardShareCommContext -v > python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py -v > ``` > > H100 microbenchmarks: autograd casting remains per parameter (6.21 ms backward/packing versus 4.71 ms with fused cast/packing); mixed output casts use 2 foreach kernels instead of 42 individual casts. These are isolated timings, not end-to-end training results. Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 36db125
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > - Preserve each parameter's pre-FSDP `grad_dtype` for reduced shards; use `reduce_dtype` as autograd's unsharded `grad_dtype`. > - Accumulate without FSDP casts and expose pending `Partial` gradients through `model.parameters().grad`. > - Use one flat output cast for uniform shard dtypes, or foreach for mixed dtypes. > - Clear reduced gradients to `None` before FP16 no-sync accumulation or incompatible non-DP `spmd_types` transitions. > > Module conversion uses the ordinary gradient-policy setter and requires `zero_grad(set_to_none=True)` when converted gradients would conflict with the policy or replacement parameter dtype, or when pending unreduced gradients would change dtype. FSDP checks the affected subtree before conversion, including grouped/shared parameters. Configure parameter dtypes before the first forward; this does not add general support for changing initialized compute dtypes. The native override getter and its tests live in a separate prerequisite. > > Test Plan > > After removing the native conversion helper, 44 CPU/CUDA conversion cases and six two-GPU mixed-precision regression cases passed. Conversion tests cover unchanged state on rejection and retry after clearing gradients, including already-BF16 weights with FP32 gradients and device-only conversion. > > ```bash > CUDA_VISIBLE_DEVICES=6 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype_after_to -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py TestFullyShardMixedPrecisionTraining.test_reduce_dtype_after_frozen_first_forward_reshard_after_backward_False TestFullyShardMixedPrecisionTraining.test_reduce_dtype_after_frozen_first_forward_reshard_after_backward_True TestFullyShardMixedPrecisionTraining.test_grad_dtype_to_with_existing_grad -v > ``` > > Mixed precision (24 cases across the full suite and targeted reruns), FSDP/HSDP accumulation with CPU offload, DTensor/unused parameters, collective packing, and CPU SPMD checks passed. The threaded test fixture emits `pg_flight_recorder_hooks` teardown errors despite reporting passing results. > > ```bash > CUDA_VISIBLE_DEVICES=4,5,6,7 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardShareCommContext -v > python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py -v > ``` > > H100 microbenchmarks: autograd casting remains per parameter (6.21 ms backward/packing versus 4.71 ms with fused cast/packing); mixed output casts use 2 foreach kernels instead of 42 individual casts. These are isolated timings, not end-to-end training results. Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: b3bab10
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > - Preserve each parameter's pre-FSDP `grad_dtype` for reduced shards; use `reduce_dtype` as autograd's unsharded `grad_dtype`. > - Accumulate without FSDP casts and expose pending `Partial` gradients through `model.parameters().grad`. > - Use one flat output cast for uniform shard dtypes, or foreach for mixed dtypes. > - Clear reduced gradients to `None` before FP16 no-sync accumulation or incompatible non-DP `spmd_types` transitions. > > Module conversion uses the ordinary gradient-policy setter and requires `zero_grad(set_to_none=True)` when converted gradients would conflict with the policy or replacement parameter dtype, or when pending unreduced gradients would change dtype. FSDP checks the affected subtree before conversion, including grouped/shared parameters. Configure parameter dtypes before the first forward; this does not add general support for changing initialized compute dtypes. The native override getter and its tests live in a separate prerequisite. > > Test Plan > > After removing the native conversion helper, 44 CPU/CUDA conversion cases and six two-GPU mixed-precision regression cases passed. Conversion tests cover unchanged state on rejection and retry after clearing gradients, including already-BF16 weights with FP32 gradients and device-only conversion. > > ```bash > CUDA_VISIBLE_DEVICES=6 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype_after_to -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py TestFullyShardMixedPrecisionTraining.test_reduce_dtype_after_frozen_first_forward_reshard_after_backward_False TestFullyShardMixedPrecisionTraining.test_reduce_dtype_after_frozen_first_forward_reshard_after_backward_True TestFullyShardMixedPrecisionTraining.test_grad_dtype_to_with_existing_grad -v > ``` > > Mixed precision (24 cases across the full suite and targeted reruns), FSDP/HSDP accumulation with CPU offload, DTensor/unused parameters, collective packing, and CPU SPMD checks passed. The threaded test fixture emits `pg_flight_recorder_hooks` teardown errors despite reporting passing results. > > ```bash > CUDA_VISIBLE_DEVICES=4,5,6,7 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardShareCommContext -v > python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py -v > ``` > > H100 microbenchmarks: autograd casting remains per parameter (6.21 ms backward/packing versus 4.71 ms with fused cast/packing); mixed output casts use 2 foreach kernels instead of 42 individual casts. These are isolated timings, not end-to-end training results. Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: afe5163
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > - Preserve each parameter's pre-FSDP `grad_dtype` for reduced shards; use `reduce_dtype` as autograd's unsharded `grad_dtype`. > - Accumulate without FSDP casts and expose pending `Partial` gradients through `model.parameters().grad`. > - Use one flat output cast for uniform shard dtypes, or foreach for mixed dtypes. > - Clear reduced gradients to `None` before FP16 no-sync accumulation or incompatible non-DP `spmd_types` transitions. > > Module conversion uses the ordinary gradient-policy setter and requires `zero_grad(set_to_none=True)` when converted gradients would conflict with the policy or replacement parameter dtype, or when pending unreduced gradients would change dtype. FSDP checks the affected subtree before conversion, including grouped/shared parameters. Configure parameter dtypes before the first forward; this does not add general support for changing initialized compute dtypes. The native override getter and its tests live in a separate prerequisite. > > Test Plan > > After removing the native conversion helper, 44 CPU/CUDA conversion cases and six two-GPU mixed-precision regression cases passed. Conversion tests cover unchanged state on rejection and retry after clearing gradients, including already-BF16 weights with FP32 gradients and device-only conversion. > > ```bash > CUDA_VISIBLE_DEVICES=6 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype_after_to -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py TestFullyShardMixedPrecisionTraining.test_reduce_dtype_after_frozen_first_forward_reshard_after_backward_False TestFullyShardMixedPrecisionTraining.test_reduce_dtype_after_frozen_first_forward_reshard_after_backward_True TestFullyShardMixedPrecisionTraining.test_grad_dtype_to_with_existing_grad -v > ``` > > Mixed precision (24 cases across the full suite and targeted reruns), FSDP/HSDP accumulation with CPU offload, DTensor/unused parameters, collective packing, and CPU SPMD checks passed. The threaded test fixture emits `pg_flight_recorder_hooks` teardown errors despite reporting passing results. > > ```bash > CUDA_VISIBLE_DEVICES=4,5,6,7 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardShareCommContext -v > python test/distributed/_composable/fsdp/test_fully_shard_spmd_types.py -v > ``` > > H100 microbenchmarks: autograd casting remains per parameter (6.21 ms backward/packing versus 4.71 ms with fused cast/packing); mixed output casts use 2 foreach kernels instead of 42 individual casts. These are isolated timings, not end-to-end training results. Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: c1e2bbf
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy for reduced shards and configure autograd's unsharded leaf with the effective mixed-precision reduction dtype. Reduction casts its output to each shard's dtype, using a flat cast for uniform dtypes and grouped foreach copies otherwise. Parameter conversion and replacement through load_state_dict preserve the gradient policy. > > Keep reduced history separate from pending accumulation. Embedding an existing FP32 reduced gradient in BF16 pending storage loses information: 256 synchronized, then 1 without synchronization, then -256 synchronized should produce 1. The public FSDPGrad represents reduced shards, unreduced autograd contributions, and HSDP contributions awaiting all-reduce separately. Both accumulated and newly computed unreduced gradients stay in the autograd leaf's configured grad_dtype; they are never promoted into a new accumulation or communication buffer. > > Start review with the dtype initialization and reduction output casts, then the FSDPGrad component representation, then publication/restoration and explicit synchronization. Reads reduce copies into an independent snapshot. Snapshot reads and synchronize_gradients() must run on all participating ranks. Zeroing and scalar scaling act on every component in its own dtype. Whole local-view aliases preserve these operations; unsupported writes and storage exports require synchronization first. Optimizer updates also require synchronization when gradients are pending. This adds no global optimizer adapter. > > Changing reduction policy requires synchronization or zero_grad(set_to_none=True). Module conversions reject changes that conflict with existing gradient policies or pending components; clearing gradients permits a compatible retry. Custom communication callbacks execute during synchronization; snapshot reads reject callbacks they cannot safely replay. CPU offload, saved aliases, partial grouped forwards, and replicated gradient replacement preserve component ownership. > > Test Plan > > Rebuilt the editable CUDA/NVSHMEM installation after rebasing onto main: > > ```bash > MAX_JOBS=60 HAS_TORCH_SHOW_DISPATCH_TRACE=1 TORCH_CUDA_ARCH_LIST=9.0 USE_CUDA=1 USE_DISTRIBUTED=1 USE_NVSHMEM=1 NVSHMEM_HOME=/home/weif/.conda/envs/code-review/lib/python3.12/site-packages/nvidia/nvshmem USE_CUDNN=0 /home/weif/.conda/envs/code-review/bin/python -m pip install -e . -v --no-build-isolation > ``` > > Before rebasing, validation covered the 256/1/-256 regression and native BF16 accumulation rounding, FSDP/HSDP accumulation with CPU offload, component mutations and aliases, gradient-dtype and conversion tests, pending-gradient consumers, and SPMD cases. Focused reruns passed after the replacement, noncontiguous-layout, grouped-forward, stream-lifetime, and pinned-offload fixes. > > After rebuilding, reran the full accumulation matrix, nine component-wrapper cases, FP32/FP16 collective packing, the four native-dtype accumulation cases, custom packing callback handling, and load_state_dict with assign=True. These focused post-rebase checks and lint passed. > > ```bash > CUDA_VISIBLE_DEVICES=6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_grad.py -v > CUDA_VISIBLE_DEVICES=6 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -v > CUDA_VISIBLE_DEVICES=2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation -v > CUDA_VISIBLE_DEVICES=6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k reduced_and_unreduced_keep_native_dtypes -v > CUDA_VISIBLE_DEVICES=6 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_comm.py TestFullyShardCollectiveOps.test_reduce_scatter_fp32 TestFullyShardCollectiveOps.test_reduce_scatter_fp16 -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 17bf1cf
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy for reduced shards and configure autograd's unsharded leaf with the effective mixed-precision reduction dtype. Reduction casts its output to each shard's dtype, using a flat cast for uniform dtypes and grouped foreach copies otherwise. > > Capture the policy at fully_shard(), including explicit None. Default policies continue to follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary instead of being silently overwritten. This avoids a separate mutable policy window between construction and the first forward. The code comment and API documentation state this limit. > > Keep reduced history separate from pending accumulation. Embedding an existing FP32 reduced gradient in BF16 pending storage loses information: 256 synchronized, then 1 without synchronization, then -256 synchronized should produce 1. The public FSDPGrad represents reduced shards, unreduced autograd contributions, and HSDP contributions awaiting all-reduce separately. Both accumulated and newly computed unreduced gradients stay in the autograd leaf's configured grad_dtype; they are never promoted into a new accumulation or communication buffer. > > Start review with the dtype initialization and reduction output casts, then the FSDPGrad component representation, then publication/restoration and explicit synchronization. Reads reduce copies into an independent snapshot. Snapshot reads and synchronize_gradients() must run on all participating ranks. Zeroing and scalar scaling act on every component in its own dtype. Whole local-view aliases preserve these operations; unsupported writes and storage exports require synchronization first. Optimizer updates also require synchronization when gradients are pending. This adds no global optimizer adapter. > > Changing reduction policy requires synchronization or zero_grad(set_to_none=True). Module conversions reject changes that conflict with existing gradient policies or pending components; clearing gradients permits a compatible retry. Custom communication callbacks execute during synchronization; snapshot reads reject callbacks they cannot safely replay. CPU offload, saved aliases, partial grouped forwards, and replicated gradient replacement preserve component ownership. > > Test Plan > > Passed all 46 CPU/CUDA conversion tests, four focused pending-gradient tests, all 19 mixed-precision grad_dtype tests including HSDP, the full gradient accumulation matrix, and lint. Coverage includes rejection before the first forward, after warmup, before backward, during conversion/load, and at unshard/synchronization boundaries; foreign Parameter metadata on assign=True replacement; and preservation of explicit None during an allowed pending-gradient conversion. > > ```bash > CUDA_VISIBLE_DEVICES=6 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k grad_dtype_edit_after_forward_rejected -k none_grad_dtype_preserved_with_pending_conversion -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: e6a4bf1
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy for reduced shards and configure autograd's unsharded leaf with the effective mixed-precision reduction dtype. Reduction casts its output to each shard's dtype, using a flat cast for uniform dtypes and grouped foreach copies otherwise. > > Capture the policy at fully_shard(), including explicit None. Default policies continue to follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary instead of being silently overwritten. This avoids a separate mutable policy window between construction and the first forward. The code comment and API documentation state this limit. > > Keep reduced history separate from pending accumulation. Embedding an existing FP32 reduced gradient in BF16 pending storage loses information: 256 synchronized, then 1 without synchronization, then -256 synchronized should produce 1. The public FSDPGrad represents reduced shards, unreduced autograd contributions, and HSDP contributions awaiting all-reduce separately. Both accumulated and newly computed unreduced gradients stay in the autograd leaf's configured grad_dtype; they are never promoted into a new accumulation or communication buffer. > > Start review with the dtype initialization and reduction output casts, then the FSDPGrad component representation, then publication/restoration and explicit synchronization. Reads reduce copies into an independent snapshot. Snapshot reads and synchronize_gradients() must run on all participating ranks. Zeroing and scalar scaling act on every component in its own dtype. Whole local-view aliases preserve these operations; unsupported writes and storage exports require synchronization first. Optimizer updates also require synchronization when gradients are pending. This adds no global optimizer adapter. > > Pending components own their storage between microbatches; restoration gives autograd the same on-device unreduced allocation for the next accumulation. Publication clears the leaf reference so that a fresh gradient assigned by pipeline backward after an FSDP callback remains distinguishable from cleared or replaced history. Repeated publication reuses the public wrapper when its components, owner, and captured reduction settings match. The pending component supplies its normalization spec directly, without duplicate saved state. > > Changing reduction policy requires synchronization or zero_grad(set_to_none=True). Module conversions reject changes that conflict with existing gradient policies or pending components; clearing gradients permits a compatible retry. Custom communication callbacks execute during synchronization; snapshot reads reject callbacks they cannot safely replay. CPU offload, saved aliases, partial grouped forwards, and replicated gradient replacement preserve component ownership. > > Test Plan > > Validation covers CPU/CUDA conversion, native-dtype cancellation and rounding, the full accumulation matrix, 1F1B, actual split pipeline backward with BF16 and FP32 accumulation, pending-gradient consumers and replacements, CPU offload, HSDP, and SPMD. Ownership regressions check storage reuse across microbatches, repeated publication without double addition, clearing before/after forward without modifying saved aliases, and materialization using the receiving parameter's reduction settings after gradient replacement. Lint also passes. > > ```bash > CUDA_VISIBLE_DEVICES=6 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py TestFullyShardPendingGradCUDA -k native_grad_storage_across_microbatches -k clearing_pending_grad_preserves_saved_aliases -k unsharded_accumulated_grad_dtensor -k pipeline_weight_backward_preserves_native_grad_storage -k republished_grad_uses_current_reduction_policy -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py TestFullyShardPendingGradCUDA -k pending_conversion_is_atomic -v > CUDA_VISIBLE_DEVICES=4,5 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py TestFullyShardPendingGradCUDA -k pipeline_weight_backward_preserves_native_grad_storage -v > CUDA_VISIBLE_DEVICES=6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k reduced_and_unreduced_keep_native_dtypes -k mixed_component_consumers -k cpu_offload_pending_grad -k pending_grad_replacement -k partial_group_clear_after_forward -k pinned_cpu_offload_explicit_sync -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_1f1b_microbatching -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k reduced_partial_and_unreduced_components -k saved_partial_alias_after_replacement -k reduced_to_pending_spmd_grad -k cpu_offload_spmd_pending_grad -k pending_grad_replacement_spmd -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 75c9a1a
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy for reduced shards and configure autograd's unsharded leaf with the effective mixed-precision reduction dtype. Both newly computed and accumulated unsharded gradients use that dtype. Reduction casts its output to each shard's dtype, using a flat cast for uniform dtypes and grouped foreach copies otherwise. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership, then the pending-gradient APIs. get_pending_gradients() returns native unreduced and HSDP partial buffers keyed by their sharded parameters without communication or materializing a combined total. Ordinary in-place tensor operations affect those buffers directly. The .grad visible through model.parameters() belongs to the currently registered parameter; it does not combine all pending and reduced contributions. With CPU offload, pending buffers stay on the compute device and reduced shards are offloaded. > > FSDPModule.zero_grad() clears both parameter owners and HSDP partial buffers. Assignment to an individual .grad or optimizer.zero_grad() affects only those addressed parameters. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Module conversion checks reject actual dtype/device changes while gradients are pending, while no-op conversions preserve native buffers. Changing reduction policy requires synchronization or clearing first. > > Test Plan > > Tests cover CPU/CUDA conversion and captured policies, native-dtype cancellation and rounding, the accumulation matrix, 1F1B and split pipeline backward, ordinary native mutations, clearing hidden buffers, CPU offload, DTensor, HSDP partial-only synchronization and changing parameter subsets, and strict SPMD. Lint passes. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardGradientAccumulation.test_1f1b_microbatching -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: e13a897
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy for reduced shards and configure autograd's unsharded leaf with the effective mixed-precision reduction dtype. Both newly computed and accumulated unsharded gradients use that dtype. Reduction casts its output to each shard's dtype, using a flat cast for uniform dtypes and grouped foreach copies otherwise. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > FSDPModule.zero_grad() clears both parameter owners and HSDP partial buffers. Assignment to an individual .grad or optimizer.zero_grad() affects only those addressed parameters. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Module conversion checks reject actual dtype/device changes while gradients are pending, while no-op conversions preserve native buffers. Changing reduction policy requires synchronization or clearing first. > > Test Plan > > Tests cover CPU/CUDA conversion and captured policies, native-dtype cancellation and rounding, the accumulation matrix, 1F1B and split pipeline backward, gradient visibility across sharding transitions, ordinary native mutations, clearing hidden buffers, CPU offload, DTensor, HSDP partial-only synchronization and changing parameter subsets, and strict SPMD. Lint passes. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardGradientAccumulation.test_1f1b_microbatching -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: c188602
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy for reduced shards and configure autograd's unsharded leaf with the effective mixed-precision reduction dtype. Both newly computed and accumulated unsharded gradients use that dtype. Reduction casts its output to each shard's dtype, using a flat cast for uniform dtypes and grouped foreach copies otherwise. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > Tests cover CPU/CUDA conversion and captured policies, native-dtype cancellation and rounding, the accumulation matrix, 1F1B and split pipeline backward, gradient visibility across sharding transitions, ordinary native mutations, clearing only registered gradients while preserving other owners and HSDP partials, CPU offload, DTensor, HSDP partial-only synchronization and changing parameter subsets, and strict SPMD. Lint passes. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -k reduce_dtype_after_frozen_first_forward -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShardGradientAccumulation.test_gradient_accumulation TestFullyShardGradientAccumulation.test_1f1b_microbatching -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: d06e663
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 78d8496
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: a488e30
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: a488e30
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 1657ae0
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: e432bce
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: b29d984
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 2ead323
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: a7acbc2
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: a6560d1
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 99613b3
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: 2f5782f
Fixes #170648. Based on #172074 by @arkadip-maitra. > Authored with Codex. > > Preserve each parameter's pre-FSDP grad_dtype policy on reduced shards. The unsharded leaf uses an explicit MixedPrecisionPolicy.reduce_dtype, otherwise the parameter's explicit grad_dtype (including None); only parameters without an override use the compute dtype. Defaulting unconditionally to compute dtype discarded explicit gradient precision: BF16 parameters with FP32 grad_dtype accumulated 256 + 1 - 256 as 0 instead of 1. Preserving the gradient policy keeps this accumulation in FP32. > > Reduce gradients in groups with the same actual dtype while retaining the existing all-gather grouping. Retain every HSDP all-reduce buffer until completion, and preserve higher-precision partial gradients if an unrestricted policy produces a different dtype later. Reduction casts outputs to each shard's dtype, using a flat cast for uniform policies and grouped foreach copies otherwise. Including unused parameters in reduction requires an explicit reduce_dtype when grad_dtype is explicitly None, so every rank can construct compatible zero gradients. > > Capture the policy at fully_shard(), including explicit None. Default policies follow parameter dtype changes, while explicit overrides survive conversion and load_state_dict(assign=True) replacement. Direct grad_dtype edits afterward, including before lazy initialization, are intentionally unsupported and raise at the next FSDP boundary. A code comment and API documentation state this limit. > > Keep native gradient owners separate: unreduced accumulation stays on the unsharded parameter's .grad, reduced history stays on the sharded parameter's .grad, and HSDP retains local reduction buffers until all-reduce completes. Combining FP32 reduced history with BF16 pending accumulation would lose information: 256 synchronized, then 1 without synchronization, then -256 synchronized must produce 1. HSDP retains per-parameter views so later microbatches can use different parameter subsets without confusing packed offsets. > > Start review with dtype initialization and reduction output casts, then native accumulation ownership and gradient clearing. In the sharded state, model.parameters() exposes sharded parameters and their reduced .grad. In the unsharded state, it exposes unsharded parameters and their accumulation .grad. HSDP partial reduction buffers remain internal. Integer reshard_after_forward retains its existing temporary parameter layout without gradients. With CPU offload, unreduced gradients stay on the compute device and reduced shards are offloaded. > > Ordinary nn.Module.zero_grad() clears only the currently registered parameters. Clearing sharded gradients preserves hidden unsharded accumulation; clearing unsharded gradients preserves reduced history and internal HSDP partials. Gradient reduction consumes the unsharded .grad and sets it to None, while HSDP retains partial buffers until all-reduce completes. synchronize_gradients() completes pending reductions before global clipping or optimizer updates; callers retaining unsharded parameters also reshard before updating them. Conversion checks preserve native buffers on no-op conversions and explain how to complete reduction, reshard, and clear gradients before incompatible conversions. Pending gradients must be consumed or cleared on their actual owners before changing reduction policy. > > Test Plan > > All 52 focused tests pass: 16 CPU/CUDA accumulation and unrestricted-policy cases, 23 mixed-precision cases, 12 HSDP pending-gradient cases, and one two-rank unused-parameter case. These exercise cancellation, per-parameter gradient dtypes, explicit reduction overrides, changing incoming gradient dtypes, partial-only synchronization, changing parameter subsets, and CPU offload. The new FP32 cancellation regression fails on the previous implementation. Lint and whitespace checks pass. > > ```bash > CUDA_VISIBLE_DEVICES=0 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_conversion.py -k test_grad_dtype_default_reduction -k test_grad_dtype_none -v > CUDA_VISIBLE_DEVICES=0,1,2,3 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -v > CUDA_VISIBLE_DEVICES=4,5,6,7 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_pending_reductions -k test_native_partial_ownership -v > CUDA_VISIBLE_DEVICES=1,2 /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_pending_grad.py -k test_grad_dtype_unused_parameters -v > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a > git diff --check > ``` Co-authored-by: Arkadip Maitra <[email protected]> Pull-Request: #194434 ghstack-source-id: a86d5e1
|
Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as |
Fixes #170648
Problem
When
fully_shard()is applied, it creates newnn.Parameterobjects to hold the sharded data. The original parameter'sgrad_dtypeproperty was not being copied to these new parameters, so any user-setgrad_dtypewas lost.Fix
_fsdp_param.py: Before creating the sharded parameter, save the originalgrad_dtype. After creating it, restore that value._fsdp_collectives.py: Before assigning a gradient to a parameter, cast the gradient to match the parameter's grad_dtype if one is set.