Skip to content

[FSDP2] Cast shards straight into the unsharded parameters on a size-1 shard mesh - #204750

Closed
fegin wants to merge 5 commits into
gh/fegin/375/basefrom
gh/fegin/375/head
Closed

fegin wants to merge 5 commits into
gh/fegin/375/basefrom
gh/fegin/375/head

Conversation

@fegin

@fegin fegin commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary (human-written)

With a size-1 mesh, FSDP2 skips the all-gather and does 1) a cast if needed, 2) a copy. The cast is an extra kernel that can be removed. This PR lets copy_ do the cast directly, which saves one kernel per parameter.

Agent Summary

On a size-1 shard mesh, FSDP2 skips the all-gather and copies each sharded parameter into its unsharded parameter. With a param_dtype, all_gather_inputs first cast each shard into a new tensor, which was then copied into the unsharded parameter: two kernels and a temporary for each parameter.

The single-rank copy now reads the shard of a default parameter (sharded state, a param_dtype, no CPU offload) in its sharded dtype, and the copy into the unsharded parameter does the cast. This is the same shard that the foreach-copy fast path of _get_param_all_gather_inputs reads. The cast is the same, so the unsharded parameters are bitwise identical. CPU offload, all-gather extensions, and post-forward shards still use all_gather_inputs.

When no cast is needed, the copy stays. Skipping it would need the unsharded parameter to alias the sharded one, but FSDP frees the unsharded storage on reshard.

A size-1 group with 176M bf16 expert parameters (fp32 sharded) takes less kernel time per forward and backward, excluding GEMMs, with 6 fewer launches: 3.84 -> 3.21 ms on H100, and 1.59 -> 1.37 ms on GB200.

Test Plan:

python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py -k "test_single_rank or WorldSize1"
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py

On 2x GB200: 14 passed. The two suites, run with the later chunk_cat commits of this stack applied: 135 passed, 1 failed. test_single_rank_unshard_casts_once fails without this change. The failure is test_fully_shard_alloc_from_pg (an NCCL buffer registration check), which also fails on main on this host.

This change was written with an AI assistant (Claude).

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

On a size-1 shard mesh, the PR skips the `all_gather_inputs` cast for default
parameters (sharded state, `param_dtype` set, no CPU offload, no all-gather
extension), so `copy_` casts the shard straight into the unsharded parameter.
Recommendation: Approve. The change is correct and every remaining point is
non-blocking.

Findings (7):

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py:525
Non-blocking: the change reaches more than the size-1 FSDP mesh in the title.
`wait_for_unshard` (and `unshard` at `:472-488`) set `world_size = 1` for any
non-`FSDPMeshInfo` mesh, whatever the replica count. That covers `replicate()`
(`replicate_with_fsdp.py:141`) and `fully_shard` with replicate-only
`dp_mesh_dims` (`_fsdp_init.py:123-130`). So every `replicate()` user with
`mp_policy.param_dtype` now takes this cast-in-`copy_` path at any data-parallel
size. Values stay identical: `_sharded_param_data` is the full DP-local tensor
there (`_fsdp_param.py:352-354`), and a DDP group has no post-forward mesh, so
its state is always SHARDED. But the description, release note and new test
cover only the FSDP size-1 case, and the Test Plan does not run
`test/distributed/_composable/test_replicate_mixed_precision.py`, which uses
bf16/fp16 `param_dtype`. Please mention `replicate()` and run that suite.

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py:526
Non-blocking: this repeats the `use_foreach_copy` predicate from
`_fsdp_collectives.py:420-426`, with two differences. It drops `not
needs_nonzero_dim_padding`, which is safe only because a size-1 chunk is never
padded (`_fsdp_param.py:362-366`). It adds `sharded_state ==
ShardedState.SHARDED`, which can never fail: `_fsdp_init.py:174-185` turns
`reshard_after_forward == 1` into False, so a size-1 group never has a
post-forward shard. Moving the predicate into one shared helper or an
`FSDPParam` property would stop the two copies drifting apart.

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py:524
Non-blocking: the comment says "casts a plain shard", but the guard at `:529`
only excludes `fsdp_pre_all_gather` extensions. Tensor subclasses without that
hook also take this path, as they already do on the multi-rank foreach path.

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py:532
Non-blocking: `dtypes` (`:532`, `:535`) is now built on every unshard for every
parameter, outside `if not fsdp_param.all_gather_outputs:`. That contradicts the
comment kept at `:536` ("Avoids building the lists once the outputs exist").
Keep only the branch's cast dtype outside the guard and build the list inside
it.

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py:531
Non-blocking, fine as a follow-up: `:544-562` still issues one `copy_` per
parameter. On the fast path every source is a 1-D `_sharded_param_data` and
every destination a 1-D `all_gather_outputs[0]` with the same numel.
`torch._foreach_copy_` supports a source dtype that differs from the destination
(`ForeachBinaryOpList.cu:559-599`), and the multi-rank path already uses it for
this cast (`_fsdp_collectives.py:456`). Batching the fast-path parameters into
one `_foreach_copy_` would cut launches further; it would need the
`alloc_storage` and `_unsafe_preserve_version_counter` calls hoisted, e.g.
`alloc_all_gather_outputs()` plus one guard over the tuple, as in
`_fsdp_collectives.py:590-592`.

[minor] test/distributed/_composable/fsdp/test_fully_shard_comm.py:921
Non-blocking: `ops.count(torch.ops.aten.copy_.default) == 2` passes both before
and after the PR, because the old path recorded 2 `_to_copy` plus 2 `copy_`.
Only the `assertNotIn(_to_copy)` at `:920` tells the two apart. The count also
ties the test to implementation details.

(1 more not shown, see the review run)

Reviewed commit: 7665362 (NOT the current head 33d7bcc)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

As of commit 33d7bcc with merge base f81a081 (image):
💚 Looks good so far! There are no failures yet. 💚

🟢 GREEN LIGHT - OUTDATED (earlier commit) - PR approved to be merged without human review:

  • Triviality
    • Established patterns: size-1 copy in wait_for_unshard reads _sharded_param_data and lets copy_ cast, as use_foreach_copy in _get_param_all_gather_inputs does
    • Same guards as that fast path (param_dtype, no offload_to_cpu, no fsdp_pre_all_gather), plus ShardedState.SHARDED
  • Correctness
    • needs_nonzero_dim_padding is omitted but cannot hold here: one chunk means sharded_size equals padded_sharded_size in FSDPParam init
    • Output dtype is still param_dtype and numel matches, so the copy_ branches in wait_for_unshard take the same path into a bf16 buffer
  • Preservation
    • Extension, CPU-offload, and post-forward cases still go through all_gather_inputs; the default path there has no side effects that get skipped
  • Tests
    • test_single_rank_unshard_casts_once checks there is no _to_copy, two copy_ ops, and a bitwise-equal unsharded param; the description reports it passing on GB200

reason: clean
Reviewed commit: e8016e5 (NOT the current head 33d7bcc)

Inference job

🐛 Report a wrong verdict

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

[ghstack-poisoned]
@fegin
fegin marked this pull request as ready for review November 13, 2026 19:13
@fegin
fegin requested a review from weifengpy as a code owner November 13, 2026 19:13
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 13, 2026
@fegin

fegin commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Claude encountered an error after 7s —— View job


I'll analyze this and get back to you.

@pytorchgreenlight pytorchgreenlight Bot added the GL/approved Approved by GreenLight label Nov 13, 2026
@fegin

fegin commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Claude encountered an error after 13s —— View job


I'll analyze this and get back to you.

[ghstack-poisoned]
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/approved Approved by GreenLight labels Nov 14, 2026
github-actions[bot]

This comment was marked as outdated.

@fegin

fegin commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Claude finished @fegin's task in 41s —— View job


I found nothing blocking, so I recommend Approve. HEAD (9b4d96c) is the same commit the earlier automated review looked at, and its five non-blocking points still hold.

PR Review: #204750

Summary

On a size-1 all-gather group, wait_for_unshard now reads _sharded_param_data for default mixed-precision params, so copy_ does the fp32→bf16 cast and the separate _to_copy goes away. No REVIEW.md applies. This is a re-review of a commit that has not changed. I checked the earlier findings at HEAD and found nothing new that blocks.

Code Quality

  • _fsdp_param_group.py:527-532 (non-blocking): this predicate copies use_foreach_copy in _fsdp_collectives.py:420-426 in two different forms:

    • It leaves out not fsdp_param.needs_nonzero_dim_padding. That is safe for now, because one chunk means sharded_size == padded_sharded_size (_fsdp_param.py:362-366).
    • It adds sharded_state == ShardedState.SHARDED, which can never be false here. _fsdp_init.py:174-180 maps reshard_after_forward=1 to False, so any post-forward group has at least 2 ranks.

    Moving the check into one shared helper (or an FSDPParam property) would stop the two copies from drifting apart. As written, the description's line "post-forward shards still use all_gather_inputs" refers to a branch that cannot run.

  • _fsdp_param_group.py:526 (non-blocking): the comment says "plain shard", but tensor subclasses without fsdp_pre_all_gather also take this path. They take it on the multi-rank foreach path too.

Testing

  • test_fully_shard_comm.py:921 (non-blocking): ops.count(aten.copy_.default) == 2 passes both before and after this change, since the old path did one _to_copy plus one copy_ per param. Only the assertNotIn(_to_copy) check tests the change. Consider dropping the count, or recording a second unshard() after reshard() to cover reused outputs.
  • test_fully_shard_comm.py:912 (non-blocking): the inline RecordOps mode duplicates the file's existing _RecordFuncs. TestFullyShardSingleRank._shard_mesh() already builds this (world_size, 1) mesh, so that class would be a more natural home for the test.

Performance

  • _fsdp_param_group.py:534,537 (non-blocking): dtypes used to be built only inside if not fsdp_param.all_gather_outputs:. Now it is built on every unshard, which goes against the "Avoids building the lists once the outputs exist" comment just below. You could compute it inside the guard instead. The cost is small.

Recommendation

Approve

The cast still produces bf16 values bitwise-identical to the unsharded params, and the output buffer's dtype and numel are the same as before. Every point above is non-blocking.

[ghstack-poisoned]

@github-actions github-actions Bot 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.

Automated review of 7665362: nothing blocking; ready for human review.

On a size-1 shard mesh, the PR skips the all_gather_inputs cast for default parameters (sharded state, param_dtype set, no CPU offload, no all-gather extension), so copy_ casts the shard straight into the unsharded parameter. Recommendation: Approve. The change is correct and every remaining point is non-blocking.

⚪ 7 non-blocking findings

Non-blocking: the change reaches more than the size-1 FSDP mesh in the title. wait_for_unshard (and unshard at :472-488) set world_size = 1 for any non-FSDPMeshInfo mesh, whatever the replica count. That covers replicate() (replicate_with_fsdp.py:141) and fully_shard with replicate-only dp_mesh_dims (_fsdp_init.py:123-130). So every replicate() user with mp_policy.param_dtype now takes this cast-in-copy_ path at any data-parallel size. Values stay identical: _sharded_param_data is the full DP-local tensor there (_fsdp_param.py:352-354), and a DDP group has no post-forward mesh, so its state is always SHARDED. But the description, release note and new test cover only the FSDP size-1 case, and the Test Plan does not run test/distributed/_composable/test_replicate_mixed_precision.py, which uses bf16/fp16 param_dtype. Please mention replicate() and run that suite.


fsdp_param.sharded_state == ShardedState.SHARDED

Non-blocking: this repeats the use_foreach_copy predicate from _fsdp_collectives.py:420-426, with two differences. It drops not needs_nonzero_dim_padding, which is safe only because a size-1 chunk is never padded (_fsdp_param.py:362-366). It adds sharded_state == ShardedState.SHARDED, which can never fail: _fsdp_init.py:174-185 turns reshard_after_forward == 1 into False, so a size-1 group never has a post-forward shard. Moving the predicate into one shared helper or an FSDPParam property would stop the two copies drifting apart.


# The copy below casts a plain shard, which saves a cast kernel

Non-blocking: the comment says "casts a plain shard", but the guard at :529 only excludes fsdp_pre_all_gather extensions. Tensor subclasses without that hook also take this path, as they already do on the multi-rank foreach path.


dtypes = [fsdp_param.param_dtype]

Non-blocking: dtypes (:532, :535) is now built on every unshard for every parameter, outside if not fsdp_param.all_gather_outputs:. That contradicts the comment kept at :536 ("Avoids building the lists once the outputs exist"). Keep only the branch's cast dtype outside the guard and build the list inside it.


all_gather_inputs = [fsdp_param._sharded_param_data]

Non-blocking, fine as a follow-up: :544-562 still issues one copy_ per parameter. On the fast path every source is a 1-D _sharded_param_data and every destination a 1-D all_gather_outputs\[0\] with the same numel. torch._foreach_copy_ supports a source dtype that differs from the destination (ForeachBinaryOpList.cu:559-599), and the multi-rank path already uses it for this cast (_fsdp_collectives.py:456). Batching the fast-path parameters into one _foreach_copy_ would cut launches further; it would need the alloc_storage and _unsafe_preserve_version_counter calls hoisted, e.g. alloc_all_gather_outputs() plus one guard over the tuple, as in _fsdp_collectives.py:590-592.


self.assertEqual(ops.count(torch.ops.aten.copy_.default), 2)

Non-blocking: ops.count(torch.ops.aten.copy_.default) == 2 passes both before and after the PR, because the old path recorded 2 _to_copy plus 2 copy_. Only the assertNotIn(_to_copy) at :920 tells the two apart. The count also ties the test to implementation details.


class RecordOps(TorchDispatchMode):

Non-blocking: the inline RecordOps dispatch mode duplicates the file's _RecordFuncs (:1138-1148), which returns its op list from __enter__. TestFullyShardSingleRank._shard_mesh() (:1156-1160) already builds this (world_size, 1) mesh, so that class is the more natural home for the test. Optionally, also record a second unshard() after reshard() to cover the case where the outputs are reused.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 14, 2026
[ghstack-poisoned]
@fegin

fegin commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 17, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

jkosnox pushed a commit to jkosnox/pytorch that referenced this pull request Nov 17, 2026
…1 shard mesh (pytorch#204750)

### Summary (human-written)
With a size-1 mesh, FSDP2 skips the all-gather and does 1) a cast if needed, 2) a copy. The cast is an extra kernel that can be removed. This PR lets `copy_` do the cast directly, which saves one kernel per parameter.

### Agent Summary
On a size-1 shard mesh, FSDP2 skips the all-gather and copies each sharded parameter into its unsharded parameter. With a param_dtype, all_gather_inputs first cast each shard into a new tensor, which was then copied into the unsharded parameter: two kernels and a temporary for each parameter.

The single-rank copy now reads the shard of a default parameter (sharded state, a param_dtype, no CPU offload) in its sharded dtype, and the copy into the unsharded parameter does the cast. This is the same shard that the foreach-copy fast path of _get_param_all_gather_inputs reads. The cast is the same, so the unsharded parameters are bitwise identical. CPU offload, all-gather extensions, and post-forward shards still use all_gather_inputs.

When no cast is needed, the copy stays. Skipping it would need the unsharded parameter to alias the sharded one, but FSDP frees the unsharded storage on reshard.

A size-1 group with 176M bf16 expert parameters (fp32 sharded) takes less kernel time per forward and backward, excluding GEMMs, with 6 fewer launches: 3.84 -> 3.21 ms on H100, and 1.59 -> 1.37 ms on GB200.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py -k "test_single_rank or WorldSize1"
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
```

On 2x GB200: 14 passed. The two suites, run with the later chunk_cat commits of this stack applied: 135 passed, 1 failed. test_single_rank_unshard_casts_once fails without this change. The failure is test_fully_shard_alloc_from_pg (an NCCL buffer registration check), which also fails on main on this host.

This change was written with an AI assistant (Claude).

Pull Request resolved: pytorch#204750
Approved by: https://github.com/pytorchgreenlight, https://github.com/weifengpy
ghstack dependencies: pytorch#204942
pytorchmergebot pushed a commit that referenced this pull request Nov 17, 2026
### Summary (human-written)
The cast path of the fused FSDP2 chunk_cat kernel (`fsdp::chunk_cat_mixed_dtype`) reads only 2 bytes at a time. This PR vectorizes the cast path to speed up the FSDP2 copy-in for gradient groups with mixed dtypes. ATen `_chunk_cat` is not changed.

### Agent Summary
fsdp::chunk_cat_mixed_dtype copies a reduce-scatter group with mixed gradient dtypes in one fused kernel: one launch copies the fp32 gradients and one launch casts the bf16 or fp16 gradients into the fp32 reduce-scatter input. The cast launch converted one element per thread per iteration with 2-byte loads and 4-byte stores, and the grid was sized for 16 output bytes per thread. It reached 1.7 TB/s on H100.

The cast branch of copy_chunk_with_pad in torch/csrc/distributed/fsdp/ChunkCat.cu now uses the same head / aligned body / tail split as the copy path. The head makes dst 16-byte aligned. Each body iteration (unit) loads 8 source elements with the widest load the source alignment allows (16, 8, 4, or 2 bytes, through the read-only cache), converts them with the same c10 cast as before, and writes two 16-byte stores. Padding past the source is written as zeros in the same stores. cast_bytes_per_block sizes the cast grid: each thread takes one unit up to three waves of resident threads, two up to six waves, and so on, up to four. On one GB200, with 8 chunks of 16 or 128 bf16 inputs into fp32 (1 MB to 4 GB of output), a fixed one unit per thread is 11-17% slower than this at 64 MB and 46-53% slower from 1 GB up, and a fixed four units per thread is up to 17% slower at 16 MB. The heuristic is within 3.5% of the best fixed choice at every size.

Only the FSDP kernel changes. Uniform groups go through _chunk_cat, whose ATen kernel has the same cast loop; changing it is left to a separate PR.

The output is bitwise identical, including padding, all source and destination alignments, odd sizes, and both bf16 and fp16. The tests compare against _chunk_cat of the inputs cast to fp32 first, which runs the same-dtype copy kernel. test_numerics_cast_alignments covers all four load widths, every head length of the padded chunk, padded units and tails, an all-padding chunk, and chunks that span several blocks. test_numerics_cast_several_units_per_thread covers an input large enough for four units per thread on GPUs with up to 304 SMs.

Kernel time from the profiler, FSDP2 copy-in, bf16 into fp32, old -> new:

| | H100 | GB300 | GB200 |
|---|---|---|---|
| 285M elements, 64 chunks | 0.955 -> 0.841 ms (1.14x) | 0.709 -> 0.266 ms (2.66x) | 0.721 -> 0.260 ms (2.77x) |
| 201M elements, 1 chunk | 0.710 -> 0.585 ms (1.21x) | 0.544 -> 0.180 ms (3.02x) | 0.552 -> 0.181 ms (3.05x) |

The GB300 numbers come from a standalone build of the old and new kernels.

Test Plan:

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py -k "ChunkCatMixedDtype or NativeCollectiveCopy or PythonCustomOp"
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_comm.py test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
```

On 2 GB200 GPUs, the first command passes 15 of 15 and the second passes 136 of 137. The one failure, test_fully_shard_alloc_from_pg, expects NCCL to register no buffer before allocation from the process group is enabled, but NCCL 2.30.7 registers a 2 MB buffer. This change does not touch that path.

This change was written with an AI assistant (Claude).

Pull Request resolved: #204752
Approved by: https://github.com/weifengpy
ghstack dependencies: #204942, #204750
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants