Repository navigation
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - Ready for human review:
Findings (1): Reviewed commit: 🔗 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 FailureAs of commit aabe67b with merge base 0e73fc6 ( 🟡 GREEN LIGHT - PR requires human review:
reason: 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. |
This was referenced Oct 7, 2026
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
This was referenced Nov 19, 2026
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Keep the original AG/RS preparation and copying as defaults.