Skip to content

Fixes grad_dtype property being lost in fsdp - #172074

Open
arkadip-maitra wants to merge 2 commits into
pytorch:mainfrom
arkadip-maitra:fix_#170648
Open

arkadip-maitra wants to merge 2 commits into
pytorch:mainfrom
arkadip-maitra:fix_#170648

Conversation

@arkadip-maitra

Copy link
Copy Markdown
Collaborator

Fixes #170648

Problem
When fully_shard() is applied, it creates new nn.Parameter objects to hold the sharded data. The original parameter's grad_dtype property was not being copied to these new parameters, so any user-set grad_dtype was lost.

Fix

  1. _fsdp_param.py: Before creating the sharded parameter, save the original grad_dtype. After creating it, restore that value.
  2. _fsdp_collectives.py: Before assigning a gradient to a parameter, cast the gradient to match the parameter's grad_dtype if one is set.
  3. Added test

@pytorch-bot

pytorch-bot Bot commented Jan 9, 2026 •

Copy link
Copy Markdown

🔗 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 (image):

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.

@pytorch-bot pytorch-bot Bot added the release notes: distributed (fsdp) release notes category label Jan 9, 2026
@arkadip-maitra
arkadip-maitra requested review from cyyever, soulitzer and weifengpy and removed request for weifengpy January 9, 2026 13:19
for param in model.parameters():
self.assertIsNotNone(param.grad)
self.assertEqual(param.grad.dtype, desired_grad_dtype)

@ppwwyyxx ppwwyyxx Jan 10, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. The parameters before sharding have grad_dtype set, fully_shard() shall preserve the property on sharded params.
  2. 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@liqing9399

Copy link
Copy Markdown

Is it feasible to implement inheritance of grad_dtype in _setattr_on_modules?

@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jan 14, 2026
@arkadip-maitra

Copy link
Copy Markdown
Collaborator Author

Is it feasible to implement inheritance of grad_dtype in _setattr_on_modules?

_setattr_on_modules is called with multiple different parameter objects (sharded_param, _sharded_post_forward_param, _unsharded_param) during the lifecycle, and they have different grad_dtype requirements:

sharded_param: should have grad_dtype (user-specified)
_unsharded_param: should NOT have grad_dtype (to preserve reduce-scatter dtype)

_setattr_on_modules just swaps which parameter is registered on the module - it doesn't have context about what the original grad_dtype was.

The current approach of saving grad_dtype in _init_sharded_param is more explicit - it happens exactly once when we create the sharded parameter from the original, and clearly documents the intent.

@arkadip-maitra

Copy link
Copy Markdown
Collaborator Author

@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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe do the casting before line 617? it makes sure accurate grad dtype before offload_to_cpu

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

ref_param_compute.detach().copy_(ref_param)

@skip_if_lt_x_gpu(2)
def test_grad_dtype_preserved(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added

@weifengpy weifengpy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see comment above

@arkadip-maitra arkadip-maitra added release notes: distributed (fsdp2) release notes category and removed release notes: distributed (fsdp) release notes category labels Feb 10, 2026
@arkadip-maitra

Copy link
Copy Markdown
Collaborator Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased fix_#170648 onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout fix_#170648 && git pull --rebase)

@weifengpy

Copy link
Copy Markdown
Contributor

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Rebase failed due to Command git -C /home/runner/work/pytorch/pytorch rebase refs/remotes/origin/viable/strict pull/172074/head returned non-zero exit code 1

Rebasing (1/3)
Auto-merging test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
CONFLICT (content): Merge conflict in test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
Auto-merging torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py
Auto-merging torch/distributed/fsdp/_fully_shard/_fsdp_param.py
CONFLICT (content): Merge conflict in torch/distributed/fsdp/_fully_shard/_fsdp_param.py
error: could not apply a9e5e056246... Fixes grad_dtype property being lost in fsdp
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Could not apply a9e5e056246... # Fixes grad_dtype property being lost in fsdp

Raised by https://github.com/pytorch/pytorch/actions/runs/23580628176

weifengpy added a commit that referenced this pull request Sep 15, 2026
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
weifengpy added a commit that referenced this pull request Sep 15, 2026
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
weifengpy added a commit that referenced this pull request Sep 15, 2026
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
weifengpy added a commit that referenced this pull request Sep 15, 2026
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
weifengpy added a commit that referenced this pull request Sep 18, 2026
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
weifengpy added a commit that referenced this pull request Sep 18, 2026
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
weifengpy added a commit that referenced this pull request Sep 18, 2026
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
weifengpy added a commit that referenced this pull request Sep 18, 2026
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
weifengpy added a commit that referenced this pull request Sep 18, 2026
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
weifengpy added a commit that referenced this pull request Sep 21, 2026
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
weifengpy added a commit that referenced this pull request Sep 21, 2026
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
weifengpy added a commit that referenced this pull request Sep 22, 2026
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
weifengpy added a commit that referenced this pull request Sep 22, 2026
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
weifengpy added a commit that referenced this pull request Sep 22, 2026
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
weifengpy added a commit that referenced this pull request Sep 22, 2026
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
weifengpy added a commit that referenced this pull request Sep 22, 2026
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
weifengpy added a commit that referenced this pull request Sep 22, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
weifengpy added a commit that referenced this pull request Sep 23, 2026
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
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

This branch has not been deployed

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

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests open source release notes: distributed (fsdp2) release notes category Stale triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fsdp2 support grad_dtype

10 participants