Skip to content

[FSDP2] Add backend-owned all-gather outputs on the layout contract - #188276

Open
wuyl1 wants to merge 5 commits into
pytorch:mainfrom
wuyl1:sdma_fsdp2
Open

wuyl1 wants to merge 5 commits into
pytorch:mainfrom
wuyl1:sdma_fsdp2

Conversation

@wuyl1

@wuyl1 wuyl1 commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

cc: @weifengpy @jeffdaily

Summary

  • This builds on pytorch/pytorch#199726 and follows the design discussed in pytorch/pytorch#186601.
  • Extend the vendor-neutral FSDP2 all-gather layout contract to support backend-owned output storage, as needed by the opt-in MORI SDMA backend.
  • Allow eligible FSDP parameter groups to adopt parameter-contiguous views into backend-owned output storage, avoiding the final copy when those views remain stable.
  • Keep default FSDP2 behavior unchanged unless users explicitly install a custom all-gather layout.
  • Keep the MORI adapter and runtime dependency out of PyTorch; the adapter lives in ROCm/MORI.

For eligible groups, MORI SDMA writes directly into its registered output storage in a parameter-contiguous layout:

[param0 rank0 rank1 ...][param1 rank0 rank1 ...]

FSDP can then construct unsharded parameters as views into the backend-owned output, avoiding rank-major reassembly and the final staging-to-parameter copy when those views remain stable.

Changes

  • Extend the layout contract introduced in [FSDP2] Add an all-gather layout contract with FSDP-owned buffers #199726 with BackendOwnedAllGatherLayout, allowing parameter outputs to reference backend-owned storage without returning FSDP-owned persistent buffers.
  • Preserve adopted output tensors, Parameter identity, saved aliases, and autograd version counters across input packing, collective completion, and output refill.
  • Avoid copy-out when backend output views remain stable. When views move, refill the adopted outputs and clone overlapping sources before any destination is overwritten.
  • Add an idempotent release_output() notification after reshard and on discarded or failed gather paths. Wait for discarded collective work before releasing its output.
  • Bind each stateful layout to one FSDP parameter group using a weak reference. Validate recursive installation before modifying any group, and reject replacement while pending gathers, unsharded parameters, or adopted backend aliases are live.
  • Preserve rank-major copy-out fallback for ineligible groups, including compiled-autograd, DTensor parameters, tensor-subclass all-gather hooks, nonzero shard dimensions, incompatible dtype/payload layouts, and post-forward subgroup gathers.
  • Preserve the exact default layout's fast path, avoiding custom-layout eligibility checks and per-parameter metadata construction.
  • Add regression coverage for backend-owned outputs, moved-view refill, saved-tensor version counters, release ordering, discarded prefetch, fallback, eligibility, and layout ownership, along with training correctness checks.

The companion MORI change provides MoriSdmaAllGather on the updated layout contract, with backend-owned parameter views and an optional shared output pool. The adapter records consumer events on release and uses cross-rank readiness synchronization before overwriting registered outputs, so reuse is ordered after both local and remote consumers. Synchronous calls preserve FSDP's stream ordering; asynchronous calls return a torch.distributed.Work whose wait() establishes a GPU-side consumer dependency without an additional CPU completion wait. Unsupported layouts or alignment use rank-major copy-out or process-group all-gather fallback as appropriate. The MORI adapter and runtime dependency remain out of PyTorch.

Runtime Controls

Default FSDP2 behavior is unchanged. Enable MORI SDMA before the first unshard, using one adapter/layout per parameter group:

from mori.ccl.torch_fsdp import MoriSdmaAllGather
from torch.distributed.fsdp import fully_shard

for module in [*model.layers, model]:
    fully_shard(module)
    comm = MoriSdmaAllGather(zero_copy_output=True)
    module.set_all_gather_layout(comm.layout, recurse=False)

The default backend-owned mode avoids the final copy for eligible groups with stable output views. zero_copy_output=False uses rank-major copy-out; fsdp_owned_output=True copies into FSDP-owned buffers. Unsupported layouts or alignment use fallback paths.

Performance

8x MI300X, Qwen2-style 7.616B BF16, sequence length 1024, batch size 1 per GPU. Tested with PyTorch dc9f852e, MoRI c19ca629, and ROCm 7.2.2.

Mode Avg step time Avg tokens/s Avg TFLOPs Avg TFLOPs/GPU Final loss Throughput gain
native 0.288613 s 28384.05 1296.97 162.12 12.104525566101074 baseline
MoRI SDMA zero-copy 0.257842 s 31771.36 1451.75 181.47 12.104525566101074 +11.93%

Averages use measured steps 50-499 across all eight ranks. Tokens/s is global throughput, TFLOPs are parameter-count estimates in TFLOP/s, and final loss is from rank 0.

Historical performance on older versions.

Test Plan

Validated FSDP Python at db85e8f5 with the existing dc9f852e native build, MoRI c19ca629, Python 3.11 and ROCm 7.2.2 on 8x MI300X (HSA_ENABLE_IPC_MODE_LEGACY=1).

  • Upstream FSDP comm, extensions, mixed-precision and training tests: 415 passed, 11 skipped. Coverage includes backend-owned outputs, moved-view refill, version counters, release ordering, layout ownership, eligibility and rank-major fallback.
  • Four version-counter regression cases passed; both rebound cases fail before the fix.
  • MoRI adapter unit tests: 57/57 passed.
  • MoRI eight-rank E2E: 9 backend-owned and 11 FSDP-owned configurations passed.
  • MoRI eight-rank BF16 training parity: four configurations, 20 steps each; outputs, loss, gradients and updated parameters bit-exact against native RCCL.
  • MoRI pooled training: 10/10 configurations passed. Pool controls, subgroup and stream/lifetime checks also passed (20/20 MoRI stages overall).
  • PyTorch spin quicklint -a and git diff --check passed.

Excluded test_train_parity_multi_group, whose native UDS EMFILE resource failure was reproduced with both base and PR FSDP Python. The 11 skips are existing platform/library gates. MoRI validation used two test-only compatibility patches and extended the subgroup test gate to eight ranks; adapter and native code were unchanged.

Co-authored-by: inkcherry [email protected]
Co-authored-by: Jeff Daily [email protected]

@wuyl1
wuyl1 requested a review from weifengpy as a code owner June 26, 2026 15:56
@pytorch-bot

pytorch-bot Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit db85e8f with merge base 0d8b367 (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Jun 26, 2026
@linux-foundation-easycla

linux-foundation-easycla Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

@pytorch-bot

pytorch-bot Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Jun 26, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@jbschlosser jbschlosser added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jun 26, 2026
@inkcherry

Copy link
Copy Markdown
Contributor

@weifengpy Could you please take a look when you get a chance? thanks!

@wuyl1

wuyl1 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

@weifengpy We have already discussed this in the RFC: #186601. When you have time, could you please help review it?

):
return self._collective

shmem = importlib.import_module("mori.shmem")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the dependency specified somewhere in torch?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I kept MORI as an optional runtime dependency.

mori.shmem / mori.ccl are now imported lazily only when MoriSdmaAllGather is used. If MORI is missing, the backend raises a clear runtime error instead of affecting normal PyTorch/FSDP imports.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to move the MORI-specific adapter to the MORI/client side and keep only the generic FSDP APIs in PyTorch? @wuyl1, This would make the PR cleaner, also appreciate @jeffdaily and @weifengpy’s thoughts on this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We propose providing a generic, vendor-independent backend in PyTorch to fuse all-gather and layout transformation, without introducing MORI-specific code. MORI and other backends supporting this mechanism can reuse it on the client side. @jeffdaily @weifengpy, we’d appreciate your thoughts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

letting MoriSdmaAllGather be hosted outside of pytorch makes sense to me

all_gather_work: dist.distributed_c10d.Work | None
# Whether the backend produced a parameter-contiguous output that can be
# used in place (see `AllGather.supports_param_contiguous_output`)
use_param_contiguous_output: bool

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am little bit hesitated of adding if-else base on use_param_contiguous_output. I was imagining a generic contract to let user override copy-out / view-out + collective

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I refactored this following your suggestion.

The FSDP all-gather path no longer branches on use_param_contiguous_output. Instead, the output handling is routed through the AllGather backend contract:

  • prepare_output(...) lets a backend prepare custom output metadata/layout.
  • copy_in(...) lets a backend choose the matching input packing.
  • finalize_outputs(...) lets a backend either use the default rank-major copy-out or view parameters directly into backend-owned output.

I also moved the param-contiguous eligibility/view initialization behind default AllGather helper methods, so the MORI backend no longer reaches into FSDP core private helpers.

@weifengpy weifengpy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see comment above

@wuyl1

wuyl1 commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

see comment above

@weifengpy Thanks for the review. I updated the PR to address both comments:

  1. MORI dependency handling:

    • Kept MORI as an optional runtime dependency.
    • Moved mori.shmem / mori.ccl imports to lazy import inside the backend initialization path.
    • Added a clear runtime error if MORI is not installed.
    • Added test coverage for the missing-MORI case.
  2. Generic backend contract:

    • Removed the FSDP-core special casing around param-contiguous output.
    • Routed all-gather output handling through the AllGather contract via prepare_output, copy_in, and finalize_outputs.
    • Moved param-contiguous eligibility and view initialization behind default AllGather helper methods, so custom backends do not need to reach into FSDP core private helpers.

The default FSDP/NCCL path should remain behaviorally unchanged and continues to use the rank-major output + copy-out path.

@inkcherry

inkcherry commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Hi @weifengpy, thanks for the review! @wuyl1 and I went through your feedback together, and he's updated the PR accordingly. We'd appreciate any further comments when you get a chance. Thanks!

@wuyl1

wuyl1 commented Jul 24, 2026

Copy link
Copy Markdown
Contributor Author

Gentle ping @weifengpy — could you please take another look when you have time? Thanks!

@jeffdaily

Copy link
Copy Markdown
Collaborator

On placement: I support the split @inkcherry proposed. The generic contract (the AllGather hooks) plus the FSDPParam/collectives plumbing belongs in PyTorch; MoriSdmaAllGather belongs on the MORI side. The July refactor already reduced the adapter to the base-class contract with a lazy mori import, so nothing requires it in-tree, and an in-tree backend that CI can never exercise (mori is not installed in any CI, so only the mock tests run) will rot. It would also be the first FSDP backend in-tree with a hard dependency on an external vendor runtime; SymmMemAllGather and ProcessGroupAllocAllGather depend only on core.

The condition for that split: the hook contract has to stop leaking internals before it becomes a de facto public API for out-of-tree backends. prepare_output/finalize_outputs currently take list[FSDPParam] and AllGatherResult plus a default_finalize closure, all private types. That is fine while the only consumer is in-tree; it is not a contract an external adapter can safely build against.

@wuyl1 on the vendor-neutral fused-backend variant: it stays vendor-neutral only while it has no mori import. As soon as it needs the vendor collective handle it degenerates back to an in-tree vendor adapter, so I would not pursue it.

Independent of placement, three things in the current zero-copy design need answers, because they live in the generic plumbing:

  1. Buffer lifetime vs FSDP2 overlap. With one backend instance shared across modules (the docs example), allocate() reuses one persistent buffer, but FSDP2 enqueues gather(B) before group A's copy-out completes and never orders gather(B) after compute(A); the default path is only safe because fresh caching-allocator buffers are event-gated. A manually reused buffer is a silent race in both modes. Per-group buffers avoid the race, but then free_unsharded_param skipping backend-owned outputs keeps every layer's full unsharded buffer resident permanently, which negates FSDP's memory saving. The RFC should state the intended steady-state model and the code should enforce or document it.

  2. _MoriSdmaAllGatherWork is not a dist.Work, and FSDP only calls wait() behind an isinstance(..., Work) check, so unshard(async_op=True) never waits for SDMA completion. Subclass torch.distributed.Work, or have the contract forbid async_op for non-Work returns.

  3. prepare_output raises on a non-4-byte-aligned split (any odd-numel bf16 param). The feature is designed around graceful fallback; this should return None (warn once), not kill training.

Process: the PR now conflicts with #194114/#194058 in _fsdp_param.py and needs a rebase, and the workflows have never been approved to run, so there is no CI signal at all. The copy-out refactor also affects the default backend path, so a green compiled-FSDP2 run is needed regardless.

Analysis assisted by AI.

@wuyl1
wuyl1 force-pushed the sdma_fsdp2 branch 2 times, most recently from 06c65ed to 9a68d10 Compare September 17, 2026 02:45
@wuyl1 wuyl1 changed the title [FSDP] Add MORI SDMA all-gather backend and zero-copy output capability [FSDP2] Add output-layout support for custom all-gather backends Sep 17, 2026
@wuyl1 wuyl1 changed the title [FSDP2] Add output-layout support for custom all-gather backends [FSDP2] Add output-layout support for MORI SDMA all-gather Sep 17, 2026
@wuyl1

wuyl1 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

@jeffdaily, thanks for the detailed review. We have updated the PR with the following changes:

  1. Removed the MORI adapter from PyTorch. It now lives in the MORI repository.
  2. Moved the main layout-handling logic and utilities into torch/distributed/fsdp/_fully_shard/_all_gather_layout.py. Changes to the core FSDP files are minimal and mostly follow this pattern:
    if layout is present:
        apply layout-specific logic
  3. Rebased the branch, resolved the resulting issues, and reran the tests and E2E performance and loss validation.

@wuyl1

wuyl1 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

@jeffdaily, thanks for the detailed review. We have updated the PR with the following changes:

  1. Removed the MORI adapter from PyTorch. It now lives in the MORI repository.
  2. Moved the main layout-handling logic and utilities into torch/distributed/fsdp/_fully_shard/_all_gather_layout.py. Changes to the core FSDP files are minimal and mostly follow this pattern:
    if layout is present:
        apply layout-specific logic
  3. Rebased the branch, resolved the resulting issues, and reran the tests and E2E performance and loss validation.

cc: @weifengpy @inkcherry

@inkcherry

Copy link
Copy Markdown
Contributor

Looks clean now, with minimal changes to the core files. @jeffdaily, @weifengpy, could we move forward with this?

layout = all_gather_comm.layout
copy_in = torch.ops.fsdp.all_gather_copy_in
output_metadata = None
if layout is not None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

layout abstraction makes sense, but i would need the abstraction to cover default code path as well, ideally all things goes through layout.prepare without if-else on layout being None

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated. Both default and custom paths now go through layout.prepare(), with DefaultAllGatherLayout as the default and no layout is None branch.

) = all_gather_result
_dtype, device = all_gather_output.dtype, all_gather_output.device
device_handle = _get_device_handle(device.type)
if all_gather_event is not None: # sync op
device_handle.current_stream().wait_event(all_gather_event)
if isinstance(all_gather_work, dist.distributed_c10d.Work): # async op
all_gather_work.wait()
if layout is not None and output_metadata is not None:
param_outputs = layout.finalize_outputs(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same - prefer default code path to go through layout.finalize_outputs as well

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated as well—the default path now goes through layout.finalize_outputs().

@@ -870,6 +871,11 @@ def init_all_gather_outputs(
world_size: int,
device: torch.device,
):
if self._keep_all_gather_output_storage:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this equivalent to reshard_after_forward=False ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not equivalent. FSDP still reshards and gathers again for backward. Per-group buffers would still lose the memory saving; release_output() enables reuse through a shared pool.

hasattr(fsdp_param, "_unsharded_param")
and fsdp_param._unsharded_param.data_ptr() != outputs[0].data_ptr()
):
del fsdp_param._unsharded_param

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would fsdp_param._unsharded_param = None give you the same thing? it would be easier to not think about hasattr(fsdp_param, "_unsharded_param")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated. _unsharded_param is initialized to None, and the hasattr checks are replaced with explicit None checks.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Summary (human written only)

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

## Agent details (if applicable)

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

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

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

## Summary (human written only)

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

## Agent details (if applicable)

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

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

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

## Summary (human written only)

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

## Agent details (if applicable)

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

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

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

## Summary (human written only)

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

## Agent details (if applicable)

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

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

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

## Summary (human written only)

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

## Agent details (if applicable)

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

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

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

## Summary (human written only)

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

## Agent details (if applicable)

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

Co-authored-by: wuyl1 <[email protected]>
Co-authored-by: inkcherry <[email protected]>
ghstack-source-id: 86aea82
Pull-Request: #199726
wuyl1 and others added 5 commits November 24, 2026 03:47
Extend the landed pytorch#199726 contract with an explicit backend-owned output mode.
FSDP adopts buffer-less outputs without freeing their storage, refills stable
parameter views when backend storage moves, preserves autograd versions around
packing and collective work, and releases output leases on reshard, discarded
gathers and failed setup. Overlapping refills and aliased rank-major fallback
preserve their sources before copying.

This retains the implementation from 2c576b8 as ported in 85fc7ab. Input layout
eligibility defaults to False here; the next commit enables eligible outputs and
binds a backend-owned layout to one group. The following commit adds the existing
regression tests, followed by the existing wrapper-output pointer fix.

Test Plan

Core CPU layout, copy-out and setter checks passed (22 tests) with an e67ea98
ROCm binary and Git-pinned FSDP Python source. The test loader removes two JVP
annotations in memory for Python 3.10 and aliases the existing BackendBase
binding; the unmodified Python 3.12 syntax and AST equivalence checks passed.
The final feature patch is byte-identical to the existing PR. Latest-main
spin quicklint -a passed for this step with isolated Python 3.11 lint tools.

Commands run inside sdma-test1:

```bash
env ROCR_VISIBLE_DEVICES= HIP_VISIBLE_DEVICES= CUDA_VISIBLE_DEVICES= PYTHONDONTWRITEBYTECODE=1 PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu OMP_NUM_THREADS=1 PYTHONPATH=/root/wuyl/pytorch-review-integration/agent_space/rebase-latest-20261012/baseline/runtime /root/wuyl/pytorch-review-build-e67/agent_space/venv/bin/python /root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/four-commit-review/validation/cpu_probe.py --repo /root/wuyl/pytorch-fsdp-clean-main-20261124 --revision 1784313 --test-revision 0d8b367 --mode cpu
```

Lint command:

```bash
docker exec -w /root/wuyl/pytorch-fsdp-clean-main-20261124 -e UV_PYTHON_INSTALL_DIR=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/python -e UV_CACHE_DIR=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/cache -e PATH=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/venv/bin:/opt/conda/envs/py_3.10/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin sdma-test1 /root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/venv/bin/spin quicklint -a torch/distributed/fsdp/_fully_shard/_all_gather_layout.py torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py torch/distributed/fsdp/_fully_shard/_fsdp_param.py torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py > /home/yangwu/.codex/fsdp-history-cleanup-20261124/validation/01-core-lint.log 2>&1
```

History reorganized with OpenAI Codex; no new feature code was introduced.

Co-authored-by: inkcherry <[email protected]>
Co-authored-by: Jeff Daily <[email protected]>
Compute the landed layout contract's parameter-contiguous eligibility from the
payload dtype and layout, disabling it for extensions, DTensor parameters,
post-forward shards and compiled autograd. Pass the result to prepare() while
retaining the landed keyword-only metadata and output_metadata comm interface.

Bind only BackendOwnedAllGatherLayout to one group through a weak reference.
Recursive installation deduplicates joint groups and validates every group
before changing any, while stateless custom layouts retain main's sharing rules.
These are the existing 85fc7ab changes separated from the storage implementation.

Test Plan

The complete four-step patch and six changed files match the existing PR.
Python 3.12 syntax checks and git diff --check passed for this step.
Final-candidate CPU layout/copy-out/setter regression passed 43 tests with the
e67ea98 binary and Git-pinned FSDP source. The loader removes two JVP annotations
in memory for Python 3.10 and aliases the existing BackendBase binding. This is
CPU validation of the complete candidate, not a latest-main rebuild. Latest-main
spin quicklint -a passed for this step with isolated Python 3.11 lint tools.

Final-candidate command run inside sdma-test1:

```bash
env ROCR_VISIBLE_DEVICES= HIP_VISIBLE_DEVICES= CUDA_VISIBLE_DEVICES= PYTHONDONTWRITEBYTECODE=1 PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu OMP_NUM_THREADS=1 PYTHONPATH=/root/wuyl/pytorch-review-integration/agent_space/rebase-latest-20261012/baseline/runtime /root/wuyl/pytorch-review-build-e67/agent_space/venv/bin/python /root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/four-commit-review/validation/cpu_probe.py --repo /root/wuyl/pytorch-fsdp-clean-main-20261124 --revision 64e1636 --test-revision 64e1636 --mode cpu
```

Lint command:

```bash
docker exec -w /root/wuyl/pytorch-fsdp-clean-main-20261124 -e UV_PYTHON_INSTALL_DIR=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/python -e UV_CACHE_DIR=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/cache -e PATH=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/venv/bin:/opt/conda/envs/py_3.10/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin sdma-test1 /root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/venv/bin/spin quicklint -a torch/distributed/fsdp/_fully_shard/_all_gather_layout.py torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py torch/distributed/fsdp/_fully_shard/_fully_shard.py > /home/yangwu/.codex/fsdp-history-cleanup-20261124/validation/02-contract-lint.log 2>&1
```

History reorganized with OpenAI Codex; no new feature code was introduced.
Keep the existing 85fc7ab tests for buffer-less adoption, moved and overlapping
refills, output leases, version counters, rank-major alias fallback, eligibility
and group binding. Training cases cover backend-owned output parity and discarded
unused prefetches using the landed helpers.

The test file is unchanged from the existing PR. This separates coverage from
the production implementation; the next commit retains the wrapper-output
pointer fix.

Test Plan

Python 3.12 syntax checks and git diff --check passed for this step.
Final-candidate CPU layout/copy-out/setter regression passed 43 tests with the e67ea98 binary and
Git-pinned FSDP source. Two JVP annotations are removed only in memory for
Python 3.10 and BackendBase aliases the same existing binding. Latest-main
spin quicklint -a passed for this step with isolated Python 3.11 lint tools.
GPU training is not rerun for
this history-only change; the final feature source is byte-identical to the PR.

Final-candidate command run inside sdma-test1:

```bash
env ROCR_VISIBLE_DEVICES= HIP_VISIBLE_DEVICES= CUDA_VISIBLE_DEVICES= PYTHONDONTWRITEBYTECODE=1 PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu OMP_NUM_THREADS=1 PYTHONPATH=/root/wuyl/pytorch-review-integration/agent_space/rebase-latest-20261012/baseline/runtime /root/wuyl/pytorch-review-build-e67/agent_space/venv/bin/python /root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/four-commit-review/validation/cpu_probe.py --repo /root/wuyl/pytorch-fsdp-clean-main-20261124 --revision 64e1636 --test-revision 64e1636 --mode cpu
```

Lint command:

```bash
docker exec -w /root/wuyl/pytorch-fsdp-clean-main-20261124 -e UV_PYTHON_INSTALL_DIR=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/python -e UV_CACHE_DIR=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/cache -e PATH=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/venv/bin:/opt/conda/envs/py_3.10/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin sdma-test1 /root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/venv/bin/spin quicklint -a test/distributed/_composable/fsdp/test_fully_shard_comm.py > /home/yangwu/.codex/fsdp-history-cleanup-20261124/validation/03-tests-lint.log 2>&1
```

History reorganized with OpenAI Codex; no new feature code was introduced.
…puts

The port hoisted the all_gather_output data_ptr() read out of the _keep_all_gather_output_storage branch. With all-gather extensions the output is a wrapper subclass (TwoTensor) without storage, so test_all_gather_extension_hsdp_mesh and test_all_gather_extensions_monkey_patch failed with "Attempted to access the data pointer on an invalid python storage". The alias check only matters for backend-owned outputs, so read the pointer there, as the original commit did.

Test Plan:

```
python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
python test/distributed/_composable/fsdp/test_fully_shard_comm.py
```

Authored with Claude.
copy_in() may return an output wrapper with a version counter independent
of the tensor returned by allocate(). Reusing the allocation's preservation
context for communication and asynchronous wait leaves the actual output
unprotected and can invalidate a parameter saved for backward.

Keep the packing context on the allocated tensor, then construct the
communication/wait context from the returned output. Cover synchronous and
deferred writes with rebound and unchanged outputs, including version and
backward checks. Clarify backend-owned buffer and single-group semantics,
and remove the backend-owned tests' constant keep argument.

Test Plan

Official spin quicklint -a and git diff --check passed. The four new CPU
regression cases pass; the two rebound cases fail on unchanged dc9f852.
The CPU subset passed 47/47. Across the four upstream FSDP files, 415 tests
passed and 11 were skipped. Only test_train_parity_multi_group was excluded
based on its previously matched base/head native resource failure.

On an eight-MI300X host, all 20 MoRI stages passed: 57 unit tests, 9 backend-owned
and 11 FSDP-owned E2E configs, four 20-step BF16 training configs bit-exact
against RCCL, ten pooled-training configs, and controls/subgroup/streams.
Validation used candidate FSDP Python with unchanged dc9f852 native binaries,
MoRI c19ca629, ROCm 7.2.2 and HSA_ENABLE_IPC_MODE_LEGACY=1. Default-IPC and
historical resource failures remain recorded; long ABBA was not rerun.

Local validation commands, from
agent_space/solid-review-20261124 in the candidate host worktree:

```bash
/usr/bin/python3 run_validation.py smoke
/usr/bin/python3 run_validation.py cpu
/usr/bin/python3 run_validation.py audit --stage before
/usr/bin/python3 run_validation.py comm
/usr/bin/python3 run_validation.py extensions
/usr/bin/python3 run_validation.py mixed_precision
/usr/bin/python3 run_validation.py training
/usr/bin/python3 run_validation.py mori
/usr/bin/python3 run_validation.py audit --stage after
```

Commit-time lint command:

```bash
docker exec -w /root/wuyl/pytorch-fsdp-solid-review-20261124 -e UV_PYTHON_INSTALL_DIR=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/python -e UV_CACHE_DIR=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/cache -e PATH=/root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/venv/bin:/opt/conda/envs/py_3.10/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin sdma-test1 /root/wuyl/pytorch-fsdp-clean-main-20261124/agent_space/lint-env/venv/bin/spin quicklint -a torch/distributed/fsdp/_fully_shard/_all_gather_layout.py torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py torch/distributed/fsdp/_fully_shard/_fsdp_param.py torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py torch/distributed/fsdp/_fully_shard/_fully_shard.py test/distributed/_composable/fsdp/test_fully_shard_comm.py
```

Agent details

Prepared with OpenAI Codex.
@wuyl1

wuyl1 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@weifengpy @jeffdaily Now that #199726 has landed, this PR has been rebased onto main and contains the remaining backend-owned output changes. I’ve rerun the FSDP tests and 8-GPU MoRI validation, and updated the Test Plan with the results and known limitations.

Could you review the current head (db85e8f5)? @jeffdaily, could you also help approve the pending CI workflows? Thanks again for your help!

cc @inkcherry

@jeffdaily jeffdaily left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. I validated the port up to dc9f852 on 8x MI300X (FSDP extensions, comm and multi-group parity tests, and 20-step bf16 MoRI SDMA training bit-exact against RCCL in all four modes), and db85e8f's version-counter fix looks right to me.

@weifengpy FYI, this is the backend-owned output follow-up to #199726. We're landing it once CI is green.

@wuyl1 two MoRI tests at c19ca629 still assert the old contract and need updating on the MoRI side:

  • test_fallback_selects_default_finalizer expects torch.ops.fsdp.all_gather_copy_in; the landed DefaultAllGatherLayout.prepare now returns self.copy_in.
  • test_shared_fsdp_outputs expects set_custom_all_gather(DefaultAllGather()) to raise under a comm-carrying layout; the landed contract accepts it.

@wuyl1

wuyl1 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

@jeffdaily Thanks for the review and validation! Both issues are fixed in ROCm/mori@d270eda:

  • test_fallback_selects_default_finalizer now checks the callable returned by the default layout's prepare, with additional checks for actual packing and aliasing.
  • test_shared_fsdp_outputs now accepts set_custom_all_gather(DefaultAllGather()) and verifies that the installed layout, its bound MoRI comm and owner remain unchanged. Incompatible custom comms are still rejected.

These test changes were already covered by the earlier validation: 57/57 adapter unit tests and 10/10 eight-rank pooled-training configurations passed. Ruff and Black also passed before commit.

The branch has been renamed to fsdp2-adapter-review-20261125.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-refresh-hf-cache ciflow/b200 ciflow/binaries Trigger all binary build and upload jobs on the PR ciflow/docker ciflow/dtensor Run DTensor specific tests ciflow/h100-symm-mem ciflow/h100 ciflow/inductor ciflow/mps Run MPS tests (subset of trunk) ciflow/periodic-strict ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request module: amp (automated mixed precision) autocast module: compiled autograd compiled_autograd module: cpu CPU specific problem (e.g., perf, algorithm) module: dynamo module: inductor module: mkldnn Related to Intel IDEEP or oneDNN (a.k.a. mkldnn) integration open source release notes: distributed (checkpoint) release notes: distributed (fsdp) release notes category release notes: inductor (aoti) release notes: quantization release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants