Repository navigation
[fsdp2] Optionally keep unsharded storage across reshard - #198417
andrewor14 wants to merge 2 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/198417
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 77b0b37 with merge base 612b9a5 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
Should this be a bool or should we make it some it can be an enum one day? |
7774875 to
7668ad5
Compare
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We always use fsdp=1 to avoid an actual all-gather. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- new weight sync ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now Potential concerns with this approach: 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be the same across weight syncs. The current state in this PR requires an explicit `reshard(free_unsharded=False)` API, which does not exist in pytorch yet. We would need to add this or something similar to support cudagraphs. 2. **Extra decode memory:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We could work around this by calling private FSDP APIs to free this storage on unshard. Requires pytorch/pytorch#198417 for new `FSDPModule.reshard` flags.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We always use fsdp=1 to avoid an actual all-gather. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- new weight sync ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now Potential concerns with this approach: 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be the same across weight syncs. The current state in this PR requires an explicit `reshard(free_unsharded=False)` API, which does not exist in pytorch yet. We would need to add this or something similar to support cudagraphs. 2. **Extra decode memory:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We could work around this by calling private FSDP APIs to free this storage on unshard. Requires pytorch/pytorch#198417 for new `FSDPModule.reshard` flags.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We always use fsdp=1 to avoid an actual all-gather. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- new weight sync ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now Potential concerns with this approach: 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be the same across weight syncs. The current state in this PR requires an explicit `reshard(free_unsharded=False)` API, which does not exist in pytorch yet. We would need to add this or something similar to support cudagraphs. 2. **Extra decode memory:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We could work around this by calling private FSDP APIs to free this storage on unshard. Requires pytorch/pytorch#198417 for new `FSDPModule.reshard` flags.
Generator MXFP8 linears use FSDP degree 1, but retaining separate parameter and compute weights wastes memory and complicates CUDA graph weight updates. Store the existing quantizer's FP8 data and GEMM-ready scales as the parameter's persistent buffers, and let FSDP expose a compute view of those same allocations. ``` meta model -> TP -> FP8 storage -> fully_shard -> allocate/init TorchStore BF16 receive DTensor -> existing MXFP8 quantizer -> update persistent FP8 data + GEMM-ready scales in place -> captured compute reads the same buffers ``` `_MXFP8StorageTensor` reuses `_quantize_mxfp8_weight`, `_MXFP8LinearOperands`, and `_UnshardedFSDPTensor`. There is one persistent storage subclass and one FP8 data allocation per converted weight. Loading BF16 weights preserves the addresses of the data and both existing scale layouts. No FSDP all-gather, packed byte payload, or scale-layout conversion is needed during unshard. The inference variant is installed after TP and before `fully_shard`, with logical BF16 parameter metadata. State dicts expose temporary BF16 DTensors with the generator's mesh and placements, preserving checkpoint and TorchStore loading. It supports ordinary and stacked projections, requires complete TP-local 32x32 tiles, and explicitly requires FSDP degree 1. Training and grouped-expert implementations are unchanged. Requires pytorch/pytorch#198468 for FSDP's borrowed-storage path and `fsdp_get_unsharded_view`. Generator parameters are frozen so ordinary BF16 parameters can share storage too. The generic generator prepare/finish callbacks remain for other formats with separate compute buffers and still require pytorch/pytorch#198417. Direct MXFP8 weight-loading tests exercise #198468 independently of #198417. Validation: - CPU quantization/storage suite: 61 passed. - GPU storage and CUDA graph checks: 4 passed; 4 native MXFP8 cases skipped because this machine has H100 GPUs, not SM100. - `pre-commit run --all-files`: passed, including type checking. - GPU checks use real DTensor/FSDP with TP=1/2 and a reference quantizer plus BF16 matmul on H100. They verify exact data/scales, shared and stable addresses, and exact replay outputs after three BF16 loads without explicit reshard/unshard. Native TorchAO MXFP8/GEMM cases require SM100 GPUs; full vLLM/RL validation is not included. - The GPU checks use the independent Python FSDP changes from #198468 on the existing built torch, without the earlier multi-rank extension-layout candidate. The CPU and multi-GPU test files are selected by the repository's existing CI workflows once that dependency is available. Prepared with Codex as a user-requested draft. Based on the independent #4860 copy of #4838; the original #4838 is untouched. ghstack-source-id: f959f33 Pull-Request: #4861
|
this is on my review radar - will take a look late today |
|
@andrewor14 if you are in a rush to unblock titan side change, any chance to patch reshard at titan first? at fsdp2 side, we might ended up with 2 rounds of API discussion. I understand the core change wasn't a lot, it's just free_unsharded + force is quite a combo for user to understand |
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We always use fsdp=1 to avoid an actual all-gather. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- new weight sync ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now Potential concerns with this approach: 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be the same across weight syncs. The current state in this PR requires an explicit `reshard(free_unsharded=False)` API, which does not exist in pytorch yet. We would need to add this or something similar to support cudagraphs. 2. **Extra decode memory:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We could work around this by calling private FSDP APIs to free this storage on unshard. Requires pytorch/pytorch#198417 for new `FSDPModule.reshard` flags.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We always use fsdp=1 to avoid an actual all-gather. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- new weight sync ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now Potential concerns with this approach: 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be the same across weight syncs. The current state in this PR requires an explicit `reshard(free_unsharded=False)` API, which does not exist in pytorch yet. We would need to add this or something similar to support cudagraphs. 2. **Extra decode memory:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We could work around this by calling private FSDP APIs to free this storage on unshard. Requires pytorch/pytorch#198417 for new `FSDPModule.reshard` flags.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We always use fsdp=1 to avoid an actual all-gather. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- new weight sync ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now Potential concerns with this approach: 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be the same across weight syncs. The current state in this PR requires an explicit `reshard(free_unsharded=False)` API, which does not exist in pytorch yet. We would need to add this or something similar to support cudagraphs. 2. **Extra decode memory:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We could work around this by calling private FSDP APIs to free this storage on unshard. Requires pytorch/pytorch#198417 for new `FSDPModule.reshard` flags.
| @@ -332,15 +332,25 @@ def __new__(cls, *args, **kwargs): | |||
| self.__init__(*args, **kwargs) | |||
| return self | |||
|
|
|||
| def reshard(self) -> None: | |||
| def reshard(self, *, free_unsharded: bool = True, force: bool = False) -> None: | |||
There was a problem hiding this comment.
free_unsharded is truly somehting we cannot express
force is equivalent to set_reshard_after_forward & set_reshard_after_backward. but most importantly, model.state_dict() triggers reshard for you. you can get rid of prepare_weight_sync at torchtitan side
we can add this API instead of changing existing reshard
FSDPModule.set_keep_unsharded_storage(keep: bool, *, recurse: bool = True)
# once, before CUDA graph capture
model.set_keep_unsharded_storage(True)
# each weight sync 1...n
# no need for prepare_weight_sync
model_sd = model.state_dict() # trigger reshard
await ts.get_state_dict("model_state_dict", user_state_dict=model_sd, ...)
model.load_state_dict(model_sd, strict=False)
with torch.inference_mode():
# unshard and forward
There was a problem hiding this comment.
Yes I think that would work! Will update this PR accordingly. For now I have decoupled pytorch/torchtitan#4838 from this PR
7668ad5 to
d666b46
Compare
d666b46 to
e174574
Compare
**Summary:** Add a recursive setter that controls whether resharding frees the unsharded parameter storage. This preserves storage addresses without changing the existing reshard API. ```python model = fully_shard(model) model.set_keep_unsharded_storage(True) model.unshard() model.reshard() # Unsharded storage stays resident in memory. ``` Enables pytorch/torchtitan#4838 and preserves existing behavior. **Test Plan:** ``` python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py \ -k keep_unsharded_storage python test/distributed/_composable/fsdp/test_fully_shard_training.py \ -k keep_unsharded_storage_with_post_forward_reshard ```
e174574 to
5b70541
Compare
…fers > AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2). > > This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276. > > FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving parameter memory with custom layouts. `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts. > > `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While such a layout is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. FSDP runs every all-gather through the installed layout's `prepare`, `copy_in` and `finalize_outputs`, including the default layout's, whose packing and copy-out are the previous default code, so a subclass's overrides take effect. A fast path that inlined the default layout measured within noise of this on a CPU-bound unshard and reshard benchmark, so there is none. > > This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, the setter documents that a layout that keeps per-call state must not be shared across parameter groups. It builds on #199729, at the bottom of this stack, which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper. > > Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, and that refills take one copy, also over the post-forward mesh and after a rank-major first unshard. Unit tests cover the rejected ownership cases, the default copy-out with and without delegation, and the setter rules. This PR also turns on the native all-gather copy in the strided-allocation, extension, mixed-precision, training-parity and inference tests, which #197701 runs with only the native reduce-scatter copy. > > Test Plan (local build, 4 B200 GPUs): > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardLayoutParity > python test/distributed/_composable/fsdp/test_fully_shard_comm.py > python test/distributed/_composable/fsdp/test_fully_shard_extensions.py > python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage > python test/distributed/_composable/fsdp/test_fully_shard_memory.py > python test/distributed/_composable/fsdp/test_fully_shard_compile.py > python test/test_public_bindings.py -k test_correct_module_names > ``` > All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on the parent commit on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 125 passed and 2 skipped. The other suites passed: compile 7, extensions 9, mixed precision 26, state dict 1, memory 7, public bindings 1. Co-authored-by: wuyl1 <[email protected]> Co-authored-by: inkcherry <[email protected]> ghstack-source-id: 2216a7b Pull-Request: #199726
> AI-assisted draft prepared with Claude Code for discussion on #188276. > > On top of the previous PR's clone of #188276, this shows the changes we suggest. The result is the all-gather contract we'd like to land, option 3 of #199720, #199721 and #199726, with #188276's backend-owned zero copy as an explicit opt-in. > > - FSDP owns the storage behind the parameters' all-gather outputs by default, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors, buffers)` with outputs that view them. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them before every later finalize, and checks that the layout refilled the same outputs in place, so `reshard_after_forward` keeps saving memory with custom layouts. > - Backend-owned storage, #188276's model, becomes an explicit opt-in. Only a `BackendOwnedAllGatherLayout`, whose `release_output()` is abstract, may return outputs that FSDP never frees, and FSDP calls `release_output()` after reshard, after a discarded prefetch and after a failed setup. `release_output` moves from `AllGather` to the layout, and `AllGather.layout` and `AllGather.reuses_output_storage` are removed. > - `finalize_outputs` takes a single `AllGatherFinalizeMetadata`, so later fields do not break out-of-tree layouts. > - `set_all_gather_layout` is the only way to install a layout. A layout that needs its own collective sets `comm`, and installing the layout installs that comm. While it is installed, `set_custom_all_gather` and the internal comm swaps of `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject any other comm. > - An installed `DefaultAllGatherLayout`, including the native copy's, takes a fast path that runs the stack's default code, so the default path builds no per-call layout metadata. > - `FSDPParam._unsharded_param` stays lazily created, because out-of-tree patches of `post_backward` check it with `hasattr`. > - Separately from the contract, `test_compiled_backward_eligibility` sets multiprocessing's start method to spawn before compiling. Compiling otherwise fixes it to fork after CUDA is initialized, so every `FSDPTestContinuous` class later in the file fails to start its workers when the file runs in one process. > > In MORI's adapter at ROCm/mori@7f40b1bd, `_MoriSdmaAllGatherLayout` would subclass `BackendOwnedAllGatherLayout`, set `comm`, and implement `release_output()` with the logic now in `MoriSdmaAllGather.release_output`. Its `finalize_outputs` would read the metadata argument and return `AllGatherOutputs(views)`, and users would install it with `module.set_all_gather_layout(layout)` instead of `set_custom_all_gather(comm)`. > > Review `_all_gather_layout.py` first, then `_fsdp_collectives.py`, `_fsdp_param_group.py` and `_fully_shard.py`. The tests add an FSDP-owned parameter-contiguous layout that checks its buffer is freed after reshard unless storage is kept and refilled with one copy. They keep #188276's backend-owned tests on the opt-in, cover the rejected ownership cases and the setter rules, and run `TestFullyShardLayoutParity` on `FSDPTestContinuous`. > > Test Plan (local build, 4 B200 GPUs): > ```bash > python test/test_public_bindings.py -k test_correct_module_names > python test/distributed/_composable/fsdp/test_fully_shard_comm.py > python test/distributed/_composable/fsdp/test_fully_shard_extensions.py > python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_train_parity_multi_group -k keep_unsharded_storage > python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage > python test/distributed/_composable/fsdp/test_fully_shard_memory.py > ``` > In the full comm file, 197 of 200 tests pass and 2 are skipped, as on #197701. `test_fully_shard_alloc_from_pg` fails, as it also does on #197701 on this machine, where NCCL registers a buffer before process-group allocation is enabled. The other suites pass: public bindings 1, extensions 9, mixed precision 26, training 7, state dict 1, memory 7. ghstack-source-id: 7839cc6 Pull-Request: #199873
…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: 2216a7b Pull-Request: #199726
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We use fsdp=1 to avoid an actual all-gather for now. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore (new weight sync) | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- reshard ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now **Design considerations:** 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be stable across weight syncs. This is enabled through `model.set_keep_unsharded_storage(True)`, added in pytorch/pytorch#198417. 2. **Avoid extra memory during decode:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We work around this by calling private FSDP APIs to free this storage after unshard. Memory lifecycle: ``` 1. prepare_for_state_dict_load: re-allocate previously freed sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 2. model.state_dict() hook: reshards model (but keep unsharded buffers) | | 1 bf16 copy + 1 mxfp8 copy v 3. ts.get_state_dict: fetch new weights into sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 4. prepare_for_forward: free sharded buffers | | 1 mxfp8 copy v (prefill/decode, then repeat step 1) ``` Note: In step (2), there is currently a memory spike since FSDP allocates separate buffers for unsharded and sharded buffers, and we need to keep both resident in memory during weight sync. E.g. for bf16 generator and fsdp=1, this currently uses 2x the model memory. This may be fine since it's not the peak memory, but we should revisit in the future.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We use fsdp=1 to avoid an actual all-gather for now. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore (new weight sync) | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- reshard ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now **Design considerations:** 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be stable across weight syncs. This is enabled through `model.set_keep_unsharded_storage(True)`, added in pytorch/pytorch#198417. 2. **Avoid extra memory during decode:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We work around this by calling private FSDP APIs to free this storage after unshard. Memory lifecycle: ``` 1. prepare_for_state_dict_load: re-allocate previously freed sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 2. model.state_dict() hook: reshards model (but keep unsharded buffers) | | 1 bf16 copy + 1 mxfp8 copy v 3. ts.get_state_dict: fetch new weights into sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 4. prepare_for_forward: free sharded buffers | | 1 mxfp8 copy v (prefill/decode, then repeat step 1) ``` Note: In step (2), there is currently a memory spike since FSDP allocates separate buffers for unsharded and sharded buffers, and we need to keep both resident in memory during weight sync. E.g. for bf16 generator and fsdp=1, this currently uses 2x the model memory. This may be fine since it's not the peak memory, but we should revisit in the future.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We use fsdp=1 to avoid an actual all-gather for now. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore (new weight sync) | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- reshard ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now **Design considerations:** 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be stable across weight syncs. This is enabled through `model.set_keep_unsharded_storage(True)`, added in pytorch/pytorch#198417. 2. **Avoid extra memory during decode:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We work around this by calling private FSDP APIs to free this storage after unshard. Memory lifecycle: ``` 1. prepare_for_state_dict_load: re-allocate previously freed sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 2. model.state_dict() hook: reshards model (but keep unsharded buffers) | | 1 bf16 copy + 1 mxfp8 copy v 3. ts.get_state_dict: fetch new weights into sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 4. prepare_for_forward: free sharded buffers | | 1 mxfp8 copy v (prefill/decode, then repeat step 1) ``` Note: In step (2), there is currently a memory spike since FSDP allocates separate buffers for unsharded and sharded buffers, and we need to keep both resident in memory during weight sync. E.g. for bf16 generator and fsdp=1, this currently uses 2x the model memory. This may be fine since it's not the peak memory, but we should revisit in the future.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We use fsdp=1 to avoid an actual all-gather for now. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore (new weight sync) | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- reshard ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now **Design considerations:** 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be stable across weight syncs. This is enabled through `model.set_keep_unsharded_storage(True)`, added in pytorch/pytorch#198417. 2. **Avoid extra memory during decode:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We work around this by calling private FSDP APIs to free this storage after unshard. Memory lifecycle: ``` 1. prepare_for_state_dict_load: re-allocate previously freed sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 2. model.state_dict() hook: reshards model (but keep unsharded buffers) | | 1 bf16 copy + 1 mxfp8 copy v 3. ts.get_state_dict: fetch new weights into sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 4. prepare_for_forward: free sharded buffers | | 1 mxfp8 copy v (prefill/decode, then repeat step 1) ``` Note: In step (2), there is currently a memory spike since FSDP allocates separate buffers for unsharded and sharded buffers, and we need to keep both resident in memory during weight sync. E.g. for bf16 generator and fsdp=1, this currently uses 2x the model memory. This may be fine since it's not the peak memory, but we should revisit in the future.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We use fsdp=1 to avoid an actual all-gather for now. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore (new weight sync) | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- reshard ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now **Design considerations:** 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be stable across weight syncs. This is enabled through `model.set_keep_unsharded_storage(True)`, added in pytorch/pytorch#198417. 2. **Avoid extra memory during decode:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We work around this by calling private FSDP APIs to free this storage after unshard. Memory lifecycle: ``` 1. prepare_for_state_dict_load: re-allocate previously freed sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 2. model.state_dict() hook: reshards model (but keep unsharded buffers) | | 1 bf16 copy + 1 mxfp8 copy v 3. ts.get_state_dict: fetch new weights into sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 4. prepare_for_forward: free sharded buffers | | 1 mxfp8 copy v (prefill/decode, then repeat step 1) ``` Note: In step (2), there is currently a memory spike since FSDP allocates separate buffers for unsharded and sharded buffers, and we need to keep both resident in memory during weight sync. E.g. for bf16 generator and fsdp=1, this currently uses 2x the model memory. This may be fine since it's not the peak memory, but we should revisit in the future.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We use fsdp=1 to avoid an actual all-gather for now. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore (new weight sync) | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- reshard ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now **Design considerations:** 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be stable across weight syncs. This is enabled through `model.set_keep_unsharded_storage(True)`, added in pytorch/pytorch#198417. 2. **Avoid extra memory during decode:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We work around this by calling private FSDP APIs to free this storage after unshard. Memory lifecycle: ``` 1. prepare_for_state_dict_load: re-allocate previously freed sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 2. model.state_dict() hook: reshards model (but keep unsharded buffers) | | 1 bf16 copy + 1 mxfp8 copy v 3. ts.get_state_dict: fetch new weights into sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 4. prepare_for_forward: free sharded buffers | | 1 mxfp8 copy v (prefill/decode, then repeat step 1) ``` Note: In step (2), there is currently a memory spike since FSDP allocates separate buffers for unsharded and sharded buffers, and we need to keep both resident in memory during weight sync. E.g. for bf16 generator and fsdp=1, this currently uses 2x the model memory. This may be fine since it's not the peak memory, but we should revisit in the future.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in pytorch#4203 but for inference. We use fsdp=1 to avoid an actual all-gather for now. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore (new weight sync) | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- reshard ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now **Design considerations:** 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be stable across weight syncs. This is enabled through `model.set_keep_unsharded_storage(True)`, added in pytorch/pytorch#198417. 2. **Avoid extra memory during decode:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We work around this by calling private FSDP APIs to free this storage after unshard. Memory lifecycle: ``` 1. prepare_for_state_dict_load: re-allocate previously freed sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 2. model.state_dict() hook: reshards model (but keep unsharded buffers) | | 1 bf16 copy + 1 mxfp8 copy v 3. ts.get_state_dict: fetch new weights into sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 4. prepare_for_forward: free sharded buffers | | 1 mxfp8 copy v (prefill/decode, then repeat step 1) ``` Note: In step (2), there is currently a memory spike since FSDP allocates separate buffers for unsharded and sharded buffers, and we need to keep both resident in memory during weight sync. E.g. for bf16 generator and fsdp=1, this currently uses 2x the model memory. This may be fine since it's not the peak memory, but we should revisit in the future.
**Summary:** Enable FSDP on the generator for quantization, which reuses the FSDP tensor lifecycle mechanism introduced in #4203 but for inference. We use fsdp=1 to avoid an actual all-gather for now. New lifecycle: ``` bf16 sharded params (_LinearShardedTensorWithMXFP8Compute) | ^ | fetch from TorchStore (new weight sync) | v | updated bf16 sharded params | | | | unshard | v | all-gathered mxfp8 params (_UnshardedFSDPTensor) | | | | | | forward (many decode steps) | | | ---------------------------------------------- reshard ``` Code cleanups enabled by this change: - Removed `skip_dp` flag, since we never skip_dp anymore - Removed spmd <-> DTensor glue code during weight sync, since model state dict always contains DTensors now **Design considerations:** 1. **Cudagraph compatibility:** FSDP frees the unsharded storage today on reshard. However, cudagraph requires the unsharded address be stable across weight syncs. This is enabled through `model.set_keep_unsharded_storage(True)`, added in pytorch/pytorch#198417. 2. **Avoid extra memory during decode:** FSDP never frees the sharded storage today because it's supposed to be the source of truth. However, during decode, we don't actually need the bf16 copy anymore, since forward only needs the mxfp8 operands. At fsdp=1, this incurs an extra bf16 copy of the weights per layer during decode. We work around this by calling private FSDP APIs to free this storage after unshard. Memory lifecycle: ``` 1. prepare_for_state_dict_load: re-allocate previously freed sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 2. model.state_dict() hook: reshards model (but keep unsharded buffers) | | 1 bf16 copy + 1 mxfp8 copy v 3. ts.get_state_dict: fetch new weights into sharded buffers | | 1 bf16 copy + 1 mxfp8 copy v 4. prepare_for_forward: free sharded buffers | | 1 mxfp8 copy v (prefill/decode, then repeat step 1) ``` **Testing:** For DAPO math Qwen3-4B, the reward was consistent with before this PR and matches the README reference, with MXFP8 decode 27% faster than before this PR. <img width="1210" height="528" alt="image" src="https://github.com/user-attachments/assets/ab835f2d-3b2a-47f9-abfc-eba5ca4f3fec" />
…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: 94e1f1c 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: 17941d9 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: e136102 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: 432dd16 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: ea8bee8 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: a90866e 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: d488d99 Pull-Request: #199726
) **Summary:** Add a recursive setter that controls whether resharding frees the unsharded parameter storage. This preserves storage addresses without changing the existing reshard API. ```python model = fully_shard(model) model.set_keep_unsharded_storage(True) model.unshard() model.reshard() # Unsharded storage stays resident in memory. ``` Enables pytorch/torchtitan#4838 and preserves existing behavior. **Test Plan:** ``` python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py \ -k keep_unsharded_storage python test/distributed/_composable/fsdp/test_fully_shard_training.py \ -k keep_unsharded_storage_with_post_forward_reshard ``` Pull Request resolved: pytorch#198417 Approved by: https://github.com/weifengpy
…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: bc3aaa9 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: 020154a 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: 8797b57 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: 1a34e72 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: 4140857 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: f731026 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: b612701 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: b612701 Pull-Request: #199726
Summary: Add a recursive setter that controls whether resharding
frees the unsharded parameter storage. This preserves storage addresses
without changing the existing reshard API.
Enables pytorch/torchtitan#4838 and preserves
existing behavior.
Test Plan: