Skip to content

[FSDP2] Separate collective copy preparation from execution - #200034

Closed
weifengpy wants to merge 25 commits into
gh/weifengpy/219/basefrom
gh/weifengpy/219/head
Closed

weifengpy wants to merge 25 commits into
gh/weifengpy/219/basefrom
gh/weifengpy/219/head

Conversation

@weifengpy

@weifengpy weifengpy commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Keep the original AG/RS preparation and copying as defaults.

AI-assisted implementation and summary prepared with Codex and Claude Code for the requested change above.

FSDP now prepares each collective copy separately from executing it, so the next PR can register native copies. To review, start with Note [All-gather output fn] and Note [Reduce-scatter input fn] in _fsdp_collectives.py and AllGatherInput in _fsdp_api.py, then read _AllGatherOutputLayout, _get_extension_all_gather_inputs and _get_all_gather_output_layouts in _fsdp_param.py, then foreach_all_gather_copy_out and foreach_reduce in _fsdp_collectives.py, then the tests.

For the all-gather, every parameter records a layout per payload: the size that fsdp_post_all_gather receives the output viewed as, and the number of rows over which the copy-out concatenates the ranks' chunks. That number is the product of the dims before the gather dim, the padded sharded parameter's for Tensor payloads, or 1 when a flat copy suffices, as for a single rank, an empty payload or a post-forward shard. foreach_all_gather_copy_out reads those layouts, allocates the outputs, and calls an all-gather output fn with plain tensors and sizes. For the reduce-scatter, foreach_reduce sizes the buffer from the padded sharded parameter sizes and calls a reduce-scatter input fn that returns the copy-in to run once the buffer is allocated. The two Notes document both contracts, and the callbacks stay plain Callables so their signatures can still change. 2.15 ships the private hooks that #197372 added with their earlier signatures. The callbacks keep those hooks' names, and FSDP passes their sizes and world size by keyword, so a callback written for the earlier signatures fails loudly rather than being ignored or misreading its arguments. The default callbacks keep the original split, rank reassembly and chunk-cat copies, and reassemble typed tensors also when the all-gather buffer holds bytes.

The two PRs below fix resharding to a smaller mesh after forward and make a size-1 shard mesh copy every extension payload, smaller ones of an unchanged dtype into a prefix. Here, post-forward shards get a flat layout, which replaces the flat copy that the post-forward fix adds to main's copy-out.

fsdp_pre_all_gather may now return AllGatherInput records that declare each payload's concatenation dim, independent of the parameter's shard dim. This PR keeps them in the private _fsdp_api module, and #197701 exports them from torch.distributed.fsdp.experimental. Their dim is required, since a default would silently gather differently from a plain tensor of a Shard(i>0) parameter, and may be any integer except a tensor. Their number, element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs. Tensor payloads are still flattened with view(-1) and passed viewed as (-1, *size[1:]), and may become uint8 byte views of their whole outputs or, for parameters with a single row, i.e. whose dims before the shard dim multiply to 1, such as Shard(0) ones, shrink after their first call, keeping nonzero trailing dims, and fill a prefix of their output. Those of other Shard(i>0) parameters are read as rows of the padded sharded parameter: with more than one shard rank, main required its element count, and they may now instead keep only its dims before the shard dim, e.g. packed uint8 rows or byte views from the first call, or be empty. FSDP checks the payloads before the collective and caches the result for up to four combinations of their kinds, dims, sizes and dtypes, so payloads that alternate between shapes, like MXFP8 tensors that send rowwise data in forward and columnwise data in backward, are not checked again on every all-gather.

Alternatives: FSDP doesn't detect payloads that move the shard dim to dim 0, as torchtitan's quantized tensors do, since a shape-based check would also reject reshapes that keep the rows, which main accepts; those payloads still come back permuted, as on main, until they return AllGatherInput(dim=0). Shard(i>0) Tensor payloads that keep only the leading dims are accepted rather than rejected because they are copied correctly and get the (-1, *size[1:]) view that main gives every Shard(i>0) Tensor payload. The copy-out checks each output's element count instead of catching the error of a mismatched view, which costs about 0.1 us per output but saves about 13 us per output of a shrunk payload. The layout cache empties when it fills, which bounds it for payloads whose sizes keep changing.

On CPU, measured with an out-of-tree A/B harness over 1000 to 3000 parameters, a Shard(0) copy-out costs about 0.15 to 0.3 us more per parameter than on main, also when the all-gather buffer holds bytes, while a Shard(1) copy-out costs about 5 to 8 us less, and the reduce-scatter about 1 to 1.5 us less. At 1000 parameters, extension inputs cost about 0.15 us more per parameter and all-gather with one payload and about 0.25 to 0.5 us with two, also when they alternate between shapes, but about 10 to 25 us more with the garbage collector on (5 to 9 us with it off) when their sizes change on every call or alternate among more than four combinations, which FSDP then checks again.

Release notes: the private FSDPParamGroup._all_gather_output_fn and _prepare_reduce_scatter_inputs callbacks take new signatures, and callbacks written for 2.15's raise a TypeError. Extension payloads that FSDP cannot copy now raise a ValueError that names the parameter before the collective:

  • a changed payload count, for which main raised a RuntimeError after the collective, or, on a size-1 shard mesh, an unnamed ValueError from zip;
  • a payload larger than on its first call, which main copied as wrong data with an out= resize warning, or, on a size-1 shard mesh, failed on in copy_;
  • a dtype change other than to uint8, for which main raised a RuntimeError after the collective in a uniform-dtype group, copied the bytes, wrongly if they grew or, for Shard(i>0) parameters with several rows, shrank, when the group gathered bytes, or, on a size-1 shard mesh, cast silently if its element count was unchanged, broadcast it if it had one element, and otherwise failed in copy_;
  • a uint8 payload smaller than its typed output, which main copied into a prefix of the output's bytes, or reassembled with ranks mixed up for Shard(i>0) parameters with several rows, with an out= resize warning, or, on a size-1 shard mesh, failed on in copy_; ROCm TransformerEngine sends one after a first all-gather outside fp8 autocast, and then computed with fp8 bytes in a typed weight;
  • Tensor payloads whose trailing dims cannot view their output, which main failed on, and, with more than one shard rank, nonempty Tensor payloads of Shard(i>0) parameters with several rows that are not uint8 payloads of typed outputs and have neither the padded sharded element count nor its dims before the shard dim, which main failed on after the collective on a first call and, on later calls, treated like the size and dtype changes above and below;
  • Tensor payloads that shrink of Shard(i>0) parameters with several rows, which main reassembled with ranks mixed up, or, on a size-1 shard mesh, copied into a prefix of their output.

Three of these break cases that main handled. When the group gathered bytes, main copied a payload whose dtype changed byte for byte if its bytes stayed the same, e.g. fp8 e4m3 to e5m2 next to fp32 scales or a typed payload after a byte view, and, for parameters with a single row, into a prefix with a resize warning if they shrank. Returning uint8 byte views of the whole outputs keeps those whose bytes stay the same working. On a size-1 shard mesh, main also cast a payload whose dtype changed to one other than uint8, but not its element count, into the first call's dtype, exactly when representable, and copied shrinking Tensor payloads of Shard(i>0) parameters with several rows into a prefix, which FSDP now rejects on every mesh since more shard ranks would mix up their rows. The padded-size check for unevenly sharded parameters now raises a ValueError instead of an AssertionError, and also runs on ranks without padding, so payloads that lack the padded size everywhere, e.g. flattened ones, fail on every rank. An extension that returns its unpadded local shard still passes on ranks whose shard needs no padding, which then hang, as before.

Fixed: payloads with a zero-size trailing dim, which failed in view(-1, 0) (since #122908) or, for Shard(i>0) parameters with more than one shard rank, in the rank reassembly, and now get an explicit leading size; Tensor payloads that shrink, of Shard(0) parameters and of Shard(i>0) ones with a single row, which main resized with a deprecation warning; and, with more than one shard rank, Tensor payloads of the latter without the padded sharded element count on their first call, which main failed on after the collective and which are now copied flat.

Test Plan:

python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardCollectiveOps -k TestFullyShardCollectiveCopies -k TestFullyShardDefaultAllGatherOutputFn
python test/distributed/_composable/fsdp/test_fully_shard_memory.py -k test_unsharded_grads_freed_after_copy_in
python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k test_reduce_dtype -k test_grad_dtype -k test_compute_dtype
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 test_dp_state_dict_save_load

All pass on B200s. Before this PR, test_all_gather_extension_shard_dim1_byte_views fails for byte views from the first call, and test_all_gather_extension_smaller_payload and test_all_gather_extension_uneven_sharding fail because the errors they expect are new.

Each new check also fails when the code it covers is removed or broken, as checked with mutants: the prefix slice, the skip of empty all-gathers, the layout cache's key and bound, del copy_in, the keyword-only sizes, the payload and dim checks, the rows rule's restriction to several ranks and rows, the replicate() mesh guard, the flat post-forward layout, the empty layouts of an extension without payloads and the restriction of byte buffers to uint8.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

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

✅ AUTOMATED REVIEW - Ready for human review:

This PR rewrites the FSDP2 all-gather copy-out and reduce-scatter copy-in
callbacks to take keyword-only sizes. It also adds AllGatherInput records with
validated, cached output layouts. Sub-agent review found the copy-out,
reassembly, buffer sizing and caller updates consistent with the old behavior,
and the new tests cover the new paths and the error cases. No maintainer
comments are pending, and the one remaining issue is minor.

Findings (1):

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_common.py:129
_get_dim0_padded_size is now unused anywhere in the tree, and this comment keeps
it as a BC shim for hypothetical external callers of a private helper. Delete it
instead of keeping dead code.

Reviewed commit: aabe67b

Review run

🔗 Helpful Links

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

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

❌ 1 Cancelled Job, 1 Unrelated Failure

As of commit aabe67b with merge base 0e73fc6 (image):

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • Not in any trivial class: rewrites the FSDP2 all-gather copy-out and reduce-scatter copy-in in _fsdp_collectives.py
    • Adds _get_all_gather_output_layouts and a 4-entry layout cache in _fsdp_param.py, new validation logic a reviewer should check
  • User-facing behavior
    • New AllGatherInput record in _fsdp_api.py changes what fsdp_pre_all_gather extensions may return
    • Uneven-shard padding check now raises ValueError instead of AssertionError and runs on every rank
    • Some payloads that used to work now raise ValueError, e.g. dtype changes in a byte-gathering group
  • Socialization
    • _all_gather_output_fn and _prepare_reduce_scatter_inputs callbacks get new keyword-only signatures, so 2.15-style callbacks raise TypeError
    • Reduce-scatter buffer is now sized from padded_sharded_param_size instead of _get_dim0_padded_size, which is a memory and layout change in foreach_reduce

reason: not_trivial
Reviewed commit: aabe67b

Inference job

🐛 Report a wrong verdict

CANCELLED JOB - The following job was cancelled. Please retry:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

[ghstack-poisoned]
@weifengpy weifengpy changed the title [FSDP2] Add native collective copy ops [FSDP2] Separate collective copy preparation from execution Oct 7, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
pytorchmergebot pushed a commit that referenced this pull request Oct 20, 2026
## BC-breaking?

> No: adds an experimental setter and module; FSDP's default copies are unchanged.

## Summary (human written only)

better perf for Shard(1)/Shard(2) to unblock torchtitan EFSDP sharding

## Agent details (if applicable)

> AI-assisted implementation and summary prepared with Codex and Claude Code.
>
> Add an `FSDPModule.set_reduce_scatter_input_fn` setter, and call the native all-gather copy-out (`fsdp::_all_gather_copy_out_`, #197204) and reduce-scatter copy-in (`fsdp::chunk_cat_mixed_dtype` with `num_leading_dims`, #200179) through `torch.distributed.fsdp.experimental`, which exports `AllGatherInput`, `all_gather_output_fn_with_native_copy` and `reduce_scatter_input_fn_with_native_copy`. The original intermediate copies remain the defaults. The all-gather copy-out has no setter here: #199726 installs it through `set_all_gather_layout` as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`; until then, the tests here install it through the private `FSDPParamGroup._all_gather_output_fn` hook.
>
> The all-gather op copies within one dtype, so its callback copies mixed-dtype groups as bytes, and it requires exact output sizes, so the callback uses the default copy-out for groups with a Tensor payload smaller than its cached output. The reduce-scatter copy-in takes mixed gradient dtypes, such as a deferred bf16 Shard(1) weight gradient next to an fp32 norm gradient, so it needs no dtype fallback; noncontiguous gradients sharded on a nonzero dim still use the chunk-and-concatenate reorder.
>
> Native copying writes contiguous tensors without intermediate buffers and benefits wide CUDA tensors with small outer_size, such as Shard(1) over [2,F,D]. Its CPU time, GPU time and metadata memory grow with a group's total outer size, and strided collective buffers take a slower path, so the documentation recommends benchmarking the target workload.
>
> Test Plan:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k test_strided_allocation -k test_reduce_scatter_input_fn_setter -k TestFullyShardNativeReduceScatterInputFn
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py -k test_all_gather_input_layouts -k test_all_gather_extension_smaller_payload
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k test_reduce_dtype -k test_native_copy_in_mixed_grad_dtypes
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference
> python test/test_public_bindings.py -k test_correct_module_names
> ```
> All pass on this revision. `test_native_copy_in_mixed_grad_dtypes` fails if the callback falls back to the default copy-in for mixed gradient dtypes, `test_strided_allocation` if a copy reorders its input, `test_reduce_scatter_input_fn_setter` if the setter ignores `recurse` or `None`, `test_all_gather_input_layouts` if the native all-gather copy falls back to the default one, and `test_all_gather_extension_smaller_payload` if it has no fallback for smaller payloads.
>
> Measured on one B200 with world-size-8 layouts (copies only, native time / default time): a [2, 8192, 4096] Shard(1) group copies out in 0.53x GPU and 0.41x CPU time and copies in in 0.38 to 0.45x GPU and 0.67 to 0.70x CPU time; Shard(1) experts [2/8, 1408, 2048] x3 copy out in 0.36 to 0.51x GPU time; native copies of contiguous tensors also skip the intermediate buffers, lowering a Shard(1)/Shard(2) group's peak memory by about 24 to 830 MB. Groups with many rows before the shard dim are slower: Shard(2) experts copy out in 1.7 to 1.8x GPU time and up to 5.6x CPU time, and a Llama-8B block's Shard(1) parameters (outer size 43010) copy out in 0.74 to 0.78x GPU but 3.2 to 4.4x CPU time, which is why the documentation recommends benchmarking.

Pull Request resolved: #197701
Approved by: https://github.com/anshul-si
ghstack dependencies: #200985, #200986, #200034
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
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: 17bd5eb
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: 17bd5eb
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: 90e19f6
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 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` rejects 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. `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` work only with `DefaultAllGatherLayout`, whose in-place copy-in puts the input in the buffer they allocate, and `set_all_gather_layout` rejects other layouts on a group that uses them. Otherwise 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 passed on the previous 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. This revision, which limits symmetric memory and process-group allocation to `DefaultAllGatherLayout`, has not been re-run yet.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: ebb2272
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 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 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, 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 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 and limits the comm setters to `DefaultAllGatherLayout`, has not been re-run yet.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 0720260
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 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 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, 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 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 and limits the comm setters to `DefaultAllGatherLayout`, has not been re-run yet.

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: cb817e1
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 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):
> ```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 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]>
ghstack-source-id: 488b1e7
Pull-Request: #199726
weifengpy added a commit that referenced this pull request Nov 11, 2026
…fers (copy of #199726, AI-assisted)

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

> A copy of #199726 at its 2026-11-08 revision (ghstack orig fca5398), the base of the FlexShard stack above, so that the stack does not depend on #199726's later revisions or its review state. Not for review or landing: review and land #199726. The rest of this description is #199726's at that revision.
>
> 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: 439b0de
Pull-Request: #204282
majing921201 pushed a commit to majing921201/pytorch that referenced this pull request Nov 16, 2026
## BC-breaking?

> No: configurations that worked on main give the same results, and those that failed now work or raise a named `NotImplementedError`.

## Summary (human written only)

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

## Agent details (if applicable)

> AI-assisted implementation and summary prepared with Claude Code, split out of pytorch#200034 at the author's request.
>
> With `reshard_after_forward=int`, FSDP reshards parameters after forward to flat chunks of their unsharded data over a smaller mesh, and all-gathers those post-forward shards in backward. Main reassembled that all-gather like that of Shard(i) chunks: `_reassemble_all_gather_outputs` took their 1-D size as the padded sharded size and indexed it at the shard dim, so all-gathering the post-forward shards of Shard(i>0) parameters has raised an `IndexError` since pytorch#137496. Post-forward shards are now copied flat, which is their layout. That fixes Shard(i>0) parameters that are empty or whose dim 0 is divisible by the post-forward mesh size. For the others, the flat chunks don't match the dim-0 post-forward shards, and main failed in `as_strided` on some ranks only, after resharding the parameters before them. Supporting them would need post-forward shards padded on dim 0 or chunked along the shard dim, which this PR leaves for later since main never supported them either.
>
> FSDP therefore now checks every parameter of a group before resharding any, where main raised partway through the group, and raises a `NotImplementedError` that names the parameter for:
> - those Shard(i>0) parameters;
> - DTensor parameters, where main raised an unnamed one;
> - all-gather extensions with zero or several payloads, where main raised an `AssertionError`;
> - all-gather extensions whose output cannot back the post-forward parameter, where main raised a `RuntimeError`: each post-forward rank's chunk of the output must hold the largest post-forward shard and, for a parameter that requires gradients, have a floating or complex dtype.
>
> Single-payload extensions whose output can back the post-forward parameter reshard as on main, which works as long as their post-forward shards are never all-gathered, e.g. with `set_unshard_in_backward(False)`; all-gathering them still raises, now naming the parameter. An extension with zero payloads that comes first in its group still fails earlier with an `IndexError`, as on main. On CPU, the check costs about 0.3 to 0.4 us per parameter, and about 1 us per extension parameter, in every forward that reshards to a smaller mesh, since checking only once would need state to invalidate.
>
> Post-forward shards are also all-gathered over the mesh they were resharded to, not the group's current `post_forward_mesh_info`: after a forward without backward, `set_reshard_after_forward(True)` made main gather them over the whole shard mesh, which gave Shard(0) parameters the right data only by coincidence and with an out= resize warning, and `set_reshard_after_forward(False)` made it fail an assertion. FSDP reads that mesh from the parameters' `post_forward_mesh_info`, which `set_reshard_after_forward` leaves unchanged (it updates only the group's), so code that overrides `FSDPParamGroup._to_sharded_post_forward` but reshards through `FSDPParam.to_sharded_post_forward` gets it too. Recording the mesh on the group at reshard time would miss such overrides, which bypass that state, and resharding groups that hold post-forward shards to the full mesh in `set_reshard_after_forward` would leave their post-forward shard data allocated, since `to_sharded` does not free it.
>
> `_test_reduce_dtype_fp32_reduce` no longer returns early for `use_shard_placement_fn` (largest-dim) runs at world size > 2, a skip that pytorch#137496 added for every `reshard_after_forward`, not only an int, since bools are ints. Its runs with an int `reshard_after_forward` reshard Shard(1) parameters to a smaller mesh after forward, so `test_reduce_dtype` now also covers this fix; it takes about 10 s longer on 4 GPUs.
>
> Test Plan:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardCollectiveCopies -k TestFullyShardCollectiveOps
> 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
> ```
> All pass on B200s. On main, `test_post_forward_shard_dim1_parity` fails with the `IndexError`, `test_post_forward_shard_dim1_needs_divisible_dim0` fails in `as_strided`, `test_post_forward_shards_keep_their_mesh` fails because the all-gather uses the whole shard mesh, `test_post_forward_reshard_dtensor` and `test_all_gather_extension_post_forward_reshard` fail on unnamed errors, and `test_reduce_dtype` fails with the `IndexError`.
Pull Request resolved: pytorch#200985
Approved by: https://github.com/anshul-si
majing921201 pushed a commit to majing921201/pytorch that referenced this pull request Nov 16, 2026
pytorch#200986)

## BC-breaking?

> No, except on a size-1 shard mesh, where main copied only the first payload: a payload count that changes after the first call with payloads, or a later payload that grows or fails in `copy_` as described below, now raises, and a payload of an unchanged dtype that shrinks to one element fills one element of its output, where main broadcast or dropped it.

## Summary (human written only)

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

## Agent details (if applicable)

> AI-assisted implementation and summary prepared with Claude Code, split out of pytorch#200034 at the author's request.
>
> A size-1 shard mesh, e.g. HSDP with one rank per shard group, and `replicate_with_fsdp.replicate()` skip the all-gather and copy each parameter's all-gather inputs into its outputs directly. Since pytorch#160135 that copy has read only `all_gather_inputs[0]` into a single output, so the `fsdp_post_all_gather` of an all-gather extension with several payloads received only the first one, and extensions with zero payloads raised an `IndexError`. It now copies every payload: uint8 payloads into all the bytes of outputs of other dtypes, as main already did for the first payload, and payloads of an unchanged dtype that are smaller than on their first call into a prefix of their output, where main raised in `copy_` or, for a one-element payload, broadcast it. A non-uint8 payload whose dtype and size both change, or a uint8 payload smaller than its typed output, still fails in `copy_`, as on main, unless it has one element, which is broadcast; filling a byte prefix for the latter, as the multi-rank path does with a resize warning, would silently put fp8 bytes into the typed weight of ROCm TransformerEngine, which sends one after a first all-gather outside fp8 autocast. Copying bytes whenever the dtype changes would accept such payloads too, but would silently reinterpret values that main casts or rejects. A payload count that differs from that of the first call with payloads raises an error. The version-counter and inference-mode handling now applies to every output.
>
> Test Plan:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardCollectiveCopies -k TestFullyShardCollectiveOps
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py -k TestFullyShardWorldSize1
> python test/distributed/_composable/test_replicate_training.py
> ```
> All pass on B200s. On main, `test_all_gather_extension_smaller_payload` fails with `ValueError: not enough values to unpack (expected 2, got 1)` because only the first payload gets an output, and `test_all_gather_extension_single_rank_no_payloads` fails with the `IndexError`.
Pull Request resolved: pytorch#200986
Approved by: https://github.com/anshul-si
ghstack dependencies: pytorch#200985
pytorchmergebot pushed a commit that referenced this pull request Nov 23, 2026
…99726)

## 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 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):
> ```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 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]>
Pull Request resolved: #199726
Approved by: https://github.com/anshul-si
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100-symm-mem ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (fsdp) release notes category release notes: distributed (fsdp2) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants