Skip to content

[fsdp] Use FSDPModule APIs instead of FSDP2's private state (AI-assisted) - #5946

Draft
weifengpy wants to merge 2 commits into
mainfrom
weifengpy/fsdp-public-apis
Draft

weifengpy wants to merge 2 commits into
mainfrom
weifengpy/fsdp-public-apis

Conversation

@weifengpy

@weifengpy weifengpy commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

The sections below were drafted with an AI assistant at the author's request. This PR is a draft: it needs pytorch/pytorch#203961 (in a PyTorch nightly) before its CI can pass.

Why

torchtitan drives FSDP2's private state, so it breaks whenever FSDP2's internals change, and pytorch/pytorch#203764 replaces them (fully_shard on the FlexShard engine, no FSDPParamGroup):

Call site Private state it uses On pytorch/pytorch#203764
ChunkedLossWrapper via distributed/fsdp_lifecycle.py saves, overrides and restores each group's post_forward_mesh_info, reduce_grads, all_reduce_grads, reshard_after_backward; sets is_last_backward; reads _post_backward_pending, _partial_reduce_output ImportError (_fsdp_param_group is gone)
post_validate_fsdp_for_accelerator_graph _modules_to_run_forward, _post_forward AttributeError
torchft maybe_set_all_reduce_hook sets param_group._all_reduce_hook silently ignored: async quorum skips the cross-replica all-reduce
RL generator weight loads (rl/generator/model.py) fsdp_lifecycle helpers, alloc_storage/free_storage on _sharded_param_data AttributeError/ImportError
tests _post_forward_indices, group policies, _unsharded_inner_tensors, all_gather_outputs AttributeError

pytorch/pytorch#203176 and pytorch/pytorch#203177 asked for public APIs for the first two; pytorch/pytorch#203961 adds them to FSDPModule (on today's FSDP2 internals, so this PR works before pytorch/pytorch#203764 lands).

Example. The chunked loss:

# before: torchtitan/distributed/fsdp_lifecycle.py, 143 lines over FSDP2's private state
with fsdp_partial_backwards(lm_head, run_backward=run_backward,
                            outer_backward_follows=decoder_requires_grad) as fsdp:
    for chunk_index in range(num_chunks):
        if chunk_index == num_chunks - 1:
            fsdp.before_last_forward()
        logits = fsdp.after_forward(tuple(lm_head(h) for h in h_chunks))
        ...

# after
with lm_head.partial_backward(outer_backward_follows=decoder_requires_grad):
    for chunk_index in range(num_chunks):
        logits = tuple(lm_head(h) for h in h_chunks)
        ...

What changed

Call site Now
components/loss.py lm_head.partial_backward(outer_backward_follows=...) when lm_head is an FSDPModule; distributed/fsdp_lifecycle.py is deleted
distributed/fsdp.py module.complete_grouped_forward() + module.reshard()
experiments/torchft/manager.py m.set_all_reduce_hook(hook) on every FSDP module (the PyTorch PR lets it set every parameter group of a module)
rl/generator/model.py module.complete_grouped_forward() + module.reshard(), then module._restore_sharded_params() and module._free_sharded_params() (private: the names the RL code's TODOs proposed)

Tests (mechanical, same assertions, public observation):

  • test_chunked_loss_fsdp.py: settings through the getters (get_reshard_after_forward, ...); all-gathers counted at dist.all_gather_single instead of patching FSDPModule.unshard; the head's resharding checked on its parameters. The check that the chunk backwards keep the decoder's backward-prefetch state moved to PyTorch's tests, which can read FSDP's internals.
  • test_accelerator_graph_train_eval.py: checks that evaluation cleanup resharded the parameters instead of reading _modules_to_run_forward.
  • test_mxfp8_fsdp.py, test_nvfp4_fsdp.py: record the all-gather outputs and unsharded inner tensors through _ShardedFSDPTensor.fsdp_post_all_gather, torchtitan's own extension hook, instead of FSDPParam attributes.
  • torchft: a fake FSDPModule records set_all_reduce_hook.
  • test_fsdp_cpu_offload.py: records the offload policy that torchtitan's FSDP helpers pass to fully_shard for each module instead of reading it from FSDP2's parameter group (_fsdp_param_group), which [FSDP2] Run fully_shard on the FlexShard engine runtime; delete FSDPParamGroup (AI-assisted) pytorch#203764 removes.
  • tests/rl/unit_tests/cpu/test_generator_model.py: checks that each group's forward is completed before its unshard() (patched FSDPModule methods) instead of reading FSDPCommContext's stream choice.

Numerics

Loss and grad_norm are bitwise identical at every step, with the same validation losses, for the integration configs that exercise these paths (scripts/loss_compare.py, 4-10 steps; flex attention instead of varlen). This revision is rebased onto torchtitan's main a419690 and ran against PyTorch main bba8f39 with the stack; qwen3 against main ran on the previous revision:

Config GPUs this PR vs main (both on pytorch/pytorch#203961) this PR on pytorch/pytorch#204334 vs on pytorch/pytorch#203961
llama3_debugmodel_sft (chunked loss) 2x B200 bitwise bitwise
shared train/eval accelerator graphs (flex) 2x B200 bitwise, validation same bitwise, validation same
qwen3 higher-precision RMSNorm + QK norm, TP 2 (flex) 4x GB300 bitwise (previous revision) bitwise
llama3_debugmodel_validation_tp2_cp2_pp2 (flex) 8x B200 bitwise, validation same bitwise, validation same

Testing

On 4x GB300, against pytorch/pytorch#203961 (today's FSDP2 internals with the APIs) and against pytorch/pytorch#204334 with the PRs above it (FSDP2 on the FlexShard engine):

Test pytorch/pytorch#203961 engine stack
tests/unit_tests/cpu/components/test_chunked_loss_fsdp.py pass pass
tests/unit_tests/gpu/distributed/test_accelerator_graph_train_eval.py (4 GPUs) 11 pass 11 pass
tests/unit_tests/gpu/distributed/test_fsdp_cpu_offload.py 6 pass 6 pass
tests/unit_tests/gpu/quantization/test_mxfp8_fsdp.py 7 pass 7 pass
tests/unit_tests/gpu/quantization/test_nvfp4_fsdp.py 2 pass 2 pass
tests/rl/unit_tests/cpu/test_generator_model.py 9 pass 9 pass
torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py 10 pass 10 pass

tests/rl/unit_tests/cpu/test_vllm_wrapper.py did not run: vLLM is not installed here. PyTorch's TestFullyShardModuleMethods covers _free_sharded_params/_restore_sharded_params and the multi-group all-reduce hook. Pyrefly reports no new errors against the stack's PyTorch, and 6 fewer than torchtitan's main (the fsdp_lifecycle.py reads of FSDP2 internals).

python -m pytest <test file>
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>

Known issues / follow-ups

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 8, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 8, 2026
weifengpy added a commit to pytorch/pytorch that referenced this pull request Nov 11, 2026
…ters (AI-assisted)

- [x] Passes lint (`spin fixlint`)
- [x] Added/updated tests
- [x] Updated documentation where applicable
- [ ] Included benchmark results

## Linked issue or supporting maintainer

> Addresses #203176 and #203177. The author has write access.

## BC-breaking?

> `FSDPModule.reshard()` now also reshards a group whose forward is in progress, which it silently skipped before. `set_all_reduce_hook` accepts modules with several parameter groups instead of raising. Everything else is new API.

## 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.** A chunked loss runs the output projection on its own, chunk by chunk, after the root forward: each chunk's forward and backward go through the projection only, from detached decoder outputs, and one outer backward through the decoder follows with the accumulated gradients. FSDP has no API for that, so torchtitan's `fsdp_lifecycle.py` drives FSDP's private state:

- It saves, overrides and restores each parameter group's `post_forward_mesh_info`, `reshard_after_backward`, `reduce_grads` and `all_reduce_grads` to keep the projection unsharded and its gradients unreduced across the chunks. The public setters cannot restore them: `set_requires_gradient_sync` also overwrites the HSDP all-reduce setting, and the root's automatic `reshard_after_forward=False` cannot be set back (#203177).
- It sets `is_last_backward=False` during the chunks so that each chunk backward's final callback does not finish the step for the decoder's groups, which clears their backward prefetch order, waits on reductions and resets per-iteration state (#203176).
- It completes a partial grouped forward through `_modules_to_run_forward` and `_post_forward`, for `fully_shard([norm, output])` called from the loss and for evaluation cleanup before graph capture (#203176).

The same holds elsewhere: torchft sets `_all_reduce_hook` on each parameter group because `set_all_reduce_hook` rejects modules with several groups, and torchtitan's RL weight sync calls `FSDPParamGroup._to_sharded()` and `alloc_storage`/`free_storage` because `reshard()` skips a group whose forward is in progress.

**API.**
- `FSDPModule.partial_backward(*, outer_backward_follows)`: a context manager for the projection's chunks. Entry all-gathers once. Inside, the module's parameters stay unsharded, each call completes its group's forward, gradients accumulate unreduced, and backwards leave the other groups' parameters, pending gradients and prefetch order alone. Exit reduces and reshards as the caller's settings say. Without an outer backward it then finishes the backward as the end of a backward does. A group shared with modules outside the projection is reduced by the outer backward instead, once, and manual finalization leaves the reduction to `finalize_backward`. A forward-only use reshards on exit, and an exception exits without collectives.
- `FSDPModule.complete_grouped_forward(output=None)`: completes the forward of a group of which only some modules ran: reshards as `reshard_after_forward` says and registers the backward hooks on `output`.
- `get_reshard_after_forward()`, `get_reshard_after_backward()`, `get_requires_gradient_sync()`, `get_requires_all_reduce()`, `get_is_last_backward()`: the settings by value, so callers can save and restore them (the getters report the root's automatic `reshard_after_forward=False` once lazy init made it the root).
- `reshard()` reshards unconditionally, and `set_all_reduce_hook` sets the hook on every parameter group of the module.
- Private `_free_sharded_params()` / `_restore_sharded_params()` free and re-allocate the sharded storage for inference on persistent unsharded parameters, as torchtitan's RL weight sync does (the names its TODOs proposed). They handle tensor subclass parameters through `__tensor_flatten__`.

**Implementation.** The scope is a flag on the module's groups that the existing paths check (no reshard after forward or backward, no reduction, no post-forward order record, no backward prefetch), plus the open scope on the shared `FSDPStateContext`, which makes a chunk backward's final callback finish only the scope's groups. Settings are never mutated, so the getters report the caller's values throughout. Each call of a grouped module completes the group in the scope, so each chunk's output gets the backward hooks. The chunks' gradients start in the unsharded gradient dtype (`grad_dtype`, e.g. the fp32 `reduce_dtype` of bf16 parameters), since they accumulate across backwards; custom backward kernels that write the weight gradient themselves, such as torchtitan's `Linear`, read it.

**Choices.**
- A group that the projection shares with other modules (`fully_shard([norm, output])`, tied embeddings) is reduced by the outer backward, once with all its gradients; other groups reduce at exit, which overlaps the decoder's backward. torchtitan's helper deferred only when gradients from earlier microbatches were pending, so in a synced step it reduced a tied group twice, once with the chunks' gradients and once with the embedding's.
- A context manager rather than a handle with a "last forward" marker: exit is where the last backward is known.
- The sharded-storage methods stay private until there is a design for inference memory APIs.

**Review order.** `_fully_shard.py` (API and docs), `_fsdp_state.py` (scope, final callback, group forward hooks), `_fsdp_param_group.py` (flag checks), tests.

### Test Plan

```
python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -k "TestFullyShardPartialBackward or TestFullyShardModuleMethods or partial_group"
python -m pytest test/distributed/_composable/fsdp/   # each file on its own
```

`TestFullyShardPartialBackward` checks the scope against a non-FSDP reference on 4 ranks for separate, grouped and tied (`[embed, norm, head]`) projections, with and without an outer backward, synced each microbatch or accumulated, FSDP and HSDP 2x2. It checks loss, gradients and parameters over 3 steps of 2 microbatches, one all-gather of the projection at most, before its forwards, one reduce-scatter per group and syncing microbatch, unchanged settings and prefetch order, a forward-only use, and recovery after an exception through `reset_iter_state`. `test_partial_backward_accumulates_in_reduce_dtype` checks the chunks' `grad_dtype`, `test_complete_grouped_forward` that a completed group reshards and re-gathers in backward. `TestFullyShardModuleMethods` covers the getters, `reshard()` during a grouped forward, the all-reduce hook with two parameter groups, and freeing and restoring sharded storage.

Results (4x B200): the FSDP2 suite passes on this revision, 436 tests, with 8 skipped (5 of them need 8 GPUs) and 1 failed: `test_fully_shard_alloc_from_pg` asserts that NCCL logs no buffer registrations, which this host's NCCL does, also without this PR.

torchtitan with the APIs in place of `fsdp_lifecycle.py` (draft torchtitan PR pytorch/torchtitan#5946): its chunked-loss (layouts, HSDP, deferred, frozen, GPipe/1F1B, multi-output head, recovery), accelerator-graph, CPU-offload and MXFP8/NVFP4 FSDP tests pass, and four integration configs (SFT with chunked loss, shared train/eval accelerator graphs, qwen3 with TP, validation with TP x CP x PP) give bitwise-identical loss and grad_norm and the same validation losses as torchtitan's main on this PR.

ghstack-source-id: 777c865
Pull-Request: #203961
weifengpy added a commit to pytorch/pytorch 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
… weight sync (AI-assisted)

Replace torchtitan/distributed/fsdp_lifecycle.py and the other private FSDP2
state that torchtitan reaches into with FSDPModule methods from
pytorch/pytorch#203961:

- ChunkedLossWrapper: lm_head.partial_backward(outer_backward_follows=...)
- post_validate_fsdp_for_accelerator_graph: complete_grouped_forward() + reshard()
- torchft: set_all_reduce_hook on every FSDP module
- RL generator weight loads: complete_grouped_forward() + reshard(), then
  _restore_sharded_params() and _free_sharded_params() instead of
  alloc_storage/free_storage on FSDP's parameter internals

Tests observe FSDP through public APIs and torchtitan's own tensors instead of
FSDP2's parameter-group internals; the generator load test checks that each
group's forward is completed before its unshard() instead of reading
FSDPCommContext's stream choice.
@weifengpy
weifengpy force-pushed the weifengpy/fsdp-public-apis branch from f4546c7 to 5fea988 Compare November 13, 2026 23:39
… 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.

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/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant