Skip to content

[FSDP2] Add an all-gather layout contract with FSDP-owned buffers - #199726

Open
weifengpy wants to merge 44 commits into
gh/weifengpy/212/basefrom
gh/weifengpy/212/head
Open

weifengpy wants to merge 44 commits into
gh/weifengpy/212/basefrom
gh/weifengpy/212/head

Conversation

@weifengpy

@weifengpy weifengpy commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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 [FSDP2] Separate collective copy preparation from execution #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)

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 rejected copy-out raises without cleaning up, so the program fails there; reset_iter_state() recovers, after which another layout can be installed, since FSDP adopts nothing from a rejected first result.

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 carries that comm as its comm, which allocates and runs all of the layout's all-gathers. 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; a custom layout without a comm runs FSDP's default all-gather. Only a layout's comm receives output_metadata, so existing custom comms keep their signature. The comms that set_custom_all_gather, set_symm_mem_for_comm and set_allocate_memory_from_process_group_for_comm install work only with DefaultAllGatherLayout: on main every comm is called with its input packed into the output it allocated, which a custom layout's copy-in does not do, and FSDP cannot tell whether a custom comm depends on that. Those setters raise under a custom layout, and set_all_gather_layout rejects a custom layout on a group that uses one of their comms. Letting set_custom_all_gather provide a custom layout's collective instead would need the comm installed before the layout and a cross-check between the two setters. Under the default layout the comm setters work at any time, as on main, since comms 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, rejected refills, recovery with reset_iter_state() 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):

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 passed on an earlier revision, before the comm-setter changes, 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. This revision, which moves a custom layout's comm onto the layout, limits the comm setters to DefaultAllGatherLayout and drops the cleanup after a rejected copy-out, has not been re-run yet.

Co-authored-by: wuyl1 [email protected]
Co-authored-by: inkcherry [email protected]

@pytorch-bot

pytorch-bot Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

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

🟡 AUTOMATED REVIEW - OUTDATED (earlier commit) - Changes requested:

The PR adds an experimental FSDP2 all-gather layout abstraction with FSDP-owned
persistent buffers, plus thorough tests and docs. One confirmed correctness bug
blocks approval: first-unshard detection looks only at the group's first
parameter, so a zero-payload extension in that position makes every later
custom-layout unshard re-adopt its buffers, which either raises an error or
leaves parameters viewing buffers that were never refilled. The remaining
findings are minor consistency and error-path issues.

Findings (4):

[major] torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py:599
`first_unshard = not fsdp_params[0].all_gather_outputs` checks only the first
param. Zero-payload extensions are allowed, so if the first param's
`fsdp_pre_all_gather` returns `()`, its outputs stay `[]` after adoption. Every
later custom-layout unshard then gets `buffers=[]` and is re-adopted instead of
refilled. Delegating layouts raise a ValueError. Layouts that allocate fresh
buffers leave non-extension params' `_unsharded_param` viewing the old,
never-refilled buffers (silent wrong data) and keep them alive. Derive the flag
from the whole group, e.g. `not any(p.all_gather_outputs fo

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py:576
`except ValueError` also catches refill failures on later unshards, not only a
rejected first unshard as the comment says. The buffers were already
re-allocated by `persistent_buffers.alloc()`, the group stays SHARDED, and
`_to_sharded` returns early, so the memory stays allocated until the next
successful reshard. Non-ValueError failures leave `_all_gather_result` set,
which blocks installing another layout.

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py:401
`set_symm_mem` and `set_allocate_memory_from_process_group` reject only layouts
bound to a comm. Unlike `set_custom_all_gather`, they don't call
`_check_all_gather_replaceable`, so they can still swap the comm under a custom
layout after its outputs were adopted or while an all-gather is pending.

[minor] torch/distributed/fsdp/_fully_shard/_fully_shard.py:971
The one-group rule for comm-bound layouts is only enforced within a single call.
Installing the same stateful bound layout on two modules with two
`recurse=False` calls is accepted silently, although the layout docstring says
overlapping all-gathers would corrupt its per-call state.

Reviewed commit: 4e75137 (NOT the current head 6aaaafb)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ You can merge normally! (16 Unrelated Failures)

As of commit 6aaaafb with merge base 4865066 (image):

🟡 GREEN LIGHT - PR was reverted - re-landing requires human review:

Green Light will not review this PR again, on this or any later commit; re-landing it needs a human approval.

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following jobs failed, but the AI CI Advisor judged the failures not to be evidence against this change:

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Oct 5, 2026
weifengpy added a commit that referenced this pull request Oct 5, 2026
…t hook and add an input hook

> 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 the stack's tensor-only hooks as the all-gather contract and extends them to cover what #188276's MORI SDMA backend needs. `AllGatherOutputFn` may now return one tensor per output instead of writing into `outputs`. When the comm sets `AllGather.reuses_output_storage` and the group is eligible (every payload has outer size 1 and the buffer dtype, and no parameter is post-forward, a DTensor, an extension, or under compiled autograd), FSDP adopts the returned views as the parameters' all-gather outputs on their first all-gather, so later gathers are zero-copy. Otherwise FSDP copies the returned tensors into its own outputs. A new tensor-only `AllGatherInputFn`, set with `FSDPModule.set_all_gather_input_fn`, packs the collective input; it reworks #197500 without its `AllGatherInput` name, which #197204 now uses for payload records. From #188276 this ports `AllGather.release_output()` and its call sites, the output ownership flag, honoring the outputs' storage offset in the unsharded parameters, the version-counter guards, and holding the collective input until the copy-out. It drops the `AllGatherLayout` object model.
>
> A zero-copy backend is three separately installed pieces (comm, input function, output function) that agree on the layout through the backend's own state, and adopted storage stays allocated across reshard, as in #188276. On the default path, `_to_sharded` now discards a pending all-gather and `_unsharded_param` is always an attribute. Review the contracts and adoption in `_fsdp_collectives.py` first, then ownership and release in `_fsdp_param.py` and `_fsdp_param_group.py`, then the setters in `_fully_shard.py`. The tests port #188276's pure-PyTorch parameter-contiguous backend and its end-to-end parity tests onto the hooks.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/test_public_bindings.py -k test_correct_module_names
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -v
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -v -k test_train_parity_single_group -k test_inference -k test_train_parity_multi_group
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py -v
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -v -k test_reduce_dtype
> ```
> All pass except `test_fully_shard_alloc_from_pg`, which fails the same way on the parent commit.

ghstack-source-id: 68dc861
Pull-Request: #199720
weifengpy added a commit that referenced this pull request Oct 5, 2026
…ayout

> 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 adopts #188276's `AllGatherLayout` (prepare, copy-in and finalize, plus `AllGather.release_output()` and backend-owned outputs) as the single all-gather contract, ported onto the stack. The stack's copy-out becomes the default layout's finalize step: `DefaultAllGatherLayout(output_fn=...)` runs #197204's copy-out with a configurable `AllGatherOutputFn`, and the native copy is `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. An experimental `FSDPModule.set_all_gather_layout` replaces #197701's `set_all_gather_output_fn`, and `set_custom_all_gather` installs a comm's own layout, so a MORI-style backend is still one call. #197204's per-payload `outer_sizes` replace #188276's per-parameter `shard_dim` and `padded_sharded_size` metadata, which also avoids #188276's post-forward Shard(i>0) `IndexError`. The default layout skips the eligibility checks and per-parameter metadata.
>
> Selecting both a custom comm and the native layout is order-dependent because `set_custom_all_gather` resets the layout, the native copy does not compose with a custom layout's rank-major fallback, and backend-owned storage keeps #188276's memory model. On the default path, `_to_sharded` now discards a pending all-gather. Review the contract and default finalize in `_all_gather_layout.py` first, then `_fsdp_collectives.py`, `_fsdp_param.py` and `_fsdp_param_group.py`, then `_fully_shard.py`. The tests port #188276's layout tests and switch #197701's native-copy tests to the layout API.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/test_public_bindings.py -k test_correct_module_names
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k NativeCollectiveCopy -k strided_allocation
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k test_reduce_dtype
> 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
> ```
> All pass.

ghstack-source-id: e8840af
Pull-Request: #199721
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.
>
> 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 and move `release_output` to it. Review the ownership rules and `AllGatherOutputs` in `_all_gather_layout.py` first, then buffer re-allocation in `_fsdp_collectives.py` and the frees in `_fsdp_param_group.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, and cover the rejected ownership cases.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/test_public_bindings.py -k test_correct_module_names
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k NativeCollectiveCopy -k strided_allocation
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k test_reduce_dtype
> 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
> ```
> All pass.

ghstack-source-id: 03a0194
Pull-Request: #199726
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. The default-path changes this draft inherited from #188276 are in the previous PR in the stack: `_to_sharded` discards a pending post-forward all-gather, `_unsharded_param` starts as `None`, and `init_unsharded_param` honors the output's storage offset.
>
> 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 runtime from about 27 minutes to about 6 minutes (1652 s to 353 s for its 77 tests); the compiled case resets dynamo itself because reused workers skip `setUp` and `tearDown`.
>
> Test Plan (local build, 4 B200 GPUs). On the final 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
> ```
> The broader suites ran on the revision before the test conversion, whose library code differs from the final one only in comments, an error message and an always-true condition:
> ```bash
> python test/test_public_bindings.py -k test_correct_module_names
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k NativeCollectiveCopy -k strided_allocation
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardAllGatherLayoutSetters
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k test_unused_backward_prefetch_with_post_forward_mesh
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k test_reduce_dtype
> ```
> All of these pass. The training subset (`test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_train_parity_multi_group`) passed on the previous PR alone and on this draft before the split, and was not rerun after it.

ghstack-source-id: 6ad27fe
Pull-Request: #199726
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 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 weifengpy changed the title [no-ci] [FSDP2] Draft: all-gather contract option 3, AllGatherLayout with FSDP-owned buffers [no-ci] [FSDP2] Add an all-gather layout contract with FSDP-owned buffers Oct 6, 2026
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 draft prepared with Claude Code for discussion on #188276.
>
> On top of the previous PR's clone of #188276, this shows the changes we suggest. The result is the all-gather contract we'd like to land, option 3 of #199720, #199721 and #199726, with #188276's backend-owned zero copy as an explicit opt-in.
>
> - FSDP owns the storage behind the parameters' all-gather outputs by default, 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 before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving memory with custom layouts.
> - 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.layout` and `AllGather.reuses_output_storage` are 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. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While it 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 stack's default code, so the default path builds no per-call layout metadata.
> - `FSDPParam._unsharded_param` stays lazily created, because out-of-tree patches of `post_backward` check it with `hasattr`.
> - Separately from the contract, `test_compiled_backward_eligibility` sets multiprocessing's start method to spawn before compiling. Compiling otherwise fixes it to fork after CUDA is initialized, so every `FSDPTestContinuous` class later in the file fails to start its workers when the file runs in one process.
>
> In MORI's adapter at ROCm/mori@7f40b1bd, `_MoriSdmaAllGatherLayout` would subclass `BackendOwnedAllGatherLayout`, set `comm`, and implement `release_output()` with the logic now in `MoriSdmaAllGather.release_output`. Its `finalize_outputs` would read the metadata argument and return `AllGatherOutputs(views)`, and users would install it with `module.set_all_gather_layout(layout)` instead of `set_custom_all_gather(comm)`.
>
> Review `_all_gather_layout.py` first, then `_fsdp_collectives.py`, `_fsdp_param_group.py` and `_fully_shard.py`. The tests add an FSDP-owned parameter-contiguous layout that checks its buffer is freed after reshard unless storage is kept and refilled with one copy. They keep #188276's backend-owned tests on the opt-in, cover the rejected ownership cases and the setter rules, and run `TestFullyShardLayoutParity` on `FSDPTestContinuous`.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/test_public_bindings.py -k test_correct_module_names
> 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
> ```
> In the full comm file, 197 of 200 tests pass and 2 are skipped, as on #197701. `test_fully_shard_alloc_from_pg` fails, as it also does on #197701 on this machine, where NCCL registers a buffer before process-group allocation is enabled. The other suites pass: public bindings 1, extensions 9, mixed precision 26, training 7, state dict 1, memory 7.


ghstack-source-id: 3704a5b
Pull-Request: #199873
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
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 draft prepared with Claude Code for discussion on #188276.
>
> On top of the previous PR's clone of #188276, this shows the changes we suggest. The result is the all-gather contract we'd like to land, option 3 of #199720, #199721 and #199726, with #188276's backend-owned zero copy as an explicit opt-in.
>
> - FSDP owns the storage behind the parameters' all-gather outputs by default, 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 before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving memory with custom layouts.
> - 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.layout` and `AllGather.reuses_output_storage` are 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. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While it 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 stack's default code, so the default path builds no per-call layout metadata.
> - `FSDPParam._unsharded_param` stays lazily created, because out-of-tree patches of `post_backward` check it with `hasattr`.
> - Separately from the contract, `test_compiled_backward_eligibility` sets multiprocessing's start method to spawn before compiling. Compiling otherwise fixes it to fork after CUDA is initialized, so every `FSDPTestContinuous` class later in the file fails to start its workers when the file runs in one process.
>
> In MORI's adapter at ROCm/mori@7f40b1bd, `_MoriSdmaAllGatherLayout` would subclass `BackendOwnedAllGatherLayout`, set `comm`, and implement `release_output()` with the logic now in `MoriSdmaAllGather.release_output`. Its `finalize_outputs` would read the metadata argument and return `AllGatherOutputs(views)`, and users would install it with `module.set_all_gather_layout(layout)` instead of `set_custom_all_gather(comm)`.
>
> Review `_all_gather_layout.py` first, then `_fsdp_collectives.py`, `_fsdp_param_group.py` and `_fully_shard.py`. The tests add an FSDP-owned parameter-contiguous layout that checks its buffer is freed after reshard unless storage is kept and refilled with one copy. They keep #188276's backend-owned tests on the opt-in, cover the rejected ownership cases and the setter rules, and run `TestFullyShardLayoutParity` on `FSDPTestContinuous`.
>
> Test Plan (local build, 4 B200 GPUs):
> ```bash
> python test/test_public_bindings.py -k test_correct_module_names
> 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
> ```
> In the full comm file, 197 of 200 tests pass and 2 are skipped, as on #197701. `test_fully_shard_alloc_from_pg` fails, as it also does on #197701 on this machine, where NCCL registers a buffer before process-group allocation is enabled. The other suites pass: public bindings 1, extensions 9, mixed precision 26, training 7, state dict 1, memory 7.


ghstack-source-id: 7839cc6
Pull-Request: #199873
@weifengpy weifengpy changed the title [no-ci] [FSDP2] Add an all-gather layout contract with FSDP-owned buffers [FSDP2] Add an all-gather layout contract with FSDP-owned buffers Oct 6, 2026
@weifengpy
weifengpy force-pushed the gh/weifengpy/212/head branch from 5fd0f4b to 815c634 Compare October 6, 2026 06:58
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
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@jeffdaily

Copy link
Copy Markdown
Collaborator

My agent came up with this analysis, but I've read and approved it.

@weifengpy, re-ran on MI300X (gfx942, ROCm 10.1, RCCL 2.30.7) at head 6aaaafb, built from source, 4 GPUs. With the container's 10 GB /dev/shm: test_fully_shard_comm.py 193 passed / 3 skipped, test_fully_shard_extensions.py 23 passed, test_fully_shard_mixed_precision.py 32 passed, test_fully_shard_training.py 61 passed / 8 skipped / 1 failed. The failure is test_train_parity_multi_group: RCCL split_group cannot create its /dev/shm segment (ENOSPC, /dev/shm full). With a private 64 GB /dev/shm all four files pass (training 62 passed / 8 skipped), and that test peaks at 16.0 GB of /dev/shm, since the split communicators' segments are held until process exit. test_fully_shard_mixed_precision.py also peaks at about 10.1 GB. So the multi-group test needs more than 10 GB on this head too; it is an environment limit, not a regression from this PR. All skips are pre-existing; the PR adds no ROCm skips.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@weifengpy CI is green at 6aaaafb and the ROCm results above still hold (the MoRI adapter is validated against this head). Anything left before landing? AMD's #188276 follow-up is waiting on this one.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@weifengpy @anshul-si any objection to landing this as-is at 6aaaafb? It's approved, green and conflict-free, and the ROCm validation above covers the MI300X check from Nov 5. If neither of you objects, I'll merge it so the #188276 follow-up can move.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Nov 23, 2026

Copy link
Copy Markdown

This PR has pending changes requested. Please address the comments and update the PR before merging.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 mandatory check(s) are pending/not yet run. The first few are:

  • EasyCLA

Dig deeper by viewing the pending checks on hud

Details for Dev Infra team

Raised by workflow job

Failing merge rule: Core Maintainers

@jeffdaily

Copy link
Copy Markdown
Collaborator

/easycla

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable)

Details for Dev Infra team

Raised by workflow job

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@weifengpy

Copy link
Copy Markdown
Contributor Author

@jeffdaily @wuyl1 this break internal so i have to revert for now. totally understand the need for MORI to build on top of it. This contract is pretty fundamental in FSDP2 & FlexShard unification

I will spend time this week to investigate internal breakage and unblock this

@izaitsevfb

Copy link
Copy Markdown
Contributor

✴️ iz2: Reverting this PR because it breaks Meta-internal tests that OSS CI does not run. The author will follow up with a fix and can reland it.
@pytorchbot revert -m "Breaks Meta-internal tests that OSS CI does not run" -c ghfirst

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@weifengpy your PR has been successfully reverted.

@wuyl1

wuyl1 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

@jeffdaily @wuyl1 this break internal so i have to revert for now. totally understand the need for MORI to build on top of it. This contract is pretty fundamental in FSDP2 & FlexShard unification

I will spend time this week to investigate internal breakage and unblock this

@weifengpy Thanks for looking into this. Understood on the revert. We’re happy to help validate the update on ROCm with the MoRI adapter.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@weifengpy Could you share what broke internally, i.e. the failing test names and the error message, with internal names removed? The PR intentionally changes private FSDP2 signatures (foreach_all_gather gains a positional layout, foreach_all_gather_copy_out drops all_gather_output_fn=, and FSDPParamGroup._all_gather_output_fn now raises), so I suspect internal code that patches or calls those. If that is it, we can prepare a reland that keeps the old private signatures working (keyword-only layout with a default, all_gather_output_fn= mapped to DefaultAllGatherLayout, and _all_gather_output_fn kept with a deprecation warning), validate it on ROCm with the MoRI adapter, and you can import it to run the internal tests before it relands.

This branch was previously deployed

1 inactive deployment
bedrock — 6aaaafb1 Deployed Nov 24, 2026 by pytorchmergebot via analyze #40775
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ci-no-td Do not run TD on this PR ciflow/inductor ciflow/pull ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes in progress PR is being worked on by the author, until the automated review accepts it Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (fsdp) release notes category Reverted skip-pr-sanity-checks triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants