Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/204282
Note: Links to docs will display an error until the docs builds have been completed. ❌ 6 New FailuresAs of commit a4ed65a with merge base bba8f39 ( NEW FAILURES - The following jobs have failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
weifengpy
added a commit
that referenced
this pull request
Nov 10, 2026
…icies and DTensor's Shard (AI-assisted) - [x] Passes lint (`spin fixlint`) - [x] Added/updated tests - [x] Updated documentation where applicable - [ ] Included benchmark results ## Linked issue or supporting maintainer > No linked issue; the author has write access. Top of the stack on #204282, a copy of #199726: the PR below runs `fully_shard` on the FlexShard engine. ## BC-breaking? > Yes, for the experimental `flex_shard` API only: > - `torch.distributed.fsdp.experimental.flex_shard` no longer exports `MixedPrecisionPolicy`, `OffloadPolicy` and `Shard`: use `torch.distributed.fsdp.MixedPrecisionPolicy`, `OffloadPolicy` and `CPUOffloadPolicy`, and `torch.distributed.tensor.Shard`. > - `MixedPrecisionPolicy.param_dtype_overrides`, a map from parameter FQN to dtype, becomes `fully_shard`'s `param_dtype_override_fn`, a function of the parameter. > - A bucket now casts the floating-point inputs of the modules it hooks to `param_dtype` (`cast_forward_inputs=True` by default) and their outputs to `output_dtype`, as `fully_shard` does. `cast_forward_inputs=False` keeps the old behavior. > - `get_placements` reports DTensor's `Shard(dim)` for a parameter sharded on a dim. ## Summary (human written only) > _Placeholder for the author._ ## Agent details (AI-generated) Drafted with an AI assistant at the author's request. This is a draft for CI and discussion, not ready for review or merge. **Problem.** `flex_shard` had its own `MixedPrecisionPolicy`, `OffloadPolicy` and `Shard`, next to `fully_shard`'s policies and DTensor's `Shard`: two classes for each concept, with different fields (FQN-keyed dtype overrides against a function of the parameter), so a `fully_shard` configuration could not move to `flex_shard` as it is. flex_shard's policy also lacked the module-boundary casts (`cast_forward_inputs`, `output_dtype`), left as a TODO. **What.** - `BucketSpec.mp_policy` is `fully_shard`'s `MixedPrecisionPolicy`. `param_dtype`, `param_dtype_override_fn` and `reduce_dtype` set the bucket's parameter dtypes, with the override function called once per parameter, as in `fully_shard`. `cast_forward_inputs` and `output_dtype` cast the inputs and outputs of the modules that the bucket hooks: inputs before the buckets' pre-forward hooks, outputs after their post-forward hooks and the root's completion of grouped forwards, in the order of FSDP2's state hooks. The buckets that hook one module must cast alike, or `flex_shard()` raises. - `BucketSpec.offload_policy` is `fully_shard`'s `OffloadPolicy`, and `CPUOffloadPolicy` works as in `fully_shard` for buckets whose placements support it (`Placement.supports_cpu_offload`: `Shard`, but not the block and mixed placements, for which `flex_shard()` raises): the bucket keeps its sharded parameters and their gradients on the CPU, pinned by default, all-gathers onto the accelerator, and the runtime copies reduced gradients back to the CPU, as it does for `fully_shard`. Offloaded buckets are eager-only, and `relayout_bucket` rejects them. - The `fsdp2_compatible` check asks the placements whether their collectives match FSDP2's (`Placement.matches_fsdp2_collectives`: `Shard`, not a mixed bucket's members) instead of checking for the `Shard` type. - A placement function may return DTensor's `Shard(dim)`, which `flex_shard()` and `relayout_bucket()` take as the engine's `Shard(dim)`, and `get_placements` reports the engine's `Shard` as DTensor's (`Placement._api_placement`). `make_shard_placement_fn` and `per_param_placements` return DTensor's `Shard`. The engine's class keeps its name in the private `_flex_shard.placements`, where `fully_shard` also uses it. **Choices.** - DTensor's `Shard` maps to the engine's at the API boundary rather than being the engine's class: DTensor's `Shard` is a C++ class, and the engine's `Placement` carries the storage layout and collective lifecycle that DTensor placements do not. - The casts are per hooked module, not per bucket, so a module's inputs are cast once however many buckets it starts. **Review order.** `bucket_storage.py` (the policy fields and dtype resolution), `bucket_runtime.py` (the casting hooks), `flex_shard.py` (validation and relayout), `placements/shard.py` and `placement_contract.py` (the `Shard` mapping and the placements' declarations), `experimental/flex_shard.py`, then tests: `test_param_dtype_override_fn` replaces the FQN-override test, `test_mixed_precision_casts_at_hooked_modules` covers the casts and the conflict check, the FSDP2 parity test now gives both frontends one policy class and DTensor's `Shard`, `test_cpu_offload` trains an offloaded model against one on the accelerator, with microbatches that accumulate gradients without sync, and `test_cpu_offload_requires_placements_that_support_it` replaces the test that `CPUOffloadPolicy` is rejected. ### Test Plan ``` python -m pytest test/distributed/_composable/flex_shard/<file>.py # each file on its own python -m pytest test/distributed/_composable/fsdp/<file>.py spin fixlint -- --take RUFF,PYFMT <changed files> spin lint -- --take PYREFLY,RUFF,PYFMT <changed files> ``` Results (B200, this revision): - flex_shard suite (4 GPUs): 146 tests and 23 subtests pass. - FSDP2 suite (`test/distributed/_composable/fsdp`, 4 GPUs): 440 passed, 8 skipped (5 need 8 GPUs), 1 failed: `test_fully_shard_alloc_from_pg`, which also fails without this stack: it asserts that NCCL logs no buffer registrations, and this host's NCCL logs them. - The other `fully_shard` users (replicate, 2D composability, PP composability on 8 GPUs, the memory tracker, DCP state dicts) pass. - torchtitan, which uses only `fully_shard`, at the pin of the PR below: the four configs that PR lists give bitwise-identical loss and grad_norm at every step, and the same validation losses, as FSDP2's own internals with the APIs of #203961. - Lint is clean but for a pyrefly error in `torch/_dynamo/variables/torch.py` that main also has. ghstack-source-id: 08a49d1 Pull-Request: #203990
This was referenced Nov 10, 2026
Draft
[FSDP2] Run fully_shard on the FlexShard engine runtime; delete FSDPParamGroup (AI-assisted)
#203764
Draft
weifengpy
added a commit
that referenced
this pull request
Nov 11, 2026
…fers (copy of #199726, AI-assisted) ## BC-breaking? > Yes, for private FSDP internals only: > - `AllGatherResult` gains the required field `all_gather_input_outer_sizes`, so building it without that field, positionally or by keyword, or unpacking it into 6 names fails. > - `foreach_all_gather` gains a positional `layout` argument, and `foreach_all_gather_copy_out` loses `all_gather_output_fn=`, gains `persistent_buffers` and returns the group's buffers, which a wrapper must return too. Replacements patched in with the old signatures raise a `TypeError`. > - `FSDPParamGroup._all_gather_output_fn`, added in 2.15, is removed; reading or assigning it raises an `AttributeError` that points to `set_all_gather_layout(DefaultAllGatherLayout(fn))`, which takes #200034's callback signature. Code that checks for the hook should check for `FSDPModule.set_all_gather_layout` instead. > - Multi-rank parameter groups without any all-gather payloads raise a `ValueError` instead of an `IndexError`. ## Summary (human written only) <!-- Author: add your own summary line here before marking this PR ready for review --> ## Agent details (if applicable) > A copy of #199726 at its 2026-11-08 revision (ghstack orig fca5398), the base of the FlexShard stack above, so that the stack does not depend on #199726's later revisions or its review state. Not for review or landing: review and land #199726. The rest of this description is #199726's at that revision. > > AI-assisted draft prepared with Claude Code for the all-gather contract discussion on #188276. Of the three alternatives, option 3 was chosen over #199720 (option 1) and #199721 (option 2). > > This adds the contract that a custom all-gather backend uses to pack its own input and produce its own output layout, e.g. parameter-contiguous output. The interface shape comes from #188276 by wuyl1 and inkcherry: `AllGatherLayout.prepare`, `prepare_output`, where returning `None` falls back to the default layout for that call, `copy_in` and `finalize_outputs`, with tensor-only metadata types. Per-payload `outer_sizes` from #197204 replace its `shard_dim` and `padded_sharded_size`. `init_unsharded_param` honoring the output's storage offset, so that parameters can view a layout's shared buffer, also comes from #188276. > > FSDP owns the storage behind the parameters' all-gather outputs, following FlexShard's placement contract. On a parameter group's first unshard, the layout's finalize allocates persistent buffers in any layout it chooses and returns `AllGatherOutputs(tensors=..., buffers=...)` with outputs that view them; FSDP checks every output's size, dtype and buffer before adopting any. The group frees the buffers on reshard unless its parameters keep their unsharded storage (#198417), re-allocates them to their recorded storage sizes before every later finalize, and checks that the layout returned the outputs it was given, so `reshard_after_forward` keeps saving parameter memory with custom layouts. All-gather extensions' inner tensors that view the buffers are left to the group. The metadata types are keyword-only, so adding fields with defaults does not break layouts that build them. > > FSDP treats an unshard as the group's first while none of its parameters has all-gather outputs. An all-gather extension without payloads has none even after adoption, so checking only the first parameter would make every later unshard of a group that starts with one re-adopt instead of refilling, which raises for a delegating layout and leaves the other parameters on stale buffers for a layout that allocates new ones. Such groups could not all-gather on main: `_get_all_gather_input_metadatas` took the all-gather dtype from the first payload of the group's first parameter, so with more than one shard rank they raised an `IndexError` on their first unshard, with any layout. The dtype now comes from the first payload of any parameter. A group whose parameters all lack payloads raises a `ValueError` instead, since there is nothing to all-gather and the copy-out cannot view an empty buffer. > > FSDP checks the buffers a layout returns before adopting them: reshard frees and re-allocates each buffer's whole storage on the current stream, so each must have resizable storage of its own on the collective's device, not the collective's input or output, which come from another stream's pool. `prepare` and `copy_in` run on the copy-in stream, so on CUDA and XPU adoption also records the current stream on each buffer: a no-op for buffers that finalize allocated, it keeps one allocated on the copy-in stream from being reused by the next collective while compute still reads it. FSDP gives the layout copies of its lists and checks the outputs against its own sizes and dtypes, so a layout cannot change them behind those checks. A layout's comm records the parameter group whose layout installed it, so installing that layout or its comm on another group raises while the layout stays installed; a deep copy is a separate instance. `set_all_gather_layout` rejects anything but an `AllGatherLayout`, every setter raises a `RuntimeError` when a group's comm or layout cannot be replaced, including `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` under a custom layout, and a rejected copy-out orders the all-gather streams after itself and frees what a refill re-allocated, the group's buffers or its parameters' outputs. > > `set_all_gather_layout` is the only way to install a layout, and it makes #197701's native all-gather copy usable as `DefaultAllGatherLayout(all_gather_output_fn_with_native_copy)`. A layout whose output needs a specific collective names that comm's type as `comm_type`. The comm is installed with `set_custom_all_gather`, before the layout, and FSDP passes it each call's layout metadata as `output_metadata` (`None` for a call with rank-major output), so the comm keeps no per-call state and one instance can serve any number of parameter groups. While such a layout is installed, `set_custom_all_gather`, `set_symm_mem_for_comm` and `set_allocate_memory_from_process_group_for_comm` reject comms of other types, and replacing the layout keeps the installed comm. Only comms of a layout's `comm_type` receive `output_metadata`, so existing custom comms keep their signature. The comm setters work at any time, as on main, since comms keep no per-call state and own no outputs. `set_all_gather_layout` changes layouts only between iterations: it cannot replace a layout while an all-gather is pending or parameters are unsharded, nor after outputs view a custom layout's buffers, since only the layout that created those outputs can refill them. The setters check every parameter group before changing any. FSDP calls the installed layout's `prepare` on every multi-rank all-gather, then the copy-in it returns. The chosen layout's `finalize_outputs` finishes a call that `prepare` returned metadata for; a call without metadata has rank-major output, which FSDP copies out with that layout's `output_fn` (`None`, as on `AllGatherLayout`, for FSDP's default copy-out). FSDP thus dispatches on the contract's metadata, not on the layout's type, and a `DefaultAllGatherLayout` subclass can override `copy_in`. A fast path that inlined the default layout measured within noise of this in wall time on a CPU-bound unshard and reshard benchmark, though it ran about 2% fewer instructions per group, so there is none. > > This leaves out #188276's backend-owned outputs, its parameter-contiguous zero copy (views into the collective buffer and FSDP's eligibility check for them) and its per-group owner binding, along with their tests, so that they remain #188276's feature on top of this contract. #199872 and #199873 propose that split to MORI as a diff against a clone of #188276. Without owner binding, `AllGatherLayout` documents that a layout that keeps per-call state must not be shared across parameter groups, and the setter asks for a separate instance on each module. It relies on #199729 (landed), which discards a pending post-forward all-gather in `_to_sharded` and adds the `_wait_all_gather` helper. > > Review `_all_gather_layout.py` first, then the all-gather and buffer re-allocation in `_fsdp_collectives.py`, the frees in `_fsdp_param_group.py`, the storage flag, inner-tensor filter and storage offset in `_fsdp_param.py`, and the setters in `_fully_shard.py`. The tests add a parameter-contiguous layout whose comm reorders a rank-major all-gather. Its training parity cases, on 4 threads plus three NCCL cases, check that one FSDP-owned buffer backs each group, that reshard frees it unless storage is kept, also right after forward and over the post-forward mesh, and that refills take one copy; cases whose first unshard falls back check parity with per-parameter buffers. Unit tests cover the rejected outputs, buffers and refills, a delegated copy-out of mixed payload dtypes, a delegating Shard(1) layout on groups that start with an extension without payloads, whose default-layout reference also covers the `IndexError`, a `copy_in` override, an extension under a shared buffer whose layout falls back to rank-major after a custom first unshard, next to one with an inner tensor of its own, custom layouts under inference mode, recovery after a rejected result or refill, and the setter rules. This PR installs the native all-gather copy with `set_all_gather_layout` where #197701's tests set the private hook, and also turns it on in the mixed-precision tests. > > Test Plan (local build, B200 GPUs): > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestAllGatherLayouts -k TestAllGatherLayoutCopyOut -k TestFullyShardAllGatherLayoutSetters -k TestFullyShardLayoutParity > python test/distributed/_composable/fsdp/test_fully_shard_comm.py > python test/distributed/_composable/fsdp/test_fully_shard_extensions.py > python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context > python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k keep_unsharded_storage > python test/distributed/_composable/fsdp/test_fully_shard_memory.py > python test/distributed/_composable/fsdp/test_fully_shard_compile.py > python test/test_public_bindings.py -k test_correct_module_names > ``` > All pass on this revision except `test_fully_shard_alloc_from_pg` in the full comm file, which also fails on main on this machine, where NCCL registers a buffer before process-group allocation is enabled. The comm file had 193 passed and 2 skipped; the other suites passed: extensions 23, mixed precision 32, training 4, state dict 1, memory 7, compile 7, public bindings 1. Co-authored-by: wuyl1 <[email protected]> Co-authored-by: inkcherry <[email protected]> ghstack-source-id: 439b0de Pull-Request: #204282
weifengpy
added a commit
that referenced
this pull request
Nov 11, 2026
…flex_shard API (AI-assisted) - [ ] Passes lint (`spin fixlint`) - [x] Added/updated tests - [ ] Updated documentation where applicable - [ ] Included benchmark results ## Linked issue or supporting maintainer > No linked issue; the author has write access. Stacked on #204282, a copy of #199726, and #203961 (the `FSDPModule` APIs torchtitan needs, independent of this PR); the PR above runs `fully_shard` on this engine. ## BC-breaking? > No. This adds a private package and an experimental module; nothing existing changes. ## Summary (human written only) > _Placeholder for the author._ ## Agent details (AI-generated) Drafted with an AI assistant at the author's request. This is a draft for CI and discussion, not ready for review or merge. CI is deferred with `[no-ci]` because the PR above runs CI on the whole stack. **What.** Moves the FlexShard engine from meta-pytorch/flex_shard (main d6bb546) into `torch.distributed.fsdp._flex_shard` and exposes its frontend as the experimental public module `torch.distributed.fsdp.experimental.flex_shard`. `flex_shard` shards parameters as plain `torch.Tensor` local shards with sharding metadata, and each bucket of parameters names its own placement (`Shard`, `BlockShard`, `BucketedBlockShard`, `BucketedOwned`, `MixedBucketPlacement`, ...). **How.** The move is mechanical. Imports are rewritten to the core package. The FP8/MXFP8 blockwise placements stay in the flex_shard repo, and `MixedBucketPlacement` gets a registry so that the repo can register its quantized member types. The repo's tests move to `test/distributed/_composable/flex_shard`, with their helpers in `torch/testing/_internal/distributed`. The experimental module reports itself as the `__module__` of the names it re-exports, as `torch.distributed.fsdp` does for FSDP2's, and `test_testing.py`'s import check skips the two modules that need the optional `spmd_types` and `triton` packages. At about 21.7k added lines this is far over the 1,500-line PR limit; landing it would mean splitting it. **Review order.** `placement_contract.py` (the prepare/run/finish contract every placement implements), `bucket_storage.py` (one byte buffer per bucket, laid out by its placement), `placements/shard.py` (FSDP-style `Shard(dim)` with FSDP's native copy ops), `bucket_comm.py` and `bucket_runtime.py` (flex_shard's hook-driven scheduler), then `flex_shard.py` and the experimental re-export module. **Known gaps.** Lint passes for the files only this PR touches; the engine files the PR above also changes (`bucket_runtime.py`, `bucket_comm.py`, `placement_contract.py`, `placements/shard.py`, `placements/utils.py`) get their lint fixes there. Most pyrefly errors in the moved code are silenced with `# pyrefly: ignore` rather than fixed. ### Test Plan ``` python -m pytest test/distributed/_composable/flex_shard/<file>.py # each file on its own, 4x B200 python -m pytest test/test_public_bindings.py -k test_correct_module_names spin lint -- --take PYREFLY,RUFF,PYFMT,FLAKE8,MYPY,TEST_LINTER,TESTOWNERS,TEST_HAS_MAIN,CODESPELL <changed files> ``` Every file passes except `test_flex_shard_fsdp2_parity.py::test_matches_fully_shard_with_head_called_twice`, which fails the same way in the flex_shard repo against this torch build: it expects FSDP2's older post-backward behavior for a module called twice in one forward. With the PR above applied, the suite reports 140 passed and that failure. `test_correct_module_names` passes. `test_testing.py`'s import check, run over `torch/distributed/fsdp` with `spmd_types` hidden, passes; the full check needs packages this host lacks (e.g. `tabulate`). These runs used an earlier revision of #199726 (aad1e3c). The stack was then cherry-picked onto the revision that #204282 copies, without conflicts; that revision changes only `_fully_shard.py` and `test_fully_shard_comm.py`. ghstack-source-id: e15e938 Pull-Request: #203763
weifengpy
added a commit
that referenced
this pull request
Nov 11, 2026
…aramGroup (AI-assisted) - [x] Passes lint (`spin fixlint`) - [x] Added/updated tests - [ ] Updated documentation where applicable - [x] Included benchmark results ## Linked issue or supporting maintainer > No linked issue; the author has write access. Stacked on #204282, a copy of #199726: the PR below moves the FlexShard engine into core, and the one below that adds the `FSDPModule` APIs (#203176, #203177) that torchtitan now uses instead of FSDP2's private state. The PR above makes `flex_shard` take `fully_shard`'s policies and DTensor's `Shard`. ## BC-breaking? > No change to public APIs (`fully_shard`, `FSDPModule`, `share_comm_ctx`, the policies, the comm and layout hooks). Numerics match the previous internals bitwise in the tests below. Private internals are removed: `FSDPCommContext`, `RegisterPostBackwardFunction`, `foreach_all_gather`/`foreach_reduce`, and `FSDPParam`'s storage methods (`to_sharded`, `to_unsharded`, ...). `FSDPMeshInfo.reduce_scatter_process_group` is gone too: the engine's storage keeps the separate reduce-scatter group. `fsdp_state._fsdp_param_groups` now holds engine buckets (`FullyShardBucket`), which keep `fsdp_params` and `mesh_info`; the single-group `_fsdp_param_group` property and the group attributes that only tests and `fsdp2_mem_tracker` read (`is_sharded`, `_all_gather_buffers`, `_reduce_scatter_process_group`, ...) are gone, and those read the bucket's engine state (`bucket.bucket`, `bucket.storage`, `bucket.all_gather`) instead. `_fsdp_param_group.py`, `FSDPState._modules_to_run_forward` and the group state that torchtitan's lifecycle helpers wrote are gone: torchtitan uses the `FSDPModule` APIs of the PR two below, and this repo's torchtitan CI pin moves to the torchtitan commit that does. FSDP's comm settings (`set_allocate_memory_from_process_group_for_comm`, `set_symm_mem_for_comm`) now also replace each other's comms, which they refused before; a custom comm still makes them raise. ## Summary (human written only) > _Placeholder for the author._ ## Agent details (AI-generated) Drafted with an AI assistant at the author's request. This is a draft for CI and discussion, not ready for review or merge. **What.** `fully_shard` now runs on one engine, the FlexShard runtime that `flex_shard` uses (`BucketRuntime`, `BucketCommContext`, `ShardedBucketStorage`, the `Shard` placement). Each `fully_shard` call becomes a `FullyShardBucket` per mesh: its parameters live in one uint8 storage, and its runtime schedules the unshard, reshard, prefetch and gradient reduction. All buckets under a root join one `BucketCommContext` at lazy init. `FSDPParam` stays as the DTensor representation of a parameter (a `ParamRepresentation` adapter), and `FSDPState` keeps the frontend duties (lazy init, the root pre-forward, input and output casts, the `FSDPModule` setters). `FSDPParamGroup`, its scheduler and the `foreach_*` collectives are deleted, so `fully_shard` and `flex_shard` share one scheduler, one set of scheduling rules, and one all-gather data path. **Review order.** 1. `_flex_shard/bucket_storage.py`, `bucket_runtime.py`, `bucket_comm.py`: what the runtime gained. FSDP2's semantic rules are the runtime's rules for both frontends: `reshard_after_backward` also holds in syncing backwards; a forward that no backward follows reshards only as `reshard_after_forward` says; the end of backward runs the post-backward of buckets backward did not reach, and `finalize_backward` reshards buckets that kept their parameters if they now reshard after backward; gradient dtypes are chosen in the forward. A bucket whose forward ran with grad since its last reduction reduces at the next syncing backward even if this rank's backward did not use its outputs, so that ranks that use them differently issue the same collective; a bucket whose forward did not run reduces nothing, as in FSDP2. FSDP2's scheduling is the runtime's only scheduling: the post-backward runs after each forward call's backward, the backward prefetches the previous bucket in post-forward order, and a prefetch is kept until its bucket uses it. `flex_shard` exposes `set_reduce_scatter_unused_params`. As in FSDP2, a backward prefetch skips a bucket that does not unshard in backward (`set_unshard_in_backward(False)`, e.g. torchtitan's embeddings): nothing would take it, so it stayed in flight into the next forward, which then used parameters gathered before the optimizer step (and a CUDA graph capture of that forward failed on its event). The other additions serve both frontends: the `ParamRepresentation` interface, the post-forward reshard over a smaller group (int `reshard_after_forward`), the HSDP all-reduce and partial reduces (`set_requires_all_reduce(False)`), `all_reduce_hook`, CPU offload (the runtime copies reduced gradients to the CPU, overlapped as in FSDP2), manual and async `finalize_backward`, `set_is_last_backward`, and context sharing (`share_comm_ctx`). Modules with buckets on several meshes retire pending reductions once, so that their reductions overlap, as FSDP2's per-module rule does. With manual finalization (pipeline schedules), the end of each backward still runs the post-backward of buckets that do not sync gradients, as FSDP2's final callback does, which widens their kept gradients before the next microbatch accumulates into them. A `PartialBackward` on the context implements `FSDPModule.partial_backward`: its buckets keep their parameters unsharded, accumulate their gradients without reducing them, complete the group's forward at each call, and neither prefetch nor finish other buckets when one of their backwards ends. `BucketCommContext.end_backward` is the end-of-backward step, which the scope's exit runs itself when no outer backward follows. As in FSDP2, a bucket without gradients now reduces nothing also when its reduce-scatter would go into an HSDP partial output (`set_requires_all_reduce(False)`); it reduce-scattered zeros before. 2. `_flex_shard/placements/shard.py`, `utils.py`: the `Shard` placement takes FSDP2's comm objects (custom all-gather and reduce-scatter, symmetric memory), its reduce-scatter input function and divide-factor rules, and reduces through `dist.reduce_scatter_single`. `_flex_shard/placements/shard_all_gather.py` and `_flex_shard/all_gather_layout.py`: every bucket of either frontend all-gathers through one pipeline, the `Shard` placement's. Each parameter contributes its padded local shard, read from the bucket storage, or the inputs that its representation returns (`ParamRepresentation.all_gather_inputs`: an all-gather extension's payloads, or the data of a tensor subclass with storage of its own), which are checked against the sharding. The bucket's `AllGatherLayout` packs them and finalizes the gathered output into each parameter's all-gather outputs, which persist across unshards in the bucket's `ShardAllGather` (the state that a placement keeps per bucket, `Placement.new_bucket_state`), and the representation builds the unsharded parameter from them (`post_all_gather`). The layout contract, `AllGatherInput` and the copy-out moved here from `_fully_shard`; `torch.distributed.fsdp.experimental` still exports them. The layout declares what the engine needs to know, so no code checks its type: FSDP's native copies (the bucket storage as the collective's input when it holds every local shard in the gather dtype, a direct cast into the gather buffer otherwise, and one `fsdp::_all_gather_copy_out_`) run instead of the layout's hooks for a layout that says they implement them (`AllGatherLayout._uses_native_copies`: a `DefaultAllGatherLayout` with the default copy-in and copy-out or `all_gather_output_fn_with_native_copy`), and outputs are allocated for custom output only for a layout that may produce it (`_rank_major_output_only`). Parameters sharded unevenly on a nonzero dim (#203465), in both frontends: each rank stores its chunk compactly at the start of a slot of the first chunk's size, so the ranks' slots line up and the all-gather needs no padding copy; the copy-out moves the full chunks and the short chunk of each such parameter in two copies, one parameter at a time, since the native one-kernel copy-out reads every slot as rows of one padded layout. The reduce-scatter pads and reorders their gradients (`_pad_and_reorder_by_rank`), and the runtime copies their gradient shards compact after the HSDP all-reduce and the all-reduce hook, so that every rank's gradient has its parameter's contiguous strides. Under a custom layout, such a parameter is all-gathered with its rows padded, as FSDP2 does, gets padded outputs like any other, and FSDP copies its data into storage of its own that backs the unsharded parameter, at every unshard (the PR below raises for this case; this PR deletes that path). 3. `_fully_shard/_fsdp_engine.py`, `_fsdp_param.py`: `FullyShardBucket` (the bucket's storage, mixed precision, the `FSDPModule` setters) and `FSDPParamRepresentation` (DTensor parameters, gradient casts and accumulation into DTensor `.grad`, deferred upcasts, and the calls into an extension's `fsdp_pre_all_gather` and `fsdp_post_all_gather`). `FSDPParam` drops its all-gather outputs and post-forward state (1,646 to 1,321 lines), and allocates no storage: the bucket allocates its storage once and each `FSDPParam` copies its shard into its slot (`FSDPParam.bind_storage`). After `to_empty`, `load_state_dict(assign=True)` or a dtype change, the bucket copies the parameters' new data into its storage, which it reallocates only if their dtypes or device changed; while `to_empty` has materialized only some modules of a group, each parameter keeps its own local tensor. Only tensor-subclass parameters and parameters with an all-gather extension at `fully_shard` keep storage of their own. A parameter tied after `fully_shard`, as torchtitan's decoder re-ties its embedding and output weights after meta-device init, has an `FSDPParam` per module and so a slot per `FSDPParam`: the parameter views the first slot, and each unshard copies it into the others (`ParamRepresentation.before_unshard`). A parameter counts as replaced only if its local tensor is no longer the slot the bucket bound it to, so an all-gather extension patched onto a local tensor stays, also on a rank whose shard is empty. 4. `_fully_shard/_fsdp_state.py`, `_fully_shard.py`, `_fsdp_init.py`: the frontend on the engine; `_fsdp_state.py` drops from 764 to 453 lines. `set_unshard_in_current_stream` (#202343) sets the engine's option, as `_set_unshard_async_op` does. `FSDPStateContext.is_last_backward` is a property that sets the engine context's `wait_reductions_at_backward_end`. Under functorch transforms, outputs get a pre-backward autograd function, as before. `partial_backward`, `complete_grouped_forward`, the setting getters and the sharded-storage methods of the PR two below run on the engine (`FSDPState._partial_backward`, `_fsdp_engine.first_storage`, `free_sharded_params`, `restore_sharded_params`), and `set_all_reduce_hook` sets the hook of every bucket of a module with several meshes. 5. `torch/_tensor.py`: `Tensor.__deepcopy__` and `__reduce_ex__` recognized wrapper subclasses by `data_ptr() == 0`, which fails for a wrapper whose storage offset is nonzero: `DTensor.from_local(x[4:8])` could not be deep-copied or saved. Sharded parameters now view their bucket at nonzero offsets, so `copy.deepcopy(model.state_dict())` and `torch.save` hit this. The check now compares `data_ptr()` with the offset. This fix stands on its own and can move to a separate PR. 6. `torch/_inductor/lowering.py`, `comm_lowering.py`: Inductor lowers FSDP2's `fsdp::` ops and the symmetric-memory ops defined in Python, which were registered only as a side effect of Dynamo importing `_fsdp_param_group`, so importing `torch._inductor` first failed. Inductor now imports them itself. 7. Deletions and ports: `_fsdp_param_group.py`; the state torchtitan's lifecycle helpers wrote or read (`FSDPState._modules_to_run_forward`, the bucket's `post_forward_mesh_info`, `reduce_grads`, `all_reduce_grads` and `reshard_after_backward` properties, `_post_backward_pending`, `_partial_reduce_output` and `reshard()`); `_fsdp_collectives.py` but its comm classes: the Python-defined `fsdp::` ops move to the engine (`_flex_shard/ops.py`), which the modules that call them import, and FSDP2's default reduce-scatter input function, its copy-in and the divide-factor helpers go, since the engine's `Shard` implements them (`set_reduce_scatter_input_fn(None)` restores the engine's copy-in); the dynamo special case for `FSDPParamGroup.use_training_state` and its unused `FSDP_TRAINING_STATE` guard; `fsdp2_mem_tracker`, which now instruments each of a state's buckets; and the pipelining `share_comm_ctx` check. The moved engine code type-checks with pyrefly without ignores. 8. Tests. Tests that asserted on deleted internals now assert on the engine's equivalents with the same intent (event order, stream use, buffer lifetimes, collective counts). `TestFSDPCommContext`, `TestFullyShardCollectiveOps`, the dynamo `use_training_state` test and the `FSDP_TRAINING_STATE` guard serialization test are deleted with what they tested. `test_fully_shard_engine.py` checks that a group's parameters live in one bucket, meta-device init with `load_state_dict(assign=True)` and of grouped modules, deepcopy and save of the state dict, that no backward prefetch stays in flight for a bucket that does not unshard in backward, and that uneven `Shard(1)` weights all-gather on the engine's `Shard`, as their dtype and as bytes, matching an unsharded reference. `test_delegating_layout_uneven_shard_dim1` covers them under a custom layout, and `flex_shard` tests cover their training, storage slots and checkpoint layouts. Regression tests cover what this PR's first CI run found: importing Inductor first (`test_fully_shard_compile.py`), gradient dtypes chosen by each forward (`test_fully_shard_mixed_precision.py`), parameters tied after `fully_shard`, manual finalization widening kept gradients, and `complete_grouped_forward` ending a partial grouped forward (`test_fully_shard_training.py`). The PR two below's `TestFullyShardPartialBackward` and `TestFullyShardModuleMethods` run on the engine, checking the engine's state that the outer backward reads where they checked FSDP2's prefetch indices. `flex_shard` tests that relied on its old rules (a syncing backward always reshards; a forward without backward always reshards) now set `reshard_after_backward` on the last microbatch or reshard explicitly, as FSDP2 code does; new tests cover buckets whose forward did not run and the no-backward reshard rule; and `test_matches_fully_shard_with_head_called_twice`, which failed on the PR below, now passes and compares all-gathers as well as reduce-scatters. **Choices.** - One engine instead of keeping `FSDPParamGroup` on shared storage (an earlier revision of this PR): prefetch, reduction and stream management have one implementation. - One rule set instead of a `fully_shard` mode: FSDP2's rules, scheduling included, are the tested behavior. This changes `flex_shard` (experimental): its post-backward runs after each forward call's backward, its backward prefetch follows FSDP2's order, and `reshard_after_backward=False` now also keeps parameters unsharded through a syncing backward, so callers reshard before the optimizer step; a forward under `no_grad` keeps the parameters of buckets without `reshard_after_forward` unsharded, as FSDP2 does. - One all-gather pipeline instead of the engine's `Shard` next to a second placement for extensions and custom layouts: FSDP's native copies are what the default layout's copy-in and copy-out do, chosen by what the layout declares. The default copy-out of extension payloads becomes the native op too, with the same values. - FSDP's comm settings ask the comm whether they may replace it (`Comm._replaceable_by_fsdp`, which FSDP's own comms set and their subclasses inherit, as FSDP2's `isinstance` checks accepted them) instead of matching its type. - Participation by forward, not by backward: deciding by whether backward reached a bucket hangs models whose ranks use a bucket's outputs differently (`test_rank_dependent_unused_params`). - Implicit forward prefetch (FSDP2's learned order) stays: the engine's all-gathers wait on the current stream, so without it nothing overlaps. - Uneven `Shard(i>0)` chunks are stored compactly rather than as padded rows, so local tensors stay contiguous and the all-gather input needs no padding copy (FSDP2 pads on the copy-in); the cost is a per-parameter copy-out for buckets that hold such parameters. - FSDP2's errors are kept where users can hit them (int `reshard_after_forward` with DTensor-sharded parameters, `Shard(i>0)` divisibility for a reshard to a smaller mesh after forward, post-forward re-gathers with all-gather extensions, partial reductions with manual finalization). **torchtitan.** `.github/ci_commit_pins/torchtitan.txt` moves to f4546c7 (branch `weifengpy/fsdp-public-apis` of pytorch/torchtitan, draft PR pytorch/torchtitan#5946), the torchtitan change that replaces `fsdp_lifecycle.py` and the other private FSDP2 state torchtitan used (torchft's all-reduce hook, the RL weight sync's storage calls, tests of internals) with the APIs of the PR two below, and whose CPU-offload test reads `_fsdp_param_groups` instead of the single-group property that this PR removes. torchtitan's own CI needs a PyTorch nightly with that PR. **Benchmark.** Llama3-8B in torchtitan on 4x B200 (FSDP 4, seq 4096, bf16 parameters, CUDA graphs): 11,222 vs 10,591 tokens/s against the internals before this stack (+6.0%; mean of 2 runs each, median over steps 5-15), with peak memory 49.50 vs 50.22 GiB. Loss and grad_norm match bitwise. ### Test Plan ``` python -m pytest test/distributed/_composable/fsdp/<file>.py # each file on its own python -m pytest test/distributed/_composable/flex_shard/<file>.py python -m pytest test/distributed/_composable/test_replicate_with_fsdp.py test/distributed/_composable/test_replicate_mixed_precision.py \ test/distributed/_composable/test_replicate_training.py test/distributed/_composable/test_composability/test_2d_composability.py \ test/distributed/_composable/test_composability/test_pp_composability.py test/distributed/_tools/test_fsdp2_mem_tracker.py \ test/distributed/test_composability.py test/distributed/checkpoint/fsdp/test_fsdp_dsd.py test/distributed/checkpoint/test_state_dict.py python -m pytest test/distributed/tensor/test_dtensor.py -k "save_load or deepcopy" python -m pytest test/test_serialization.py test/test_subclass.py spin fixlint -- --take RUFF,PYFMT <changed files> spin lint -- --take PYREFLY,RUFF,PYFMT,FLAKE8,MYPY,TEST_LINTER,TESTOWNERS,TEST_HAS_MAIN,CODESPELL <changed files> # torchtitan at the pin of this repo's CI, in its repo root, for each config below python scripts/loss_compare.py . . --baseline-module=<module> --baseline-config=<config> --test-module=<module> \ --test-config=<config> --metrics=loss,grad_norm --steps=<n> --baseline-ngpus=<g> --test-ngpus=<g> --export-result=<file> ``` This revision is rebased onto main at 49db559, which brings #203465 and #202343; the numbers below come from a build of that commit. - FSDP2 suite (`test/distributed/_composable/fsdp`, 4x B200): 440 passed, 8 skipped (5 need 8 GPUs), 1 failed, including #203465's uneven-sharding tests and the partial-backward and module-method tests of the PR two below. That PR passes its version of the suite on the same build (436, with the tests of internals that this PR deletes). The failure, `test_fully_shard_alloc_from_pg`, fails on both: it asserts that NCCL logs no buffer registrations, and the NCCL on this host logs them. - flex_shard suite (4x B200): 144 tests and 23 subtests pass. - CPU time of `fully_shard`'s default unshard and reshard, which now go through the one all-gather pipeline: 1590 µs per group of 100 parameters, against 1620 µs for the revision before (`FSDPModule.unshard()` and `reshard()` over 30 groups on 2 GPUs, median of 5 rounds; rerunning the old revision gives 1621 µs). - The other `fully_shard` users above (replicate, 2D/3D composability with PP, the memory tracker, DCP state dicts; 4x and 8x B200): all pass (`test_pp_composability.py`: 26 passed on 8 GPUs). `test_schedule_multiproc.py` does not import on this host (`model_registry`), with or without this PR. - `test_dtensor.py -k "save_load or deepcopy"` passes; `test_serialization.py` has the same two failures with and without the `torch/_tensor.py` change (`TestOldSerialization.test_serialization_container*`), and `test_subclass.py` passes. - torchtitan (weifengpy/torchtitan-flexshard 79fd6d5, `debug.deterministic=True`, seed 42, 20 steps, on an earlier revision of this PR; the CI-pin configs below were rerun on this one): loss and grad_norm are bitwise identical to the internals before this stack at every step for 9 configs: the Llama3 debug model with FSDP, HSDP and TP x FSDP, and the DeepSeek-V3 debug model with and without EP, on 4 and 8 GPUs, plus Llama3-8B. - torchtitan at the new pin: the four integration tests that failed in this PR's first CI run (SFT with chunked loss, higher-precision RMSNorm with QK norm on qwen3 with TP 2, validation with TP x CP x PP, shared train and eval accelerator graphs) give bitwise-identical loss and grad_norm at every step, and the same validation losses, against the PR two below, and that one against torchtitan's main (with `fsdp_lifecycle.py`). B200 has no FA4, so the qwen3 and muse_glimmer configs ran with flex attention instead of varlen. torchtitan's chunked-loss, accelerator-graph, CPU-offload and MXFP8/NVFP4 FSDP unit tests pass on both PRs, except one test that needs FA4. ghstack-source-id: 2189bd0 Pull-Request: #203764
weifengpy
added a commit
that referenced
this pull request
Nov 11, 2026
…icies and DTensor's Shard (AI-assisted) - [x] Passes lint (`spin fixlint`) - [x] Added/updated tests - [x] Updated documentation where applicable - [ ] Included benchmark results ## Linked issue or supporting maintainer > No linked issue; the author has write access. Top of the stack on #204282, a copy of #199726: the PR below runs `fully_shard` on the FlexShard engine. ## BC-breaking? > Yes, for the experimental `flex_shard` API only: > - `torch.distributed.fsdp.experimental.flex_shard` no longer exports `MixedPrecisionPolicy`, `OffloadPolicy` and `Shard`: use `torch.distributed.fsdp.MixedPrecisionPolicy`, `OffloadPolicy` and `CPUOffloadPolicy`, and `torch.distributed.tensor.Shard`. > - `MixedPrecisionPolicy.param_dtype_overrides`, a map from parameter FQN to dtype, becomes `fully_shard`'s `param_dtype_override_fn`, a function of the parameter. > - A bucket now casts the floating-point inputs of the modules it hooks to `param_dtype` (`cast_forward_inputs=True` by default) and their outputs to `output_dtype`, as `fully_shard` does. `cast_forward_inputs=False` keeps the old behavior. > - `get_placements` reports DTensor's `Shard(dim)` for a parameter sharded on a dim. ## Summary (human written only) > _Placeholder for the author._ ## Agent details (AI-generated) Drafted with an AI assistant at the author's request. This is a draft for CI and discussion, not ready for review or merge. **Problem.** `flex_shard` had its own `MixedPrecisionPolicy`, `OffloadPolicy` and `Shard`, next to `fully_shard`'s policies and DTensor's `Shard`: two classes for each concept, with different fields (FQN-keyed dtype overrides against a function of the parameter), so a `fully_shard` configuration could not move to `flex_shard` as it is. flex_shard's policy also lacked the module-boundary casts (`cast_forward_inputs`, `output_dtype`), left as a TODO. **What.** - `BucketSpec.mp_policy` is `fully_shard`'s `MixedPrecisionPolicy`. `param_dtype`, `param_dtype_override_fn` and `reduce_dtype` set the bucket's parameter dtypes, with the override function called once per parameter, as in `fully_shard`. `cast_forward_inputs` and `output_dtype` cast the inputs and outputs of the modules that the bucket hooks: inputs before the buckets' pre-forward hooks, outputs after their post-forward hooks and the root's completion of grouped forwards, in the order of FSDP2's state hooks. The buckets that hook one module must cast alike, or `flex_shard()` raises. - `BucketSpec.offload_policy` is `fully_shard`'s `OffloadPolicy`, and `CPUOffloadPolicy` works as in `fully_shard` for buckets whose placements support it (`Placement.supports_cpu_offload`: `Shard`, but not the block and mixed placements, for which `flex_shard()` raises): the bucket keeps its sharded parameters and their gradients on the CPU, pinned by default, all-gathers onto the accelerator, and the runtime copies reduced gradients back to the CPU, as it does for `fully_shard`. Offloaded buckets are eager-only, and `relayout_bucket` rejects them. - The `fsdp2_compatible` check asks the placements whether their collectives match FSDP2's (`Placement.matches_fsdp2_collectives`: `Shard`, not a mixed bucket's members) instead of checking for the `Shard` type. - A placement function may return DTensor's `Shard(dim)`, which `flex_shard()` and `relayout_bucket()` take as the engine's `Shard(dim)`, and `get_placements` reports the engine's `Shard` as DTensor's (`Placement._api_placement`). `make_shard_placement_fn` and `per_param_placements` return DTensor's `Shard`. The engine's class keeps its name in the private `_flex_shard.placements`, where `fully_shard` also uses it. **Choices.** - DTensor's `Shard` maps to the engine's at the API boundary rather than being the engine's class: DTensor's `Shard` is a C++ class, and the engine's `Placement` carries the storage layout and collective lifecycle that DTensor placements do not. - The casts are per hooked module, not per bucket, so a module's inputs are cast once however many buckets it starts. **Review order.** `bucket_storage.py` (the policy fields and dtype resolution), `bucket_runtime.py` (the casting hooks), `flex_shard.py` (validation and relayout), `placements/shard.py` and `placement_contract.py` (the `Shard` mapping and the placements' declarations), `experimental/flex_shard.py`, then tests: `test_param_dtype_override_fn` replaces the FQN-override test, `test_mixed_precision_casts_at_hooked_modules` covers the casts and the conflict check, the FSDP2 parity test now gives both frontends one policy class and DTensor's `Shard`, `test_cpu_offload` trains an offloaded model against one on the accelerator, with microbatches that accumulate gradients without sync, and `test_cpu_offload_requires_placements_that_support_it` replaces the test that `CPUOffloadPolicy` is rejected. ### Test Plan ``` python -m pytest test/distributed/_composable/flex_shard/<file>.py # each file on its own python -m pytest test/distributed/_composable/fsdp/<file>.py spin fixlint -- --take RUFF,PYFMT <changed files> spin lint -- --take PYREFLY,RUFF,PYFMT <changed files> ``` Results (B200, this revision): - flex_shard suite (4 GPUs): 146 tests and 23 subtests pass. - FSDP2 suite (`test/distributed/_composable/fsdp`, 4 GPUs): 440 passed, 8 skipped (5 need 8 GPUs), 1 failed: `test_fully_shard_alloc_from_pg`, which also fails without this stack: it asserts that NCCL logs no buffer registrations, and this host's NCCL logs them. - The other `fully_shard` users (replicate, 2D composability, PP composability on 8 GPUs, the memory tracker, DCP state dicts) pass. - torchtitan, which uses only `fully_shard`, at the pin of the PR below: the four configs that PR lists give bitwise-identical loss and grad_norm at every step, and the same validation losses, as FSDP2's own internals with the APIs of #203961. - Lint is clean but for a pyrefly error in `torch/_dynamo/variables/torch.py` that main also has. ghstack-source-id: 08a49d1 Pull-Request: #203990
This was referenced Nov 14, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
BC-breaking?
Summary (human written only)
Agent details (if applicable)
Co-authored-by: wuyl1 [email protected]
Co-authored-by: inkcherry [email protected]