Skip to content

[no-ci] [FSDP2] Keep only fully_shard's frontend; run its parameters and lifecycle on the shared engine (AI-assisted) - #204334

Draft
weifengpy wants to merge 5 commits into
gh/weifengpy/242/basefrom
gh/weifengpy/242/head
Draft

weifengpy wants to merge 5 commits into
gh/weifengpy/242/basefrom
gh/weifengpy/242/head

Conversation

@weifengpy

@weifengpy weifengpy commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):


  • 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 #203990: the PRs below run fully_shard and flex_shard on the FlexShard engine, on #204282, a copy of #199726, and #203961; the three above add flex_shard features and BlockShard for fully_shard.

BC-breaking?

No for fully_shard's public API. Private names change:

  • torch.distributed.fsdp._fully_shard._fsdp_api re-exports the policies, comm interfaces and handles from torch.distributed.fsdp._flex_shard.api, which both frontends use; it keeps DataParallelMeshDims and still exports _ReduceOp and AllGatherInput, which fbcode imports from there. _fsdp_collectives re-exports the comm implementations from torch.distributed.fsdp._flex_shard.comms.
  • FSDPParam keeps its DTensor spec and the attributes tools read (sharded_param, unsharded_param, _param_fqn, sharded_state, _module_info, unsharded_accumulated_grad); its storage methods (bind_storage, reset_sharded_param, all_gather_inputs, ...) and dtype properties move into the engine.
  • FSDPState keeps its name and _fsdp_param_groups; its hook and lifecycle methods come from the engine's ShardedModuleState.
  • _get_param_module_infos is replaced by the engine's param_owners; _chunk_with_empty and _get_dim_chunked_size are gone (the engine's Shard.compute_local_shape gives the same local shapes; nothing in fbcode imports them from torch).

Yes for the experimental flex_shard, which now follows fully_shard's rules:

  • flex_shard is a composable API like fully_shard: flex_shard.state(module) holds its state, and applying it twice to a module raises the composable-API error.
  • finalize_backward requires set_manual_backward_finalization(True), and returns torch.distributed.fsdp.GradientReductionHandle; unshard(async_op=True) returns a torch.distributed.fsdp.UnshardHandle.
  • reshard() is fully_shard's: it keeps the state of a backward still to run, which re-gathers in its pre-backward hook, and no longer ends the manual finalization mode of a backward it abandons.
  • set_max_pending_reduce_grads is replaced by fully_shard's set_reduce_scatter_max_input_buffers (at least 1).
  • Hooks are installed by flex_shard(), also for a module on meta, whose first forward raises until its parameters are materialized.
  • Buckets that hook the same module unshard in the order of their BucketSpecs; their prepended hooks ran them in reverse before.
  • ShardedBucketStorage.from_bucket, install_sharded_params and copy_params_from are gone: build_flex_bucket builds a bucket, through the engine's build_bucket.

Summary (human written only)

Placeholder for the author.

Agent details (AI-generated)

Drafted with an AI assistant at the author's request. This is a draft for CI and discussion, not ready for review or merge.

Problem. After the PRs below, fully_shard ran on the engine's runtime but still kept its own per-parameter storage model (FSDPParam's storage, padding, re-homing and dtypes, and the FullyShardBucket adapter), its own module lifecycle (FSDPState's hooks, root lazy init and finalization), the implementations of its setters and the comm implementations, next to the engine's, and flex_shard kept its own parameter install, unshard and finalization methods and handles. FSDP2's own code was 3,731 code lines, of which about a third was frontend.

What. These parts move into the engine (torch/distributed/fsdp/_flex_shard), where both frontends run on the same code, and FSDP2 keeps its frontend: the fully_shard/FSDPModule API, the DTensor representation of its parameters, the translation of its arguments (meshes, HSDP, managed modules) and FSDP2's lifecycle rules. FSDP2's own code goes from 3,731 to 2,038 code lines (without docstrings and comments; 5,057 on main):

Role Code lines
API: fully_shard(), FSDPModule, its handles 408
DataParallelMeshDims, and the shared policies and comm interfaces re-exported 50
DTensor representation: FSDPParam, FSDPParamRepresentation 751
Argument translation: meshes, HSDP, managed modules, device moves 504
Glue: FullyShardBucket, FSDPState's rules, FSDP2-only setters 313
Old import path (_fsdp_collectives) 12

The engine grows by 1,940 code lines, so the two together grow by 247 (+1.6%): the interfaces between the frontends and the shared code (representation hooks, module state, parameter sources). Without API changes, about 60 more lines of FSDPParam (the properties tools read) can go once those tools use public APIs.

Choices.

  • fully_shard keeps DTensor parameters through the engine's ParamRepresentation hooks rather than an engine-side DTensor type, so flex_shard's plain-tensor parameters need nothing new. The representation only exposes parameters; questions about their data (storage of their own, all-gather extensions) go to the bucket's ParamHoming, which the runtime owns and the placements ask.
  • One bucket builder, build_bucket, for both frontends and relayout_bucket, and one parameter install: ParamHoming takes each placement's storage layout, so flex_shard's block, owned and mixed placements and fully_shard's Shard buckets install, and re-home after to_empty(), the same way. Placements say what they support (supports_own_param_storage, requires_dtype_grouped_layout) instead of the builder checking their types. Shard's layout aligns each parameter to its element size, which only changes buckets of several dtypes (fully_shard's; flex_shard requires one dtype per bucket).
  • Re-homing is lazy and the same for both frontends: load_state_dict (whose assign=True replaces parameters) has the bucket re-read its parameters, and the next unshard copies replaced data into the storage; module.to(dtype) also rebuilds the unsharded parameters in the new dtype. Parameters left on meta while others are not keep zero slots and make the first forward raise, naming them.
  • flex_shard takes fully_shard's rules where the two differed (finalize_backward requires manual finalization, reshard(), the reduce-scatter buffer cap), rather than the engine keeping both. Both frontends' explicit unshard()/reshard() check that no backward is running or failed and no finalization handle is pending, and reshard() restores the grad upcasts that a backward left deferred.
  • FSDPState and FullyShardBucket keep their names, and _fsdp_param_groups stays as a property, to keep test and tool churn small. FSDPModule's methods reach the engine through module functions (_fsdp_runtimes, _fsdp_storages, ...) rather than new private methods, so classes that mirror FSDPModule's methods (SimpleFSDP) have nothing new to reserve.
  • FSDP2's hooks stay outside Dynamo (FSDPState wraps the shared hooks), while flex_shard's are traced as before; under torch.compile the shared hooks run only the buckets' traced unshards and casts.

Review order.

  1. _flex_shard/param_homing.py: how a bucket keeps its parameters' data, for both frontends (install, home/refresh, the lazy re-home after a load, tied parameters, storage of their own for tensor subclasses and all-gather extensions, parameters left on meta), the one bucket builder (build_bucket) and parameter discovery (param_owners).
  2. _flex_shard/param_extensions.py: FSDP's all-gather extensions, moved from FSDPParam; flex_shard gives them its bucket mesh.
  3. bucket_runtime.py: ParamRepresentation's hooks that build and re-read sharded parameters; the runtime owns its ParamHoming and casts reduced gradients per dtype run for both frontends. placements/shard.py, shard_all_gather.py, placement_contract.py: placements ask the homing about parameter-defined all-gathers; Shard.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): lazy init re-reads parameters and checks they are materialized, explicit unshard, manual and asynchronous finalization (FinalizationHandle), reset_iter_state, the reduce-scatter buffer cap, moved from FSDPState, FSDPModule and _fsdp_engine.py. flex_shard runs on it: one state per call and a group per bucket.
  5. _flex_shard/module_ops.py: explicit unshard (ModuleUnshardHandle) and reshard, nn.Module._apply on sharded parameters, 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 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, _fsdp_engine.py, _fsdp_state.py, _fully_shard.py, and flex_shard.py (FlexShardState, FlexShardRepresentation, build_flex_bucket).

Behavior changes besides flex_shard's above:

  • load_state_dict(assign=True) after the first forward uses the loaded values, for both frontends (test_load_state_dict_assign_after_forward): [FSDP2] Run fully_shard on the FlexShard engine runtime; delete FSDPParamGroup (AI-assisted) #203764 fixes the regression for fully_shard, and flex_shard never used them.
  • module.to(dtype) after a forward works for both frontends; fully_shard raised in the next forward (before this stack too: "mat1 and mat2 must have the same dtype"), and flex_shard also failed on module.cpu().
  • A submodule kept alive after its model is deleted no longer keeps all of the model's sharded storage alive, since the load_state_dict post-hook that re-reads a bucket's parameters holds it weakly (test_fully_shard_del_memory).
  • fully_shard: a parameter that several modules share is tied again when an op such as to_empty() gave each module its own, as flex_shard already did; set_manual_backward_finalization applies to the next backward right away, not from the next forward; reshard() restores the grad upcasts that a backward under manual finalization left deferred, so grads kept without sync accumulate in the wider dtype; explicit unshard()/reshard() raise in backward, after a backward that raised, or with a finalization handle pending.
  • flex_shard: all-gather extensions get the bucket's mesh (they got none); a tensor-subclass parameter in a bucket whose placement is not Shard raises when sharded; reduced gradients are cast per dtype run, in one buffer per run.

Test Plan

python -m pytest test/distributed/_composable/fsdp/<file>.py        # each file on its own, 4 GPUs
python -m pytest test/distributed/_composable/flex_shard/<file>.py  # each file on its own, 4 GPUs
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/_tools/test_fsdp2_mem_tracker.py test/distributed/checkpoint/fsdp/test_fsdp_dsd.py test/distributed/checkpoint/test_state_dict.py
python -m pytest test/distributed/_composable/test_composability/test_pp_composability.py   # 8 GPUs
spin fixlint -- --take RUFF,PYFMT <changed files>
spin lint -- --take PYREFLY,MYPY,RUFF,PYFMT,FLAKE8 <changed files>

New tests: for both frontends, test_load_state_dict_assign_after_forward and test_params_left_on_meta_must_be_replaced_before_forward (test_fully_shard_state_dict.py, test_flex_shard_state_dict.py), and test_module_to_dtype_after_forward (fully_shard) and test_module_to_dtype_and_device_after_forward (flex_shard, also module.cpu()); for flex_shard, test_params_with_storage_of_their_own_require_shard and test_all_gather_extensions_get_the_bucket_mesh (test_flex_shard_buckets.py); for fully_shard, test_empty_shards_stay_homed (test_fully_shard_engine.py: a rank whose shard is empty must not take it for a replaced parameter, or it alone re-homes and the ranks' collectives diverge).

Results on main bba8f39, at the top of the stack (this PR and the three above it: flex_shard features, DTensor BlockShard and its fully_shard support), each file on its own:

  • FSDP2 suite (test/distributed/_composable/fsdp, 4x GB300): 479 passed, 8 deselected (they 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. test_fully_shard_training_overlap, which compares measured times, failed once and passed in two reruns.
  • flex_shard suite (4x GB300): 157 passed.
  • The other fully_shard users (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. PP composability passes (26 passed) on 8x B200.
  • torchtitan at its CI pin (d07461d): sft and seag (2x B200), qwen3hp (4x GB300) and val (TP x CP x PP, 8x B200) give loss and grad_norm bitwise identical to FSDP2's own internals ([FSDP2] Add partial_backward, complete_grouped_forward and policy getters (AI-assisted) #203961), and seag and val the same validation losses. torchtitan's FSDP unit tests (chunked loss, accelerator graphs, CPU offload, MXFP8/NVFP4, RL generator, torchft) pass (4x GB300).
  • CPU time of an explicit unshard() plus reshard() per group of 100 parameters (30 groups, 2x GB300, median of 5 rounds): 1,386 µs, against 1,660 µs at [FSDP] flex_shard takes fully_shard's mixed precision and offload policies and DTensor's Shard (AI-assisted) #203990 (a rerun gave 1,631 µs).
  • Every commit of the stack is lint clean on its own, with the linters of CI's lint job on the files changed from main (spin lint -- --skip CLANGTIDY,CLANGTIDY_EXECUTORCH_COMPATIBILITY,CLANGFORMAT <files>, which includes PYREFLY).

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 7 New Failures, 1 Unrelated Failure

As of commit 80a32e9 with merge base bba8f39 (image):

NEW FAILURES - The following jobs have failed:

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

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

@pytorch-bot pytorch-bot Bot added release notes: distributed (fsdp) release notes category ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests labels Nov 11, 2026
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Nov 11, 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 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,166 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. `ParamHoming.install` 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. `refresh`/`home` re-home data that `to_empty()`, `load_state_dict(assign=True)` or `module.to()` replaced, and tied parameters are tied again. `ShardedBucketStorage.from_bucket` now creates the bucket's runtime and installs through it; `build_homed_bucket` does the same for `fully_shard`, with parameter discovery (`param_owners`). Moved from `FullyShardBucket`, `FSDPParam` and `flex_shard`'s `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`.
3. `bucket_runtime.py`: `ParamRepresentation` gains the hooks that build and re-read sharded parameters (`new_sharded_param`, `local_tensor`, `set_local_tensor`, `refresh_param`), answers the all-gather questions through the bucket's `ParamHoming`, and casts reduced gradients per dtype run, as FSDP2 did, for both frontends. `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, forward casts, `partial_backward`, explicit unshard, manual and asynchronous finalization (`FinalizationHandle`) and `reset_iter_state`, moved from `FSDPState`, `FSDPModule` and `_fsdp_engine.py`. `flex_shard` runs on it too: one state per call 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 and the settings of a module's buckets, which `FSDPModule`'s and `FlexShardModule`'s methods both call. `UnshardHandle` and `GradientReductionHandle` move to `_fsdp_api.py`, so the engine implements them.
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 frontend: `_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`.

Behavior changes:

- 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 parameters holds its group 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`: `finalize_backward` requires `set_manual_backward_finalization(True)`; `reshard()` also ends the manual mode of the backward it abandons; 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).

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,PYREFLY <changed files>
```

At this revision, the FSDP2 suite passes (440 tests, 8 skipped) but for `test_fully_shard_alloc_from_pg`, which also fails without this stack on this host (NCCL logs buffer registrations). `flex_shard`'s 146 tests and 23 subtests pass, as do replicate, 2D and PP composability, the memory tracker and DCP state dicts. Lint is clean but for a pyrefly error in `torch/_dynamo/variables/torch.py` that main also has.

torchtitan at the CI pin f4546c7 (sft, seag, qwen3 HP, validation with TP2/CP2/PP2) through `scripts/loss_compare.py`: loss and grad norm at every step, and the validation losses, match FSDP2's own internals with #203961's APIs bit for bit.

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

ghstack-source-id: ae59194
Pull-Request: #204334
[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 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

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant