Repository navigation
Conversation
🔗 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 ( 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. |
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
|
@weifengpy Could you please take a look when you get a chance? thanks! |
|
@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") |
There was a problem hiding this comment.
is the dependency specified somewhere in torch?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 Thanks for the review. I updated the PR to address both comments:
The default FSDP/NCCL path should remain behaviorally unchanged and continues to use the rank-major output + copy-out path. |
|
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! |
|
Gentle ping @weifengpy — could you please take another look when you have time? Thanks! |
|
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:
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. |
06c65ed to
9a68d10
Compare
|
@jeffdaily, thanks for the detailed review. We have updated the PR with the following changes:
|
cc: @weifengpy @inkcherry |
|
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: |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
same - prefer default code path to go through layout.finalize_outputs as well
There was a problem hiding this comment.
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: | |||
There was a problem hiding this comment.
is this equivalent to reshard_after_forward=False ?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
would fsdp_param._unsharded_param = None give you the same thing? it would be easier to not think about hasattr(fsdp_param, "_unsharded_param")
There was a problem hiding this comment.
Updated. _unsharded_param is initialized to None, and the hasattr checks are replaced with explicit None checks.
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
…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
## 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
## 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
## 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
## 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
## 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
## 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
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.
|
@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 ( cc @inkcherry |
jeffdaily
left a comment
There was a problem hiding this comment.
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_finalizerexpectstorch.ops.fsdp.all_gather_copy_in; the landedDefaultAllGatherLayout.preparenow returnsself.copy_in.test_shared_fsdp_outputsexpectsset_custom_all_gather(DefaultAllGather())to raise under a comm-carrying layout; the landed contract accepts it.
|
@jeffdaily Thanks for the review and validation! Both issues are fixed in ROCm/mori@d270eda:
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 |
cc: @weifengpy @jeffdaily
Summary
For eligible groups, MORI SDMA writes directly into its registered output storage in a parameter-contiguous layout:
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
BackendOwnedAllGatherLayout, allowing parameter outputs to reference backend-owned storage without returning FSDP-owned persistent buffers.release_output()notification after reshard and on discarded or failed gather paths. Wait for discarded collective work before releasing its output.The companion MORI change provides
MoriSdmaAllGatheron 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 atorch.distributed.Workwhosewait()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:
The default backend-owned mode avoids the final copy for eligible groups with stable output views.
zero_copy_output=Falseuses rank-major copy-out;fsdp_owned_output=Truecopies 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, MoRIc19ca629, and ROCm 7.2.2.0.288613 s28384.051296.97162.1212.1045255661010740.257842 s31771.361451.75181.4712.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
db85e8f5with the existingdc9f852enative build, MoRIc19ca629, Python 3.11 and ROCm 7.2.2 on 8x MI300X (HSA_ENABLE_IPC_MODE_LEGACY=1).spin quicklint -aandgit diff --checkpassed.Excluded
test_train_parity_multi_group, whose native UDSEMFILEresource 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]