Skip to content

[FSDP2] Run fully_shard on the FlexShard engine runtime; delete FSDPParamGroup (AI-assisted) - #203764

Draft
weifengpy wants to merge 15 commits into
gh/weifengpy/236/basefrom
gh/weifengpy/236/head
Draft

weifengpy wants to merge 15 commits into
gh/weifengpy/236/basefrom
gh/weifengpy/236/head

Conversation

@weifengpy

@weifengpy weifengpy commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Screenshot 2026-11-06 at 1 20 13 PM
  • Passes lint (spin fixlint)
  • 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 #203763, which moves the FlexShard engine into core, on #204282, a copy of #199726, and at the bottom #203961, which 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. AllGatherInput moves to the engine and stays importable from _fsdp_api. _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, and _fsdp_api still exports AllGatherInput. As in [FSDP2] Add an all-gather layout contract with FSDP-owned buffers #199726's latest revision, a custom layout carries its own comm, which the engine calls with the layout's output_metadata, and FSDP's comm setters raise ValueError under a custom layout. 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 ([FSDP2] Uneven nonzero-dimension sharding #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. Parameters that load_state_dict(assign=True) replaces mark their bucket, and its next unshard copies their data into the storage, as FSDP2 read them per parameter (test_load_state_dict_assign_after_forward).
  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 ([FSDP2] Add public 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/_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.
  6. 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.
  7. 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.
  • An empty list to set_modules_to_forward_prefetch or set_modules_to_backward_prefetch keeps the default prefetch, as in FSDP2, where it set no explicit prefetch; the engine's own setters take an empty list as no prefetch, so the frontend passes None for it. test_set_modules_to_prefetch_empty_list_keeps_default checks this, and also passes on FSDP2's internals.
  • 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).

Rebase. This revision is on main bba8f39. Main changed no FSDP2 code since 2b47752, and the rebase conflicted only in the torchtitan pin. What main changed in FSDP2 between 49db559 and 2b47752 runs on the engine: set_custom_all_reduce (#203312) sets the bucket's all-reduce comm, which the engine calls by keyword, and raises for modules with several groups or without a replication mesh, as main does; a one-rank group's packed reduce-scatter buffer is FSDP's own, not the comm's (#203556, skip_reduce_scatter), and the engine reuses it as the output; the engine divides only by the pre- and post-divide factors, so the double division that #203693 fixed does not arise, and its test stays. Main's #203963 fixed deepcopy and save of wrapper subclasses at nonzero storage offsets, so this PR no longer changes torch/_tensor.py.

torchtitan. .github/ci_commit_pins/torchtitan.txt moves to d07461d (branch weifengpy/fsdp-public-apis of pytorch/torchtitan, draft PR pytorch/torchtitan#5946, rebased onto torchtitan's main a419690, where the RL weight sync moved to torchtitan/rl/generator/model.py), 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 #203961, and whose CPU-offload test records the offload policy that torchtitan passes to fully_shard instead of reading FSDP2's parameter group. 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. (Measured on the previous base, 49db559.)

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"
spin fixlint -- --take RUFF,PYFMT <changed files>
spin lint -- --take PYREFLY,RUFF,PYFMT,FLAKE8,MYPY,TEST_LINTER,TESTOWNERS,TEST_HAS_MAIN,CODESPELL <changed files>
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>

The numbers below come from builds of main bba8f39 with this stack: 4x GB300 (aarch64, CUDA 13.0) and 8x B200.

  • FSDP2 suite (test/distributed/_composable/fsdp, each file on its own, 4x B200): 456 passed, 8 skipped (they need 8 GPUs), 1 failed: test_fully_shard_alloc_from_pg asserts that NCCL logs no buffer registrations; the NCCL on these hosts logs them, so it fails on main too. [no-ci] [FSDP2] Add an all-gather layout contract with FSDP-owned buffers (copy of #199726, AI-assisted) #204282 below passes its version of the suite on the same build: 450 passed, including the tests of internals that this PR deletes, with the same alloc_from_pg failure.
  • flex_shard suite (4x GB300): 144 passed.
  • The other fully_shard users, at the top of the stack (4x GB300): replicate (5, 10, 16 passed), 2D composability (17), test_composability.py (22), the memory tracker (3) and DCP state dicts (6, 27) pass, and PP composability (26 passed) on 8x B200.
  • test_dtensor.py passes at the top of the stack (112 passed, 4 expected failures), including test_dtensor_local_view_deepcopy_save_load, a DTensor whose local tensor sits at a nonzero storage offset, as sharded parameters now do.
  • torchtitan (weifengpy/torchtitan-flexshard 79fd6d5, debug.deterministic=True, seed 42, 20 steps, on an earlier revision of this PR): 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, run at the top of the stack: sft and seag (2x B200), qwen3hp (4x GB300) and val (TP x CP x PP, 8x B200) give bitwise-identical loss and grad_norm at every step, and seag and val the same validation losses, against [FSDP2] Add partial_backward, complete_grouped_forward and policy getters (AI-assisted) #203961 with the same torchtitan, and [FSDP2] Add partial_backward, complete_grouped_forward and policy getters (AI-assisted) #203961 gives the same for sft, seag and val against torchtitan's main (with fsdp_lifecycle.py). The qwen3 and muse_glimmer configs ran with flex attention instead of varlen. torchtitan's chunked-loss, accelerator-graph, CPU-offload, MXFP8/NVFP4 FSDP, RL generator and torchft unit tests pass on both PRs (4x GB300).

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure

As of commit d9f467f with merge base bba8f39 (image):

NEW FAILURE - The following job has failed:

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

[ghstack-poisoned]
@weifengpy weifengpy changed the title [FSDP2] Run fully_shard on the FlexShard engine (AI-assisted) [FSDP2] Run fully_shard on the FlexShard engine runtime; delete FSDPParamGroup (AI-assisted) Nov 6, 2026
weifengpy added a commit that referenced this pull request Nov 6, 2026
…aramGroup (AI-assisted)

- [ ] 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. Top of a two-PR stack on #199726; the PR below moves the FlexShard engine into core.

## 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: `FSDPParamGroup`, `FSDPCommContext`, `RegisterPostBackwardFunction`, `foreach_all_gather`/`foreach_reduce`, and `FSDPParam`'s storage methods (`to_sharded`, `to_unsharded`, ...). `fsdp_state._fsdp_param_group(s)` now returns engine buckets, which keep the commonly read attributes (`fsdp_params`, `mesh_info`, `reduce_grads`, `reshard_after_backward`, ...).

## 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.

**Review order.**
1. `_flex_shard/bucket_storage.py`, `bucket_runtime.py`, `bucket_comm.py`: what the runtime gained. `ShardedBucketStorage._fsdp2_semantics` turns on FSDP2's scheduling rules for `fully_shard` buckets: a post-backward per forward call, `reshard_after_backward` in syncing backwards, backward prefetch of the previous bucket in post-forward order, prefetches kept until used or the last backward, a post-backward at the end of backward for buckets backward did not reach, and gradient dtypes chosen in the forward. `flex_shard` buckets keep their behavior. 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, 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.
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`.
3. `_fully_shard/_fsdp_engine.py`: `FullyShardBucket` (homing `FSDPParam` storage into the bucket, mixed precision, the `FSDPModule` setters) and `FSDPParamRepresentation` (DTensor parameters, gradient accumulation into DTensor `.grad`, deferred upcasts, offload).
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. Under functorch transforms, outputs get a pre-backward autograd function, as before.
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. Deletions and ports: `_fsdp_param_group.py`, most of `_fsdp_collectives.py` (the comm classes, ops, layout helpers and the default reduce-scatter input function stay), the dynamo special case for `FSDPParamGroup.use_training_state`, `fsdp2_mem_tracker`, and the pipelining `share_comm_ctx` check.
7. 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 deepcopy and save of the state dict.

**Choices.**
- One engine instead of keeping `FSDPParamGroup` on shared storage (the previous revision of this PR): the FSDP2 scheduling rules become runtime options that `flex_shard` can adopt, and prefetch, reduction and stream management have one implementation.
- Implicit forward prefetch (FSDP2's learned order) stays: the engine's all-gathers wait on the current stream, so without it nothing overlaps.
- FSDP2's errors are kept where users can hit them (int `reshard_after_forward` with DTensor-sharded parameters, `Shard(i>0)` divisibility, post-forward re-gathers with all-gather extensions, partial reductions with manual finalization).

**Not done.** The dynamo guard builder `FSDP_TRAINING_STATE` is no longer used and can be removed separately. `flex_shard` does not expose the FSDP2 scheduling options yet. The full `spin fixlint`, including pyrefly, has not been run.

**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
```

- FSDP2 suite (`test/distributed/_composable/fsdp`, 8x B200): 418 passed, 3 skipped, 1 failed. The failure, `test_fully_shard_alloc_from_pg`, also fails with the previous internals on this host: it asserts that NCCL logs no buffer registrations, and NCCL 2.30.7 logs them.
- flex_shard suite (4x B200): 140 passed, 1 failed. `test_matches_fully_shard_with_head_called_twice` fails the same way on the PR below.
- The other `fully_shard` users above (replicate, 2D/3D composability with PP, the memory tracker, DCP state dicts; 4x and 8x B200): the same results as with the previous internals. `test_schedule_multiproc.py` does not import on this host (`model_registry`) with either.
- `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): 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.

ghstack-source-id: d5aa2f4
Pull-Request: #203764
weifengpy added a commit that referenced this pull request Nov 6, 2026
…aramGroup (AI-assisted)

- [ ] 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. Top of a two-PR stack on #199726; the PR below moves the FlexShard engine into core.

## 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: `FSDPParamGroup`, `FSDPCommContext`, `RegisterPostBackwardFunction`, `foreach_all_gather`/`foreach_reduce`, and `FSDPParam`'s storage methods (`to_sharded`, `to_unsharded`, ...). `fsdp_state._fsdp_param_group(s)` now returns engine buckets, which keep the commonly read attributes (`fsdp_params`, `mesh_info`, `reduce_grads`, `reshard_after_backward`, ...).

## 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.

**Review order.**
1. `_flex_shard/bucket_storage.py`, `bucket_runtime.py`, `bucket_comm.py`: what the runtime gained. `ShardedBucketStorage._fsdp2_semantics` turns on FSDP2's scheduling rules for `fully_shard` buckets: a post-backward per forward call, `reshard_after_backward` in syncing backwards, backward prefetch of the previous bucket in post-forward order, prefetches kept until used or the last backward, a post-backward at the end of backward for buckets backward did not reach, and gradient dtypes chosen in the forward. `flex_shard` buckets keep their behavior. 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, 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.
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`.
3. `_fully_shard/_fsdp_engine.py`: `FullyShardBucket` (homing `FSDPParam` storage into the bucket, mixed precision, the `FSDPModule` setters) and `FSDPParamRepresentation` (DTensor parameters, gradient accumulation into DTensor `.grad`, deferred upcasts, offload).
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. Under functorch transforms, outputs get a pre-backward autograd function, as before.
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. Deletions and ports: `_fsdp_param_group.py`, most of `_fsdp_collectives.py` (the comm classes, ops, layout helpers and the default reduce-scatter input function stay), the dynamo special case for `FSDPParamGroup.use_training_state`, `fsdp2_mem_tracker`, and the pipelining `share_comm_ctx` check.
7. 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 deepcopy and save of the state dict.

**Choices.**
- One engine instead of keeping `FSDPParamGroup` on shared storage (the previous revision of this PR): the FSDP2 scheduling rules become runtime options that `flex_shard` can adopt, and prefetch, reduction and stream management have one implementation.
- Implicit forward prefetch (FSDP2's learned order) stays: the engine's all-gathers wait on the current stream, so without it nothing overlaps.
- FSDP2's errors are kept where users can hit them (int `reshard_after_forward` with DTensor-sharded parameters, `Shard(i>0)` divisibility, post-forward re-gathers with all-gather extensions, partial reductions with manual finalization).

**Not done.** The dynamo guard builder `FSDP_TRAINING_STATE` is no longer used and can be removed separately. `flex_shard` does not expose the FSDP2 scheduling options yet. The full `spin fixlint`, including pyrefly, has not been run.

**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
```

- FSDP2 suite (`test/distributed/_composable/fsdp`, 8x B200): 418 passed, 3 skipped, 1 failed. The failure, `test_fully_shard_alloc_from_pg`, also fails with the previous internals on this host: it asserts that NCCL logs no buffer registrations, and NCCL 2.30.7 logs them.
- flex_shard suite (4x B200): 140 passed, 1 failed. `test_matches_fully_shard_with_head_called_twice` fails the same way on the PR below.
- The other `fully_shard` users above (replicate, 2D/3D composability with PP, the memory tracker, DCP state dicts; 4x and 8x B200): the same results as with the previous internals. `test_schedule_multiproc.py` does not import on this host (`model_registry`) with either.
- `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): 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.

ghstack-source-id: d5aa2f4
Pull-Request: #203764
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Nov 7, 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. Top of a two-PR stack on #199726; the PR below moves the FlexShard engine into core.

## 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: `FSDPParamGroup`, `FSDPCommContext`, `RegisterPostBackwardFunction`, `foreach_all_gather`/`foreach_reduce`, and `FSDPParam`'s storage methods (`to_sharded`, `to_unsharded`, ...). `fsdp_state._fsdp_param_group(s)` now returns engine buckets, which keep the commonly read attributes (`fsdp_params`, `mesh_info`, `reduce_grads`, `reshard_after_backward`, ...).

## 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.

**Review order.**
1. `_flex_shard/bucket_storage.py`, `bucket_runtime.py`, `bucket_comm.py`: what the runtime gained. `ShardedBucketStorage._fsdp2_semantics` turns on FSDP2's scheduling rules for `fully_shard` buckets: a post-backward per forward call, `reshard_after_backward` in syncing backwards, backward prefetch of the previous bucket in post-forward order, prefetches kept until used or the last backward, a post-backward at the end of backward for buckets backward did not reach, and gradient dtypes chosen in the forward. `flex_shard` buckets keep their behavior. 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, 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.
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`.
3. `_fully_shard/_fsdp_engine.py`: `FullyShardBucket` (homing `FSDPParam` storage into the bucket, mixed precision, the `FSDPModule` setters) and `FSDPParamRepresentation` (DTensor parameters, gradient accumulation into DTensor `.grad`, deferred upcasts, offload). 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`). `FSDPParam.reset_sharded_param` compares the byte offset as well as the storage, since a group's parameters share one storage.
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. Under functorch transforms, outputs get a pre-backward autograd function, as before. `FSDPState._modules_to_run_forward` stays as a view of an open grouped forward, which torchtitan's evaluation cleanup reads and clears.
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`, most of `_fsdp_collectives.py` (the comm classes, ops, layout helpers and the default reduce-scatter input function stay), the dynamo special case for `FSDPParamGroup.use_training_state`, `fsdp2_mem_tracker`, and the pipelining `share_comm_ctx` check.
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 deepcopy and save of the state dict. 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 a caller finishing a partial grouped forward (`test_fully_shard_training.py`).

**Choices.**
- One engine instead of keeping `FSDPParamGroup` on shared storage (the previous revision of this PR): the FSDP2 scheduling rules become runtime options that `flex_shard` can adopt, and prefetch, reduction and stream management have one implementation.
- Implicit forward prefetch (FSDP2's learned order) stays: the engine's all-gathers wait on the current stream, so without it nothing overlaps.
- FSDP2's errors are kept where users can hit them (int `reshard_after_forward` with DTensor-sharded parameters, `Shard(i>0)` divisibility, post-forward re-gathers with all-gather extensions, partial reductions with manual finalization).

**Not done.** The dynamo guard builder `FSDP_TRAINING_STATE` is no longer used and can be removed separately. `flex_shard` does not expose the FSDP2 scheduling options yet. Lint passes, including pyrefly, but most pyrefly errors in the moved engine code are silenced with `# pyrefly: ignore` rather than fixed.

**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>
```

- FSDP2 suite (`test/distributed/_composable/fsdp`, 8x B200): 423 passed, 3 skipped, 1 failed. The failure, `test_fully_shard_alloc_from_pg`, also fails with the previous internals on this host: it asserts that NCCL logs no buffer registrations, and NCCL 2.30.7 logs them.
- flex_shard suite (4x B200): 140 passed, 1 failed. `test_matches_fully_shard_with_head_called_twice` fails the same way on the PR below.
- The other `fully_shard` users above (replicate, 2D/3D composability with PP, the memory tracker, DCP state dicts; 4x and 8x B200): the same results as with the previous internals (`test_pp_composability.py`: 26 passed on 8 GPUs). `test_schedule_multiproc.py` does not import on this host (`model_registry`) with either.
- `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): 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 this repo's CI pin (1d1fa94): the four integration tests that failed in this PR's first CI run (SFT, 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 against the internals before this stack, and the same validation losses. B200 has no FA4, so the qwen3 and muse_glimmer configs ran with flex attention instead of varlen.

ghstack-source-id: a50408a
Pull-Request: #203764
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Nov 7, 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. Top of a two-PR stack on #199726; the PR below moves the FlexShard engine into core.

## 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: `FSDPParamGroup`, `FSDPCommContext`, `RegisterPostBackwardFunction`, `foreach_all_gather`/`foreach_reduce`, and `FSDPParam`'s storage methods (`to_sharded`, `to_unsharded`, ...). `fsdp_state._fsdp_param_group(s)` now returns engine buckets, which keep the commonly read attributes (`fsdp_params`, `mesh_info`, `reduce_grads`, `reshard_after_backward`, ...).

## 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.

**Review order.**
1. `_flex_shard/bucket_storage.py`, `bucket_runtime.py`, `bucket_comm.py`: what the runtime gained. `ShardedBucketStorage._fsdp2_semantics` turns on FSDP2's scheduling rules for `fully_shard` buckets: a post-backward per forward call, `reshard_after_backward` in syncing backwards, backward prefetch of the previous bucket in post-forward order, prefetches kept until used or the last backward, a post-backward at the end of backward for buckets backward did not reach, and gradient dtypes chosen in the forward. `flex_shard` buckets keep their behavior. 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, 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.
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`.
3. `_fully_shard/_fsdp_engine.py`: `FullyShardBucket` (homing `FSDPParam` storage into the bucket, mixed precision, the `FSDPModule` setters) and `FSDPParamRepresentation` (DTensor parameters, gradient accumulation into DTensor `.grad`, deferred upcasts, offload). 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`). `FSDPParam.reset_sharded_param` compares the byte offset as well as the storage, since a group's parameters share one storage.
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. Under functorch transforms, outputs get a pre-backward autograd function, as before. `FSDPState._modules_to_run_forward` stays as a view of an open grouped forward, which torchtitan's evaluation cleanup reads and clears.
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`, most of `_fsdp_collectives.py` (the comm classes, ops, layout helpers and the default reduce-scatter input function stay), the dynamo special case for `FSDPParamGroup.use_training_state`, `fsdp2_mem_tracker`, and the pipelining `share_comm_ctx` check.
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 deepcopy and save of the state dict. 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 a caller finishing a partial grouped forward (`test_fully_shard_training.py`).

**Choices.**
- One engine instead of keeping `FSDPParamGroup` on shared storage (the previous revision of this PR): the FSDP2 scheduling rules become runtime options that `flex_shard` can adopt, and prefetch, reduction and stream management have one implementation.
- Implicit forward prefetch (FSDP2's learned order) stays: the engine's all-gathers wait on the current stream, so without it nothing overlaps.
- FSDP2's errors are kept where users can hit them (int `reshard_after_forward` with DTensor-sharded parameters, `Shard(i>0)` divisibility, post-forward re-gathers with all-gather extensions, partial reductions with manual finalization).

**Not done.** The dynamo guard builder `FSDP_TRAINING_STATE` is no longer used and can be removed separately. `flex_shard` does not expose the FSDP2 scheduling options yet. Lint passes, including pyrefly, but most pyrefly errors in the moved engine code are silenced with `# pyrefly: ignore` rather than fixed.

**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>
```

- FSDP2 suite (`test/distributed/_composable/fsdp`, 8x B200): 423 passed, 3 skipped, 1 failed. The failure, `test_fully_shard_alloc_from_pg`, also fails with the previous internals on this host: it asserts that NCCL logs no buffer registrations, and NCCL 2.30.7 logs them.
- flex_shard suite (4x B200): 140 passed, 1 failed. `test_matches_fully_shard_with_head_called_twice` fails the same way on the PR below.
- The other `fully_shard` users above (replicate, 2D/3D composability with PP, the memory tracker, DCP state dicts; 4x and 8x B200): the same results as with the previous internals (`test_pp_composability.py`: 26 passed on 8 GPUs). `test_schedule_multiproc.py` does not import on this host (`model_registry`) with either.
- `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): 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 this repo's CI pin (1d1fa94): the four integration tests that failed in this PR's first CI run (SFT, 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 against the internals before this stack, and the same validation losses. B200 has no FA4, so the qwen3 and muse_glimmer configs ran with flex attention instead of varlen.

ghstack-source-id: 51916de
Pull-Request: #203764
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Nov 7, 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. Top of a two-PR stack on #199726; the PR below moves the FlexShard engine into core.

## 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: `FSDPParamGroup`, `FSDPCommContext`, `RegisterPostBackwardFunction`, `foreach_all_gather`/`foreach_reduce`, and `FSDPParam`'s storage methods (`to_sharded`, `to_unsharded`, ...). `fsdp_state._fsdp_param_group(s)` now returns engine buckets, which keep the commonly read attributes (`fsdp_params`, `mesh_info`, `reduce_grads`, `reshard_after_backward`, ...).

## 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. The two scheduling trade-offs are `BucketCommContext` options named by what they do: `post_backward_per_call` (reduce and reshard after each forward call's backward, versus once after the last) and `keep_prefetches_until_used` (FSDP2's backward prefetch of the previous bucket in post-forward order, with prefetches kept until used, versus one prefetch at a time that is released when execution diverges from the learned order). `fully_shard` turns both on; `flex_shard` keeps them off by default and exposes setters for them and for `set_reduce_scatter_unused_params`. 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, 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.
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/param_driven_shard.py` and `_flex_shard/all_gather_layout.py`: the all-gather of parameters that define their own inputs (all-gather extensions, tensor-subclass data) or of a custom `AllGatherLayout` is the engine's `ParamDrivenShard`. It keeps each parameter's all-gather outputs, checks extension payloads against the sharding, packs and finalizes them with the bucket's layout, and builds the unsharded parameter, calling the representation's `all_gather_inputs` and `post_all_gather` hooks for the extension. The layout contract, `AllGatherInput` and the copy-out moved here from `_fully_shard`; `torch.distributed.fsdp.experimental` still exports them.
3. `_fully_shard/_fsdp_engine.py`, `_fsdp_param.py`: `FullyShardBucket` (homing `FSDPParam` storage into the bucket, mixed precision, the `FSDPModule` setters) and `FSDPParamRepresentation` (DTensor parameters, gradient accumulation into DTensor `.grad`, deferred upcasts, offload, 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,281 lines). 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`). `FSDPParam.reset_sharded_param` compares the byte offset as well as the storage, since a group's parameters share one storage.
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. Under functorch transforms, outputs get a pre-backward autograd function, as before. `FSDPState._modules_to_run_forward` stays as a view of an open grouped forward, which torchtitan's evaluation cleanup reads and clears.
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`, most of `_fsdp_collectives.py` (the comm classes, ops and the default reduce-scatter input function stay), the dynamo special case for `FSDPParamGroup.use_training_state`, `fsdp2_mem_tracker`, and the pipelining `share_comm_ctx` check.
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 deepcopy and save of the state dict. 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 a caller finishing a partial grouped forward (`test_fully_shard_training.py`). `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 with both scheduling options on 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 are the tested behavior, and only the two real trade-offs stay options. This changes `flex_shard` (experimental): `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.
- 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.
- FSDP2's errors are kept where users can hit them (int `reshard_after_forward` with DTensor-sharded parameters, `Shard(i>0)` divisibility, post-forward re-gathers with all-gather extensions, partial reductions with manual finalization).

**Not done.** The dynamo guard builder `FSDP_TRAINING_STATE` is no longer used and can be removed separately. Lint passes, including pyrefly, but most pyrefly errors in the moved engine code are silenced with `# pyrefly: ignore` rather than fixed.

**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>
```

- FSDP2 suite (`test/distributed/_composable/fsdp`, 8x B200): 423 passed, 3 skipped, 1 failed. The failure, `test_fully_shard_alloc_from_pg`, also fails with the previous internals on this host: it asserts that NCCL logs no buffer registrations, and NCCL 2.30.7 logs them.
- flex_shard suite (4x B200): 143 passed.
- The other `fully_shard` users above (replicate, 2D/3D composability with PP, the memory tracker, DCP state dicts; 4x and 8x B200): the same results as with the previous internals (`test_pp_composability.py`: 26 passed on 8 GPUs). `test_schedule_multiproc.py` does not import on this host (`model_registry`) with either.
- `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 this repo's CI pin (1d1fa94): the four integration tests that failed in this PR's first CI run (SFT, 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 against the internals before this stack, and the same validation losses. B200 has no FA4, so the qwen3 and muse_glimmer configs ran with flex attention instead of varlen.

ghstack-source-id: 49e6b08
Pull-Request: #203764
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Nov 7, 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. Top of a two-PR stack on #199726; the PR below moves the FlexShard engine into core.

## 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`, ...). `fsdp_state._fsdp_param_group(s)` now returns engine buckets, which keep the commonly read attributes (`fsdp_params`, `mesh_info`, `post_forward_mesh_info`, `reduce_grads`, `reshard_after_backward`, `reshard()`, ...), and `_fsdp_param_group.FSDPParamGroup` names the bucket class, since torchtitan's FSDP lifecycle helpers import it.

## 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. The two scheduling trade-offs are `BucketCommContext` options named by what they do: `post_backward_per_call` (reduce and reshard after each forward call's backward, versus once after the last) and `keep_prefetches_until_used` (FSDP2's backward prefetch of the previous bucket in post-forward order, with prefetches kept until used, versus one prefetch at a time that is released when execution diverges from the learned order). `fully_shard` turns both on; `flex_shard` keeps them off by default and exposes setters for them and for `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, 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.
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/param_driven_shard.py` and `_flex_shard/all_gather_layout.py`: the all-gather of parameters that define their own inputs (all-gather extensions, tensor-subclass data) or of a custom `AllGatherLayout` is the engine's `ParamDrivenShard`. It keeps each parameter's all-gather outputs, checks extension payloads against the sharding, packs and finalizes them with the bucket's layout, and builds the unsharded parameter, calling the representation's `all_gather_inputs` and `post_all_gather` hooks for the extension. The layout contract, `AllGatherInput` and the copy-out moved here from `_fully_shard`; `torch.distributed.fsdp.experimental` still exports them. Parameters sharded unevenly on a nonzero dim (#203465) take this path too: `FSDPParam` pads their all-gather inputs on short and empty ranks and the copy-out drops the padding, as in FSDP2; `Shard`'s reduce-scatter pads and reorders their gradients (`_pad_and_reorder_by_rank`, which FSDP2's default reduce-scatter input function now shares), 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. As in the PR below, a custom layout raises for such parameters.
3. `_fully_shard/_fsdp_engine.py`, `_fsdp_param.py`: `FullyShardBucket` (homing `FSDPParam` storage into the bucket, mixed precision, the `FSDPModule` setters) and `FSDPParamRepresentation` (DTensor parameters, gradient accumulation into DTensor `.grad`, deferred upcasts, offload, 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,281 lines). 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`). `FSDPParam.reset_sharded_param` compares the storage by identity and the byte offset, since a group's parameters share one storage and empty storages all report `data_ptr()` 0: otherwise an empty rank's shard looks replaced at lazy init and is re-homed into a new local tensor, which drops an all-gather extension patched onto the old one.
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 keeps the engine context's copy in sync, since torchtitan's chunked loss sets and restores it directly. Under functorch transforms, outputs get a pre-backward autograd function, as before. `FSDPState._modules_to_run_forward` stays as a view of an open grouped forward, which torchtitan's evaluation cleanup reads and clears.
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`, most of `_fsdp_collectives.py` (the comm classes, ops and the default reduce-scatter input function stay), the dynamo special case for `FSDPParamGroup.use_training_state`, `fsdp2_mem_tracker`, and the pipelining `share_comm_ctx` check.
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)`, deepcopy and save of the state dict, and that no backward prefetch stays in flight for a bucket that does not unshard in backward. 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 a caller finishing a partial grouped forward (`test_fully_shard_training.py`). `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 with both scheduling options on 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 are the tested behavior, and only the two real trade-offs stay options. This changes `flex_shard` (experimental): `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.
- 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.
- 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).

**Not done.** The dynamo guard builder `FSDP_TRAINING_STATE` is no longer used and can be removed separately. Lint passes, including pyrefly, but most pyrefly errors in the moved engine code are silenced with `# pyrefly: ignore` rather than fixed.

**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`, 8x B200): 433 passed, 3 skipped, 1 failed, including #203465's uneven-sharding tests. The PR below alone gives the same counts on the same build (its suite keeps 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): 143 passed.
- 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 this repo's current CI pin (9f70e55): 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 against the PR below alone, and the same validation losses. B200 has no FA4, so the qwen3 and muse_glimmer configs ran with flex attention instead of varlen.

ghstack-source-id: 17cebb7
Pull-Request: #203764
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Nov 8, 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. Top of a two-PR stack on #199726; the PR below moves the FlexShard engine into core.

## 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`, ...). `fsdp_state._fsdp_param_group(s)` now returns engine buckets, which keep the commonly read attributes (`fsdp_params`, `mesh_info`, `post_forward_mesh_info`, `reduce_grads`, `reshard_after_backward`, `reshard()`, ...), and `_fsdp_param_group.FSDPParamGroup` names the bucket class, since torchtitan's FSDP lifecycle helpers import it.

## 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. The two scheduling trade-offs are `BucketCommContext` options named by what they do: `post_backward_per_call` (reduce and reshard after each forward call's backward, versus once after the last) and `keep_prefetches_until_used` (FSDP2's backward prefetch of the previous bucket in post-forward order, with prefetches kept until used, versus one prefetch at a time that is released when execution diverges from the learned order). `fully_shard` turns both on; `flex_shard` keeps them off by default and exposes setters for them and for `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, 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.
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/param_driven_shard.py` and `_flex_shard/all_gather_layout.py`: the all-gather of parameters that define their own inputs (all-gather extensions, tensor-subclass data) or of a custom `AllGatherLayout` is the engine's `ParamDrivenShard`. It keeps each parameter's all-gather outputs, checks extension payloads against the sharding, packs and finalizes them with the bucket's layout, and builds the unsharded parameter, calling the representation's `all_gather_inputs` and `post_all_gather` hooks for the extension. The layout contract, `AllGatherInput` and the copy-out moved here from `_fully_shard`; `torch.distributed.fsdp.experimental` still exports them. Parameters sharded unevenly on a nonzero dim (#203465) take this path too: `FSDPParam` pads their all-gather inputs on short and empty ranks and the copy-out drops the padding, as in FSDP2; `Shard`'s reduce-scatter pads and reorders their gradients (`_pad_and_reorder_by_rank`, which FSDP2's default reduce-scatter input function now shares), 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. As in the PR below, a custom layout raises for such parameters.
3. `_fully_shard/_fsdp_engine.py`, `_fsdp_param.py`: `FullyShardBucket` (the bucket's storage, mixed precision, the `FSDPModule` setters) and `FSDPParamRepresentation` (DTensor parameters, gradient accumulation into DTensor `.grad`, deferred upcasts, offload, 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 keeps the engine context's copy in sync, since torchtitan's chunked loss sets and restores it directly. Under functorch transforms, outputs get a pre-backward autograd function, as before. `FSDPState._modules_to_run_forward` stays as a view of an open grouped forward, which torchtitan's evaluation cleanup reads and clears.
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`; `_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`; 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, and that no backward prefetch stays in flight for a bucket that does not unshard in backward. 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 a caller finishing a partial grouped forward (`test_fully_shard_training.py`). `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 with both scheduling options on 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 are the tested behavior, and only the two real trade-offs stay options. This changes `flex_shard` (experimental): `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.
- 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.
- 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).

**Not done.** torchtitan reaches into FSDP2's private state, so shims for it stay: the `FSDPParamGroup` name, the bucket's group attributes, `_modules_to_run_forward`, and `is_last_backward` as a property. They can go once FSDP has public APIs for what torchtitan's lifecycle helpers do (#203176, #203177) and torchtitan uses them. Parameters sharded unevenly on a nonzero dim take the parameter-driven all-gather; the engine's own `Shard` placement, `flex_shard` and custom layouts don't support them yet.

**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`, 8x B200): 434 passed, 3 skipped, 1 failed, including #203465's uneven-sharding tests. The PR below alone passes its version of the suite on the same build (433, 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): 143 passed.
- 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 this repo's current CI pin (9f70e55): 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 against the PR below alone, and the same validation losses. B200 has no FA4, so the qwen3 and muse_glimmer configs ran with flex attention instead of varlen.

ghstack-source-id: 3394c2d
Pull-Request: #203764
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Nov 8, 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. Top of a two-PR stack on #199726; the PR below moves the FlexShard engine into core.

## 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`, ...). `fsdp_state._fsdp_param_group(s)` now returns engine buckets, which keep the commonly read attributes (`fsdp_params`, `mesh_info`, `post_forward_mesh_info`, `reduce_grads`, `reshard_after_backward`, `reshard()`, ...), and `_fsdp_param_group.FSDPParamGroup` names the bucket class, since torchtitan's FSDP lifecycle helpers import it.

## 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. The two scheduling trade-offs are `BucketCommContext` options named by what they do: `post_backward_per_call` (reduce and reshard after each forward call's backward, versus once after the last) and `keep_prefetches_until_used` (FSDP2's backward prefetch of the previous bucket in post-forward order, with prefetches kept until used, versus one prefetch at a time that is released when execution diverges from the learned order). `fully_shard` turns both on; `flex_shard` keeps them off by default and exposes setters for them and for `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, 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.
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/param_driven_shard.py` and `_flex_shard/all_gather_layout.py`: the all-gather of parameters that define their own inputs (all-gather extensions, tensor-subclass data) or of a custom `AllGatherLayout` is the engine's `ParamDrivenShard`. It keeps each parameter's all-gather outputs, checks extension payloads against the sharding, packs and finalizes them with the bucket's layout, and builds the unsharded parameter, calling the representation's `all_gather_inputs` and `post_all_gather` hooks for the extension. The layout contract, `AllGatherInput` and the copy-out moved here from `_fully_shard`; `torch.distributed.fsdp.experimental` still exports them. Parameters sharded unevenly on a nonzero dim (#203465) use the engine's own `Shard`, 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 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 accumulation into DTensor `.grad`, deferred upcasts, offload, 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 keeps the engine context's copy in sync, since torchtitan's chunked loss sets and restores it directly. Under functorch transforms, outputs get a pre-backward autograd function, as before. `FSDPState._modules_to_run_forward` stays as a view of an open grouped forward, which torchtitan's evaluation cleanup reads and clears.
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`; `_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`; 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 a caller finishing a partial grouped forward (`test_fully_shard_training.py`). `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 with both scheduling options on 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 are the tested behavior, and only the two real trade-offs stay options. This changes `flex_shard` (experimental): `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.
- 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).

**Not done.** torchtitan reaches into FSDP2's private state, so shims for it stay: the `FSDPParamGroup` name, the bucket's group attributes, `_modules_to_run_forward`, and `is_last_backward` as a property. They can go once FSDP has public APIs for what torchtitan's lifecycle helpers do (#203176, #203177) and torchtitan uses them.

**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`, 8x B200): 437 passed, 3 skipped, 1 failed, including #203465's uneven-sharding tests. The PR below alone passes its version of the suite on the same build (433, 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 passed.
- 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 this repo's current CI pin (9f70e55): 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 against the PR below alone, and the same validation losses. B200 has no FA4, so the qwen3 and muse_glimmer configs ran with flex attention instead of varlen.

ghstack-source-id: 7b0ced0
Pull-Request: #203764
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Nov 8, 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. Top of the stack on #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.

## 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`, ...). `fsdp_state._fsdp_param_group(s)` now returns engine buckets, which keep the attributes that tests read (`fsdp_params`, `mesh_info`, ...). `_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.

## 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. The two scheduling trade-offs are `BucketCommContext` options named by what they do: `post_backward_per_call` (reduce and reshard after each forward call's backward, versus once after the last) and `keep_prefetches_until_used` (FSDP2's backward prefetch of the previous bucket in post-forward order, with prefetches kept until used, versus one prefetch at a time that is released when execution diverges from the learned order). `fully_shard` turns both on; `flex_shard` keeps them off by default and exposes setters for them and for `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, 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/param_driven_shard.py` and `_flex_shard/all_gather_layout.py`: the all-gather of parameters that define their own inputs (all-gather extensions, tensor-subclass data) or of a custom `AllGatherLayout` is the engine's `ParamDrivenShard`. It keeps each parameter's all-gather outputs, checks extension payloads against the sharding, packs and finalizes them with the bucket's layout, and builds the unsharded parameter, calling the representation's `all_gather_inputs` and `post_all_gather` hooks for the extension. The layout contract, `AllGatherInput` and the copy-out moved here from `_fully_shard`; `torch.distributed.fsdp.experimental` still exports them. Parameters sharded unevenly on a nonzero dim (#203465) use the engine's own `Shard`, 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 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 accumulation into DTensor `.grad`, deferred upcasts, offload, 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`; 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 with both scheduling options on 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 are the tested behavior, and only the two real trade-offs stay options. This changes `flex_shard` (experimental): `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.
- 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 8eb29ddc3 (branch `weifengpy/fsdp-public-apis` of pytorch/torchtitan, draft PR TITAN_PR), 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. 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`, 8x B200): 445 passed, 3 skipped, 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 (440, 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): 167 passed.
- 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: 711539f
Pull-Request: #203764
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Nov 8, 2026
…oad test (AI-assisted)

The single-group FSDPState._fsdp_param_group property goes away with
pytorch/pytorch#203764; _fsdp_param_groups exists on both sides.
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
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
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Nov 13, 2026
…and lifecycle on the shared engine (AI-assisted)

`fully_shard` still kept its own per-parameter storage model (`FSDPParam`'s storage, padding, re-homing and dtypes, the `FullyShardBucket` adapter), its own module lifecycle (`FSDPState`'s hooks, root lazy init and finalization) and the comm implementations, next to the engine's, while `flex_shard` kept its own parameter install, unshard, reshard and finalization methods and handles. This moves all of them into the engine (`torch/distributed/fsdp/_flex_shard`), where both frontends run on the same code, and leaves FSDP2 its frontend: the `fully_shard`/`FSDPModule` API, the DTensor representation of the parameters, the translation of its arguments (meshes, HSDP, managed modules and parameters), and FSDP2's lifecycle rules.

FSDP2's own code in `torch/distributed/fsdp/_fully_shard` goes from 3,674 to 2,028 code lines (without docstrings and comments; 4,997 on main).

Stacked on #203990.

Review order:

1. `_flex_shard/param_homing.py`: how a bucket keeps its parameters' data, for both frontends. `build_bucket`, the one bucket builder (both frontends and `relayout_bucket`), creates the storage and the runtime; the runtime's `ParamHoming` copies each parameter's shard into the storage as its placement lays it out and registers a sharded parameter that views it (a DTensor for `fully_shard`, a plain tensor with sharding metadata for `flex_shard`). Tensor subclasses and parameters with all-gather extensions keep storage of their own, in buckets whose placement supports it (`Shard`). A `load_state_dict` has the bucket re-read its parameters, and the next unshard copies data that `load_state_dict(assign=True)`, `to_empty()` or `module.to()` replaced into the storage (`refresh`/`home`); a dtype change also rebuilds the unsharded parameters. Parameters left on meta while others are not keep zero slots and count as unmaterialized. Moved from `FullyShardBucket`, `FSDPParam` and `flex_shard`'s `from_bucket`/`install_sharded_params`/`copy_params_from`.
2. `_flex_shard/param_extensions.py`: FSDP's all-gather extensions (`fsdp_pre_all_gather`, `fsdp_post_all_gather`), moved from `FSDPParam`; `flex_shard` passes them its bucket mesh.
3. `bucket_runtime.py`: `ParamRepresentation` builds and re-reads sharded parameters (`new_sharded_param`, `local_tensor`, `set_local_tensor`, `refresh_param`) and nothing else; the runtime owns its `ParamHoming`, which the placements ask about parameter-defined all-gathers (`Placement.new_bucket_state`), and casts reduced gradients per dtype run, as FSDP2 did, for both frontends. `placement_contract.py`: placements declare `supports_own_param_storage` and `requires_dtype_grouped_layout`, and their bucket state can be reset. `placements/shard.py`: `compute_local_shape` keeps the other dims of an empty shard, as a DTensor's local tensor. `bucket_storage.py`: `ParamMeta`, for parameters whose sharded data is not the parameter itself (a DTensor's local tensor).
4. `_flex_shard/module_state.py`: the module lifecycle (`ShardedModuleState`, `BucketGroup`): forward hooks, the root's lazy init across nested calls (which re-reads parameters replaced since construction and raises for parameters still on meta), forward casts, `partial_backward`, explicit unshard, manual and asynchronous finalization (`FinalizationHandle`), `reset_iter_state` and the reduce-scatter buffer cap, moved from `FSDPState`, `FSDPModule` and `_fsdp_engine.py`. `flex_shard` runs on it too: one state per call (`FlexShardState`, through `contract`) and a group per bucket, which replaces its own hook installation, finalization and handles.
5. `_flex_shard/module_ops.py`: explicit unshard (`ModuleUnshardHandle`) and reshard, `nn.Module._apply` on sharded parameters (`apply_to_params`), and the settings of a module's buckets, which `FSDPModule`'s and `FlexShardModule`'s methods both call. `_flex_shard/api.py`: the policies, comm interfaces and handles that both frontends take and return, which `_fsdp_api.py` re-exports.
6. `_flex_shard/comms.py` (moved from `_fsdp_collectives.py`, which re-exports it) and `TrainingState`/`_cast_fp_tensor` (moved to `_flex_shard/utils.py`, re-exported by `_fsdp_common.py`).
7. The frontends: `_fsdp_param.py` (`FSDPParam`: the DTensor spec of a parameter and its conversions), `_fsdp_engine.py` (`FullyShardBucket`, `FSDPParamRepresentation`), `_fsdp_state.py` (`FSDPState`: FSDP2's rules on the shared lifecycle), `_fully_shard.py`, and `flex_shard.py` (`FlexShardState`, `FlexShardRepresentation`, `build_flex_bucket`).

Behavior changes:

- Both frontends: `load_state_dict(assign=True)` after the first forward uses the loaded values (#203764 fixes this for `fully_shard`; `flex_shard` never used them); `module.to(dtype)` after a forward works (`fully_shard` raised in the next forward, also before this stack; `flex_shard` also failed on `module.cpu()`); parameters left on meta while others are not make the first forward raise, naming them; `reshard()` restores the grad upcasts that a backward left deferred, and explicit `unshard()`/`reshard()` raise in backward, after a backward that raised, or while a finalization handle is pending.
- A submodule kept alive after its model is deleted no longer keeps all of the model's sharded storage alive: the `load_state_dict` post-hook that re-reads a bucket's parameters holds it weakly.
- `fully_shard`: a parameter that several modules share is tied again when an op such as `to_empty()` gave each module its own (`flex_shard` already did this). `set_manual_backward_finalization` applies to the next backward right away, not from the next forward.
- `flex_shard`, as `fully_shard`: it is a composable API (`flex_shard.state(module)`; applying it twice raises); `finalize_backward` requires `set_manual_backward_finalization(True)`; `reshard()` keeps the state of a backward still to run; `set_reduce_scatter_max_input_buffers` replaces `set_max_pending_reduce_grads`; hooks are installed by `flex_shard()`, also for a module on meta; reduced gradients are cast per dtype run, in one buffer per run; buckets that hook the same module unshard in the order of their `BucketSpec`s (their prepended hooks ran them in reverse). All-gather extensions get the bucket mesh, and a tensor-subclass parameter in a bucket whose placement is not `Shard` raises when sharded.

Test plan:

Each test file on its own, on B200s (4 GPUs; PP composability on 8):

```
python -m pytest test/distributed/_composable/fsdp/<file>.py
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
python -m pytest test/distributed/_composable/test_composability/test_2d_composability.py test/distributed/_composable/test_composability/test_pp_composability.py
python -m pytest test/distributed/_tools/test_fsdp2_mem_tracker.py test/distributed/checkpoint/fsdp/test_fsdp_dsd.py test/distributed/checkpoint/test_state_dict.py
spin lint -- --take RUFF,PYFMT,FLAKE8,MYPY,PYREFLY <changed files>
```

New tests: `test_load_state_dict_assign_after_forward` and `test_params_left_on_meta_must_be_replaced_before_forward` for both frontends, `test_module_to_dtype_after_forward` (`fully_shard`) and `test_module_to_dtype_and_device_after_forward` (`flex_shard`, also `module.cpu()`), `test_params_with_storage_of_their_own_require_shard` and `test_all_gather_extensions_get_the_bucket_mesh` (`flex_shard`), and `test_empty_shards_stay_homed` (`fully_shard`).

Results (B200, this revision, on a host that other users' jobs shared all day):

- FSDP2 suite (`test/distributed/_composable/fsdp`, each file on its own, 4 GPUs): 444 passed, 8 skipped (5 need 8 GPUs), 1 failed: `test_fully_shard_alloc_from_pg`, which asserts that NCCL logs no buffer registrations; the NCCL on this host logs them, so it fails on main too. Under the load, `test_train_parity_multi_group` hit an NCCL timeout in some runs, as it does on this host today with FSDP2's own internals (#203961) and with #203764; it passed in an earlier run of this PR (3,273 s). `test_fully_shard_per_param_mesh_training_overlap`, which compares measured times, failed once under the load and passed in two reruns, as it does with #203990.
- `flex_shard` suite (4 GPUs): 151 tests and 23 subtests pass.
- The other `fully_shard` users: replicate (5, 10, 16 passed, 1 skipped), 2D composability (17 passed, 1 skipped), PP composability (26, 8 GPUs), the memory tracker (3) and DCP state dicts (6, 26) pass.
- torchtitan at its CI pin (f4546c7): sft, seag, qwen3hp and val give loss and grad_norm bitwise identical to FSDP2's own internals (#203961), and val the same validation losses.
- CPU time of an explicit `unshard()` plus `reshard()` per group of 100 parameters (30 groups, 2 GPUs, median of 5 rounds): 1,344 µs, against 1,655 µs at #203990 (a rerun gave 1,603 µs).
- `spin lint -- --take RUFF,PYFMT,FLAKE8,MYPY,PYREFLY`: clean but one PYREFLY error in `torch/_dynamo/variables/torch.py`, which main has too.

This PR was authored with an AI assistant (Claude).

ghstack-source-id: 1485840
Pull-Request: #204334
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Nov 13, 2026
…oad test (AI-assisted)

The single-group FSDPState._fsdp_param_group property goes away with
pytorch/pytorch#203764; _fsdp_param_groups exists on both sides.
weifengpy added a commit to pytorch/torchtitan that referenced this pull request Nov 14, 2026
… offload test (AI-assisted)

The test read each module's offload policy from FSDP2's parameter group
(`_fsdp_param_group`), which pytorch/pytorch#203764 removes, as does the
policy attribute of the engine bucket that replaces it (pytorch/pytorch#204334).
It now records the policy that torchtitan's FSDP helpers pass to `fully_shard`
for each module, which is what the tests check, without FSDP2's private state.
[ghstack-poisoned]
[ghstack-poisoned]

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant