Skip to content

[FSDP2] Discard a pending post-forward all-gather when resharding - #199729

Closed
weifengpy wants to merge 4 commits into
gh/weifengpy/213/basefrom
gh/weifengpy/213/head
Closed

weifengpy wants to merge 4 commits into
gh/weifengpy/213/basefrom
gh/weifengpy/213/head

Conversation

@weifengpy

@weifengpy weifengpy commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft #199726 (option 3), which inherited it from #188276, and is based on main so it can land on its own.

With reshard_after_forward set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in finalize_backward, but a backward that is not the last one, as in gradient accumulation with set_is_last_backward(False), only reshards the group to the full mesh in post_backward and keeps the pending result. The next forward's unshard then returns early because a result is pending, and wait_for_unshard copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (start (0) + length (512) exceeds dimension size (256) in the regression test). _to_sharded now waits for a pending all-gather result and discards it before the group returns to the sharded state, as finalize_backward and _reset_iter_state already do for mistargeted unshards. The three share the wait in _wait_all_gather, which waits through the FSDP device handle as #199677 made finalize_backward do. Only that path changes: unshard issues nothing while the group is unsharded, so a result is pending when _to_sharded runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed.

Test Plan: the local build predates main, so the tests ran with the same change on top of #199430, whose FSDP2 code paths for this bug match main's; the change differs only in the finalize_backward lines #199677 rewrote. test_unused_backward_prefetch_with_post_forward_mesh fails without the _to_sharded change, with the stale result still pending after the non-final backward, and passes with it.

python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch

All 8 tests pass on 4 B200 GPUs.

Co-authored-by: wuyl1 [email protected]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 0751e83 with merge base 381cc3e (image):
💚 Looks good so far! There are no failures yet. 💚

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

  • Triviality
    • _to_sharded in _fsdp_param_group.py now waits on and discards a pending _all_gather_result, changing FSDP2 collective lifecycle
    • _to_sharded is shared by reshard, _reset_iter_state and the state-dict hook, so the new wait runs on every path that leaves the post-forward state
    • Holding it safe means arguing a state-machine invariant: unshard returns early when unsharded, so only a post-forward gather can be pending
  • Review value
    • A prior review comment on the PR already proposed code changes: a FSDPParamGroup method in place of the free _wait_all_gather, and a more general comment
    • Whether silently dropping an unused prefetch is right, versus not issuing it at all, is a design call for an FSDP owner
  • Tests
    • test_unused_backward_prefetch_with_post_forward_mesh covers the gradient-accumulation path with reshard_after_forward=2, so this is not a test gap

reason: not_trivial
Reviewed commit: a1f40c1 (NOT the current head 0751e83)

Inference job

🐛 Report a wrong verdict

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

[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Oct 5, 2026
> AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft #199726 (option 3), which inherited it from #188276, and is based on main so it can land on its own.
>
> With `reshard_after_forward` set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in `finalize_backward`, but a backward that is not the last one, as in gradient accumulation with `set_is_last_backward(False)`, only reshards the group to the full mesh in `post_backward` and keeps the pending result. The next forward's `unshard` then returns early because a result is pending, and `wait_for_unshard` copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (`start (0) + length (512) exceeds dimension size (256)` in the regression test). `_to_sharded` now waits for a pending all-gather result and discards it before the group returns to the sharded state, as `finalize_backward` and `_reset_iter_state` already do for mistargeted unshards. The three share the wait in `_wait_all_gather`, which waits through the FSDP device handle as #199677 made `finalize_backward` do. Only that path changes: `unshard` issues nothing while the group is unsharded, so a result is pending when `_to_sharded` runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed.
>
> Test Plan: the local build predates main, so the tests ran with the same change on top of #199430, whose FSDP2 code paths for this bug match main's; the change differs only in the `finalize_backward` lines #199677 rewrote. `test_unused_backward_prefetch_with_post_forward_mesh` fails without the `_to_sharded` change, with the stale result still pending after the non-final backward, and passes with it.
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch
> ```
> All 8 tests pass on 4 B200 GPUs.

ghstack-source-id: 9a55a31
Pull-Request: #199729
weifengpy added a commit that referenced this pull request Oct 5, 2026
> AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft #199726 (option 3), which inherited it from #188276, and is based on main so it can land on its own.
>
> With `reshard_after_forward` set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in `finalize_backward`, but a backward that is not the last one, as in gradient accumulation with `set_is_last_backward(False)`, only reshards the group to the full mesh in `post_backward` and keeps the pending result. The next forward's `unshard` then returns early because a result is pending, and `wait_for_unshard` copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (`start (0) + length (512) exceeds dimension size (256)` in the regression test). `_to_sharded` now waits for a pending all-gather result and discards it before the group returns to the sharded state, as `finalize_backward` and `_reset_iter_state` already do for mistargeted unshards. The three share the wait in `_wait_all_gather`, which waits through the FSDP device handle as #199677 made `finalize_backward` do. Only that path changes: `unshard` issues nothing while the group is unsharded, so a result is pending when `_to_sharded` runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed.
>
> Test Plan: the local build predates main, so the tests ran with the same change on top of #199430, whose FSDP2 code paths for this bug match main's; the change differs only in the `finalize_backward` lines #199677 rewrote. `test_unused_backward_prefetch_with_post_forward_mesh` fails without the `_to_sharded` change, with the stale result still pending after the non-final backward, and passes with it.
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch
> ```
> All 8 tests pass on 4 B200 GPUs.

ghstack-source-id: 9a55a31
Pull-Request: #199729
weifengpy added a commit that referenced this pull request Oct 5, 2026
…with FSDP-owned buffers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. It is one of three alternatives, #199720 (option 1), #199721 (option 2) and #199726 (option 3), and is not ready for review.
>
> This keeps option 2's `AllGatherLayout` contract and changes who owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. By default FSDP owns it: on a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it likes and returns `AllGatherOutputs(tensors, buffers)` with outputs that view those buffers. The group then frees the buffers on reshard, re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refills the same outputs in place, so `reshard_after_forward` keeps saving parameter memory for custom layouts too. The default layout keeps today's per-output allocation and its copy-out. Backend-owned storage, #188276's model, becomes an explicit opt-in: only a `BackendOwnedAllGatherLayout`, whose `release_output()` is abstract, may return outputs that FSDP never frees, and FSDP calls `release_output()` after reshard, after a discarded prefetch, and after a failed setup. `release_output` moves from `AllGather` to the layout, and `AllGather.reuses_output_storage` is removed.
>
> `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts. `set_all_gather_layout` is the only way to install a layout, and `AllGather` no longer carries one. A layout that needs its own collective sets `comm`, and installing the layout installs that comm in the same call. While such a layout is installed, `set_custom_all_gather` rejects any other comm, as do the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm`; installing another layout lifts the binding and keeps the comm. An installed `DefaultAllGatherLayout`, including the native copy's, takes a fast path that runs the previous default code: `foreach_all_gather` builds no `AllGatherInputMetadata`, calls no `prepare`, and enters no version-counter context, `foreach_all_gather_copy_out` calls the layout's `output_fn` without building a copy plan, and reshard frees layout storage only for custom layouts. Copy-out dispatches on the installed layout rather than the per-call one, because a custom layout's rank-major fallback still needs the ownership-aware path. #199729 lands the `_to_sharded` fix for a pending post-forward all-gather separately on main; this draft carries the same fix and its `_wait_all_gather` helper so that it stands alone on the stack, while the regression test stays in #199729. `FSDPParam._unsharded_param` stays lazily created, because out-of-tree patches of `post_backward` check it with `hasattr`, and `init_unsharded_param` honors the output's storage offset so that parameters can be views into a layout's shared buffer.
>
> The group frees shared buffers after all parameters transition, because freeing per parameter broke post-forward resharding, where a parameter still reads a buffer another parameter already left. A group's first finalize decides whether it owns buffers, and MORI's adapter would subclass the opt-in layout, set its `comm`, and move `release_output` to it. Review the ownership rules, `AllGatherOutputs` and `AllGatherFinalizeMetadata` in `_all_gather_layout.py` first, then the default fast path, buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add an FSDP-owned parameter-contiguous layout that checks its buffer is freed after reshard and refilled with one copy, keep #188276's backend-owned tests on the opt-in, cover the rejected ownership cases, and check the setter rules. `TestFullyShardLayoutParity` reuses its worker processes through `FSDPTestContinuous` instead of launching processes per test, which cuts its local runtime for its 77 tests from 1652 s to between 353 s and 447 s; the compiled case resets dynamo itself because reused workers skip `setUp` and `tearDown`.
>
> Test Plan (local build, 4 B200 GPUs), run on this revision:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardAllGatherLayoutSetters
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass. The extensions, mixed-precision and training suites ran on earlier revisions of this draft and were not rerun on this one.

ghstack-source-id: 02f1151
Pull-Request: #199726
@weifengpy
weifengpy marked this pull request as ready for review October 5, 2026 05:58
@weifengpy
weifengpy requested a review from anshul-si October 5, 2026 05:58
@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 1m 58s —— View job


The fix looks correct and the test is a real regression test; my only requests are two small cleanups to the helper and the new comment.

PR Review: #199729

Summary

The PR makes FSDPParamGroup._to_sharded wait for and discard any pending _all_gather_result. It also moves the existing wait logic in finalize_backward and _reset_iter_state into a shared _wait_all_gather helper. No REVIEW.md files apply.

I traced the bug through unshard / wait_for_unshard / post_backward / _root_post_backward_final_callback, and the root cause in the description holds:

  • unshard returns early while the group is UNSHARDED. So _to_sharded can only see a pending result when it is leaving SHARDED_POST_FORWARD.
  • In that case the result was gathered over post_forward_mesh_info. Once the group flips to SHARDED, _all_gather_process_group points at the full mesh, so a later copy-out could never have worked.
  • This means the discard does not change any path that worked before. The variant with set_reshard_after_backward(False) keeps the group in SHARDED_POST_FORWARD. The next copy-out then uses the post-forward PG, so that variant is consistent and needs no fix.

Two minor code-quality issues are below. Nothing blocks the PR.

Code Quality

  • Duplicated wait-and-clear (torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py:600-602, :890-894, :1108-1113). All three call sites run the same two lines, _wait_all_gather(self._all_gather_result) followed by self._all_gather_result = None, and they live on the object that owns the state. A method such as FSDPParamGroup._discard_all_gather_result() would:

    • do the None check, the wait and the clear in one place;
    • use self.device_handle directly, instead of looking the handle up again from all_gather_output.device;
    • make it impossible to wait and then forget to clear.

    The free function in _fsdp_collectives.py then has no other caller and can go.

  • The new comment in _to_sharded names only one cause (_fsdp_param_group.py:1109-1111). It describes the "backward prefetch of a group that backward did not use" case. But _to_sharded is shared with reshard, _reset_iter_state and the state-dict pre-hooks (to_sharded_hook, :1183), and the discard rests on a general rule: any result pending at this point was gathered over the post-forward mesh. Please state that rule and give the unused-backward prefetch as an example, e.g. "a pending all-gather here was issued in the post-forward state over the post-forward mesh and cannot be copied out after resharding to the full mesh; e.g. a backward prefetch of a group unused in backward". Otherwise the next reader may think the other callers never reach this branch.

Recommendation

Approve. The fix is minimal and targets the actual root cause. The regression test (test_unused_backward_prefetch_with_post_forward_mesh) uses gradient accumulation with set_is_last_backward(False), which skips finalize_backward, so it exercises the failing path. The two items above are small cleanups.

weifengpy added a commit that referenced this pull request Oct 6, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> #197701's native copy becomes `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`, and `set_all_gather_layout` replaces `set_all_gather_output_fn` as the only way to install a layout. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. An installed `DefaultAllGatherLayout`, including the native copy's, takes a fast path that runs the previous default code.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. #199729 lands the `_to_sharded` fix for a pending post-forward all-gather separately on main; this draft carries the same fix and its `_wait_all_gather` helper so that it stands alone on the stack.
>
> Review `_all_gather_layout.py` first, then the default fast path and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_train_parity_multi_group -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> The layout unit and setter tests (29) and the parity suite (38) pass on this revision. The other commands ran one revision earlier, which differed only in the test layout's views and a docstring. The full comm file had 125 passed and 2 skipped, and `test_fully_shard_alloc_from_pg` failed, as it also does on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The other suites passed: extensions 9, mixed precision 26, training 7, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 75f08b1
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 6, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> #197701's native copy becomes `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`, and `set_all_gather_layout` replaces `set_all_gather_output_fn` as the only way to install a layout. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. #199729 lands the `_to_sharded` fix for a pending post-forward all-gather separately on main; this draft carries the same fix and its `_wait_all_gather` helper so that it stands alone on the stack.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 5ceea13
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 6, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. #199729 lands the `_to_sharded` fix for a pending post-forward all-gather separately on main; this draft carries the same fix and its `_wait_all_gather` helper so that it stands alone on the stack.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 5ceea13
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 6, 2026
> AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft #199726 (option 3), which inherited it from #188276, and is based on main so it can land on its own.
>
> With `reshard_after_forward` set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in `finalize_backward`, but a backward that is not the last one, as in gradient accumulation with `set_is_last_backward(False)`, only reshards the group to the full mesh in `post_backward` and keeps the pending result. The next forward's `unshard` then returns early because a result is pending, and `wait_for_unshard` copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (`start (0) + length (512) exceeds dimension size (256)` in the regression test). `_to_sharded` now waits for a pending all-gather result and discards it before the group returns to the sharded state, as `finalize_backward` and `_reset_iter_state` already do for mistargeted unshards. The three share the wait in `_wait_all_gather`, which waits through the FSDP device handle as #199677 made `finalize_backward` do. Only that path changes: `unshard` issues nothing while the group is unsharded, so a result is pending when `_to_sharded` runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed.
>
> Test Plan: the local build predates main, so the tests ran with the same change on top of #199430, whose FSDP2 code paths for this bug match main's; the change differs only in the `finalize_backward` lines #199677 rewrote. `test_unused_backward_prefetch_with_post_forward_mesh` fails without the `_to_sharded` change, with the stale result still pending after the non-final backward, and passes with it.
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch
> ```
> All 8 tests pass on 4 B200 GPUs.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: 9a55a31
Pull-Request: #199729
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Oct 6, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 2216a7b
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 6, 2026
> AI-assisted change prepared with Claude Code. It was split out of the all-gather contract draft #199726 (option 3), which inherited it from #188276, and is based on main so it can land on its own.
>
> With `reshard_after_forward` set to an int, a group that forward used but backward does not use is still prefetched by the next group's pre-backward. The group is in its post-forward state, so the prefetch all-gathers its post-forward shards over the smaller post-forward mesh, and since the group's own pre-backward never runs, nothing waits for that result. The last backward discards it in `finalize_backward`, but a backward that is not the last one, as in gradient accumulation with `set_is_last_backward(False)`, only reshards the group to the full mesh in `post_backward` and keeps the pending result. The next forward's `unshard` then returns early because a result is pending, and `wait_for_unshard` copies out a buffer gathered over the post-forward mesh as if the full mesh had gathered it, which fails in the copy-out (`start (0) + length (512) exceeds dimension size (256)` in the regression test). `_to_sharded` now waits for a pending all-gather result and discards it before the group returns to the sharded state, as `finalize_backward` and `_reset_iter_state` already do for mistargeted unshards. The three share the wait in `_wait_all_gather`, which waits through the FSDP device handle as #199677 made `finalize_backward` do. Only that path changes: `unshard` issues nothing while the group is unsharded, so a result is pending when `_to_sharded` runs only if an all-gather issued in the post-forward state was never waited on, such as this backward prefetch, and copying such a result out over the full mesh always failed.
>
> Test Plan: the local build predates main, so the tests ran with the same change on top of #199430, whose FSDP2 code paths for this bug match main's; the change differs only in the `finalize_backward` lines #199677 rewrote. `test_unused_backward_prefetch_with_post_forward_mesh` fails without the `_to_sharded` change, with the stale result still pending after the non-final backward, and passes with it.
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardPrefetch
> ```
> All 8 tests pass on 4 B200 GPUs.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: 1209001
Pull-Request: #199729
weifengpy added a commit that referenced this pull request Oct 6, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: 2216a7b
Pull-Request: #199726

@anshul-si anshul-si 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.

LGTM

weifengpy added a commit that referenced this pull request Oct 14, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: ce2d349
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 14, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: ce2d349
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 14, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: ce2d349
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: 260e0f6
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: 7bb21f4
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: b16488f
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: b16488f
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: b16488f
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: f82d37d
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
…fers

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
ghstack-source-id: f82d37d
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
…fers

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it from 6 positional fields or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers. Replacements patched in with the old signatures, e.g. LoongForge's delta-FP8 all-gather, raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; use `set_all_gather_layout(DefaultAllGatherLayout(fn))`.

<!-- Author: add your own summary line here before marking this PR ready for review -->

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields does not break layouts that build them.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, modules with several parameter groups reject it, and installing another layout restores the default comm unless it brings its own. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, the comm and layout cannot be replaced while an all-gather is pending, parameters are unsharded or outputs view its buffers; the default layout keeps #197701's rules for `set_custom_all_gather`. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's finalize; `DefaultAllGatherLayout` packs with its `copy_in`, so a subclass can override that, and copies out with its `output_fn`. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus two NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs and refills, the default copy-out with and without delegation, a delegating Shard(1) layout, a `copy_in` override, an extension under a shared buffer, recovery after a rejected result, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision, training-parity and inference tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on #197701 on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 199 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 6 (one more needs 4 GPUs and was skipped on 2), public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: b8e74b2
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
…fers

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it from 6 positional fields or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers. Replacements patched in with the old signatures, e.g. LoongForge's delta-FP8 all-gather, raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; use `set_all_gather_layout(DefaultAllGatherLayout(fn))`.

<!-- Author: add your own summary line here before marking this PR ready for review -->

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields does not break layouts that build them.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, modules with several parameter groups reject it, and installing another layout restores the default comm unless it brings its own. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, the comm and layout cannot be replaced while an all-gather is pending, parameters are unsharded or outputs view its buffers; the default layout keeps #197701's rules for `set_custom_all_gather`. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's finalize; `DefaultAllGatherLayout` packs with its `copy_in`, so a subclass can override that, and copies out with its `output_fn`. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus two NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs and refills, the default copy-out with and without delegation, a delegating Shard(1) layout, a `copy_in` override, an extension under a shared buffer, recovery after a rejected result, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision, training-parity and inference tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on #197701 on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 199 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 6 (one more needs 4 GPUs and was skipped on 2), public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: b8e74b2
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers. Replacements patched in with the old signatures, e.g. LoongForge's delta-FP8 all-gather, raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed, so assigning it is silently ignored; use `set_all_gather_layout(DefaultAllGatherLayout(fn))` with #200034's callback signature.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, it must be installed on a single parameter group, since such a layout typically keeps per-call state, and installing another layout installs `DefaultAllGather` unless it brings its own comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, `set_custom_all_gather` and `set_all_gather_layout` cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers; with the default layout, `set_custom_all_gather` behaves as before. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that a `DefaultAllGatherLayout` copies out with its `output_fn` directly; it packs with its `copy_in`, so a subclass can override that. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2 to 3% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus two NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs and refills, the default copy-out with and without delegation, a delegating Shard(1) layout, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, recovery after a rejected result, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision, training-parity and inference tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on #197701 on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 199 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 6 (one more needs 4 GPUs and was skipped on 2), public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 1ce3ffe
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers. Replacements patched in with the old signatures, e.g. LoongForge's delta-FP8 all-gather, raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed, so assigning it is silently ignored; use `set_all_gather_layout(DefaultAllGatherLayout(fn))` with #200034's callback signature.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, it must be installed on a single parameter group, since such a layout typically keeps per-call state, and installing another layout installs `DefaultAllGather` unless it brings its own comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, `set_custom_all_gather` and `set_all_gather_layout` cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers; with the default layout, `set_custom_all_gather` behaves as before. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that a `DefaultAllGatherLayout` copies out with its `output_fn` directly; it packs with its `copy_in`, so a subclass can override that. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2 to 3% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus two NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs and refills, the default copy-out with and without delegation, a delegating Shard(1) layout, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, recovery after a rejected result, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision, training-parity and inference tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on #197701 on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 199 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 6 (one more needs 4 GPUs and was skipped on 2), public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 1ce3ffe
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers. Replacements patched in with the old signatures, e.g. LoongForge's delta-FP8 all-gather, raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed, so assigning it is silently ignored; use `set_all_gather_layout(DefaultAllGatherLayout(fn))` with #200034's callback signature.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, one call cannot install it on several parameter groups, and each module needs its own instance, since such a layout typically keeps per-call state, and installing another layout installs `DefaultAllGather` unless it brings its own comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, `set_custom_all_gather` and `set_all_gather_layout` cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers; with the default layout, `set_custom_all_gather` behaves as before. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that a `DefaultAllGatherLayout` copies out with its `output_fn` directly; it packs with its `copy_in`, so a subclass can override that. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus two NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs and refills, the default copy-out with and without delegation, a delegating Shard(1) layout, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, recovery after a rejected result, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision, training-parity and inference tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on #197701 on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 199 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 6 (one more needs 4 GPUs and was skipped on 2), public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 727488a
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 15, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers. Replacements patched in with the old signatures, e.g. LoongForge's delta-FP8 all-gather, raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed, so assigning it is silently ignored; use `set_all_gather_layout(DefaultAllGatherLayout(fn))` with #200034's callback signature.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, one call cannot install it on several parameter groups, and each module needs its own instance, since such a layout typically keeps per-call state, and installing another layout installs `DefaultAllGather` unless it brings its own comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, `set_custom_all_gather` and `set_all_gather_layout` cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers; with the default layout, `set_custom_all_gather` behaves as before. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that a `DefaultAllGatherLayout` copies out with its `output_fn` directly; it packs with its `copy_in`, so a subclass can override that. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus two NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs and refills, the default copy-out with and without delegation, a delegating Shard(1) layout, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, recovery after a rejected result, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision, training-parity and inference tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on #197701 on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 199 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 6 (one more needs 4 GPUs and was skipped on 2), public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 727488a
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 21, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers. Replacements patched in with the old signatures, e.g. LoongForge's delta-FP8 all-gather, raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed, so assigning it is silently ignored; use `set_all_gather_layout(DefaultAllGatherLayout(fn))` with #200034's callback signature.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads still fails, now with a `StopIteration`, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, one call cannot install it on several parameter groups, and each module needs its own instance, since such a layout typically keeps per-call state, and installing another layout installs `DefaultAllGather` unless it brings its own comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, `set_custom_all_gather` and `set_all_gather_layout` cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers; with the default layout, `set_custom_all_gather` behaves as before. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that a `DefaultAllGatherLayout` copies out with its `output_fn` directly; it packs with its `copy_in`, so a subclass can override that. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus two NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs and refills, the default copy-out with and without delegation, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, recovery after a rejected result, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision, training-parity and inference tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on #197701 on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 199 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 6 (one more needs 4 GPUs and was skipped on 2), public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 482e72a
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 21, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. FSDP gives the layout copies of its output and buffer lists, so a layout cannot change them behind those checks. A layout bound to its comm records the parameter group it serves, so installing the same instance on another module raises; its comm must not be installed on another group either, which FSDP does not check. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected refill frees the buffers it re-allocated.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, one call cannot install it on several parameter groups, and each module needs its own instance, since such a layout typically keeps per-call state, and installing another layout installs `DefaultAllGather` unless it brings its own comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, `set_custom_all_gather` and `set_all_gather_layout` cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers; with the default layout, `set_custom_all_gather` behaves as before. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that a `DefaultAllGatherLayout` copies out with its `output_fn` directly; it packs with its `copy_in`, so a subclass can override that. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, custom layouts under inference mode, recovery after a rejected result, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 181 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 86aea82
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Oct 22, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, one call cannot install it on several parameter groups, and each module needs its own instance, since such a layout typically keeps per-call state, so a module with several parameter groups rejects it. Installing another layout installs `DefaultAllGather` unless it brings its own comm. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, the setters cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers. The outputs of a `DefaultAllGatherLayout` depend on neither its copy-out function nor the comm, so swapping such layouts works at any time, like the removed hook, and so does `set_custom_all_gather` under one, as on main. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that for a `DefaultAllGatherLayout` it calls only `copy_in`, which a subclass can override, and copies out with its `output_fn` directly. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 185 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: ab79655
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 5, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, one call cannot install it on several parameter groups, and each module needs its own instance, since such a layout typically keeps per-call state, so a module with several parameter groups rejects it. Installing another layout installs `DefaultAllGather` unless it brings its own comm. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, the setters cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers. The outputs of a `DefaultAllGatherLayout` depend on neither its copy-out function nor the comm, so swapping such layouts works at any time, like the removed hook, and so does `set_custom_all_gather` under one, as on main. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that for a `DefaultAllGatherLayout` it calls only `copy_in`, which a subclass can override, and copies out with its `output_fn` directly. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 185 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 2df0967
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 5, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, one call cannot install it on several parameter groups, and each module needs its own instance, since such a layout typically keeps per-call state, so a module with several parameter groups rejects it. Installing another layout installs `DefaultAllGather` unless it brings its own comm. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, the setters cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers. The outputs of a `DefaultAllGatherLayout` depend on neither its copy-out function nor the comm, so swapping such layouts works at any time, like the removed hook, and so does `set_custom_all_gather` under one, as on main. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that for a `DefaultAllGatherLayout` it calls only `copy_in`, which a subclass can override, and copies out with its `output_fn` directly. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 185 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 603ff0b
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 5, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`; installing the layout installs that comm, one call cannot install it on several parameter groups, and each module needs its own instance, since such a layout typically keeps per-call state, so a module with several parameter groups rejects it. Installing another layout installs `DefaultAllGather` unless it brings its own comm. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. With a custom layout, the setters cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers. The outputs of a `DefaultAllGatherLayout` depend on neither its copy-out function nor the comm, so swapping such layouts works at any time, like the removed hook, and so does `set_custom_all_gather` under one, as on main. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that for a `DefaultAllGatherLayout` it calls only `copy_in`, which a subclass can override, and copies out with its `output_fn` directly. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 185 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: d99483e
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 5, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout whose output needs a specific collective names that comm's type as `comm_type`. The comm is installed with `set_custom_all_gather`, before the layout, and FSDP passes it each call's layout metadata as `output_metadata` (`None` for a call with rank-major output), so the comm keeps no per-call state and one instance can serve any number of parameter groups. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject comms of other types, and replacing the layout keeps the installed comm. Only comms of a layout's `comm_type` receive `output_metadata`, so existing custom comms keep their signature. With a custom layout, the setters cannot replace the comm or layout while an all-gather is pending, parameters are unsharded or outputs view its buffers. The outputs of a `DefaultAllGatherLayout` depend on neither its copy-out function nor the comm, so swapping such layouts works at any time, like the removed hook, and so does `set_custom_all_gather` under one, as on main. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that for a `DefaultAllGatherLayout` it calls only `copy_in`, which a subclass can override, and copies out with its `output_fn` directly. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 185 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 5074fe9
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 5, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout whose output needs a specific collective names that comm's type as `comm_type`. The comm is installed with `set_custom_all_gather`, before the layout, and FSDP passes it each call's layout metadata as `output_metadata` (`None` for a call with rank-major output), so the comm keeps no per-call state and one instance can serve any number of parameter groups. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject comms of other types, and replacing the layout keeps the installed comm. Only comms of a layout's `comm_type` receive `output_metadata`, so existing custom comms keep their signature. The comm setters work at any time, as on main, since comms keep no per-call state and own no outputs. With a custom layout, `set_all_gather_layout` cannot replace it, or install one, while an all-gather is pending, parameters are unsharded or outputs view its buffers, since only the layout that created those outputs can refill them. The outputs of a `DefaultAllGatherLayout` depend on neither its copy-out function nor the comm, so swapping such layouts works at any time, like the removed hook. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that for a `DefaultAllGatherLayout` it calls only `copy_in`, which a subclass can override, and copies out with its `output_fn` directly. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 185 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: eb9d812
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 6, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout whose output needs a specific collective names that comm's type as `comm_type`. The comm is installed with `set_custom_all_gather`, before the layout, and FSDP passes it each call's layout metadata as `output_metadata` (`None` for a call with rank-major output), so the comm keeps no per-call state and one instance can serve any number of parameter groups. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject comms of other types, and replacing the layout keeps the installed comm. Only comms of a layout's `comm_type` receive `output_metadata`, so existing custom comms keep their signature. The comm setters work at any time, as on main, since comms keep no per-call state and own no outputs. `set_all_gather_layout` changes layouts only between iterations: it cannot replace a layout while an all-gather is pending or parameters are unsharded, nor after outputs view a custom layout's buffers, since only the layout that created those outputs can refill them. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that for a `DefaultAllGatherLayout` it calls only `copy_in`, which a subclass can override, and copies out with its `output_fn` directly. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 185 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 96475c2
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 6, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout whose output needs a specific collective names that comm's type as `comm_type`. The comm is installed with `set_custom_all_gather`, before the layout, and FSDP passes it each call's layout metadata as `output_metadata` (`None` for a call with rank-major output), so the comm keeps no per-call state and one instance can serve any number of parameter groups. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject comms of other types, and replacing the layout keeps the installed comm. Only comms of a layout's `comm_type` receive `output_metadata`, so existing custom comms keep their signature. The comm setters work at any time, as on main, since comms keep no per-call state and own no outputs. `set_all_gather_layout` changes layouts only between iterations: it cannot replace a layout while an all-gather is pending or parameters are unsharded, nor after outputs view a custom layout's buffers, since only the layout that created those outputs can refill them. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that for a `DefaultAllGatherLayout` it calls only `copy_in`, which a subclass can override, and copies out with its `output_fn` directly. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 185 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 96475c2
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 8, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout whose output needs a specific collective names that comm's type as `comm_type`. The comm is installed with `set_custom_all_gather`, before the layout, and FSDP passes it each call's layout metadata as `output_metadata` (`None` for a call with rank-major output), so the comm keeps no per-call state and one instance can serve any number of parameter groups. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject comms of other types, and replacing the layout keeps the installed comm. Only comms of a layout's `comm_type` receive `output_metadata`, so existing custom comms keep their signature. The comm setters work at any time, as on main, since comms keep no per-call state and own no outputs. `set_all_gather_layout` changes layouts only between iterations: it cannot replace a layout while an all-gather is pending or parameters are unsharded, nor after outputs view a custom layout's buffers, since only the layout that created those outputs can refill them. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that for a `DefaultAllGatherLayout` it calls only `copy_in`, which a subclass can override, and copies out with its `output_fn` directly. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 185 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 711aeaa
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 8, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout whose output needs a specific collective names that comm's type as `comm_type`. The comm is installed with `set_custom_all_gather`, before the layout, and FSDP passes it each call's layout metadata as `output_metadata` (`None` for a call with rank-major output), so the comm keeps no per-call state and one instance can serve any number of parameter groups. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject comms of other types, and replacing the layout keeps the installed comm. Only comms of a layout's `comm_type` receive `output_metadata`, so existing custom comms keep their signature. The comm setters work at any time, as on main, since comms keep no per-call state and own no outputs. `set_all_gather_layout` changes layouts only between iterations: it cannot replace a layout while an all-gather is pending or parameters are unsharded, nor after outputs view a custom layout's buffers, since only the layout that created those outputs can refill them. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns and the chosen layout's `finalize_outputs`, except that for a `DefaultAllGatherLayout` it calls only `copy_in`, which a subclass can override, and copies out with its `output_fn` directly. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 185 passed and 2 skipped; the other suites passed: extensions 20, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 711aeaa
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 9, 2026
## BC-breaking?

> Yes, for private FSDP internals only:
> - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails.
> - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`.
> - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead.
> - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`.

## Summary (human written only)

<!-- Author: add your own summary line here before marking this PR ready for review -->

## Agent details (if applicable)

> AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2).
>
> This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276.
>
> FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them.
>
> FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer.
>
> FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs.
>
> `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout whose output needs a specific collective names that comm's type as `comm_type`. The comm is installed with `set_custom_all_gather`, before the layout, and FSDP passes it each call's layout metadata as `output_metadata` (`None` for a call with rank-major output), so the comm keeps no per-call state and one instance can serve any number of parameter groups. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject comms of other types, and replacing the layout keeps the installed comm. Only comms of a layout's `comm_type` receive `output_metadata`, so existing custom comms keep their signature. The comm setters work at any time, as on main, since comms keep no per-call state and own no outputs. `set_all_gather_layout` changes layouts only between iterations: it cannot replace a layout while an all-gather is pending or parameters are unsharded, nor after outputs view a custom layout's buffers, since only the layout that created those outputs can refill them. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns. The chosen layout's `finalize_outputs` finishes a call that `prepare` returned metadata for; a call without metadata has rank-major output, which FSDP copies out with that layout's `output_fn` (`None`, as on `AllGatherLayout`, for FSDP's default copy-out). FSDP thus dispatches on the contract's metadata, not on the layout's type, and a `DefaultAllGatherLayout` subclass can override `copy_in`. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none.
>
> This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper.
>
> Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests.
>
> Test Plan (local build, B200 GPUs):
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context
> python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_compile.py
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 193 passed and 2 skipped; the other suites passed: extensions 23, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: cbb2c68
Pull-Request: #199726
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants