PyTorch FSDP2 Deep Dive — DeviceMesh, DTensor Shards, Eager Hooks, and torch.compile
A source-level walk through PyTorch FSDP2 — how fully_shard builds groups from a DeviceMesh, turns parameters into sharded DTensors, swaps between sharded and unsharded storage through eager forward and backward hooks, overlaps collectives with compute, and deliberately integrates with torch.compile.
All PyTorch permalinks in this post are pinned to pytorch/pytorch commit
7f7be6e2, the tip ofmainwhen this post was written on October 24, 2026. Line numbers are for that exact revision.
The behavior that makes FSDP2 click
Suppose a Transformer block owns a 1 GiB parameter tensor and trains on eight GPUs. Outside the block’s computation, each rank should pay for roughly one eighth of that tensor. During the block’s matrix multiplications, however, each rank needs the full parameter. During backward, every rank produces a full gradient, but the optimizer should again own only one eighth of it.
FSDP2 turns those three requirements into a repeating state transition:
1
2
3
4
5
6
7
8
9
10
11
12
13
sharded DTensor parameter
│
│ all-gather before computation
▼
unsharded ordinary parameter
│
│ run forward or backward computation
▼
full gradient on each rank
│
│ reduce-scatter after backward computation
▼
sharded DTensor gradient
The important part is not merely that an all-gather and a reduce-scatter happen. It is where PyTorch inserts them, which parameter object is visible to user code at each point, when storage is allocated and freed, and how that machinery behaves when the model body is compiled.
FSDP2’s answer is quite different from a conventional wrapper. The public fully_shard function applies a composable distributed contract to an existing module, installs eager hooks and side-state, changes the module’s class to inject the FSDPModule API without changing object identity, and registers sharded parameters as DTensors. User code keeps the same module reference and the same parameter FQNs.
This post follows that implementation from setup through one eager iteration, then explains the compile boundary.
FSDP2 in one paragraph
FSDP2 groups parameters, shards each group’s persistent storage across a data-parallel mesh dimension, all-gathers a group before its computation, optionally frees the unsharded storage after forward, all-gathers again before backward, and reduce-scatters the full gradients back into sharded gradients. Each rank then applies its optimizer to its local parameter and gradient shards. Nested groups let communication for the next layer overlap computation for the current layer. A two-dimensional mesh can additionally replicate each shard group, producing HSDP: reduce-scatter inside the sharding dimension and all-reduce across the replication dimension.
The current implementation lives in torch/distributed/fsdp/_fully_shard/. The old torch.distributed._composable.fsdp location is now only a compatibility re-export.
Part 1 — The concepts behind the setup
DeviceMesh: name the process-group topology
A DeviceMesh is an $N$-dimensional arrangement of ranks. Each mesh dimension defines a family of process groups while giving that dimension a stable name. Instead of passing several unrelated process groups through the stack, code can say “shard over this dimension, replicate over that one, and use another dimension for tensor parallelism.”
The implementation is in torch/distributed/device_mesh.py. For FSDP2, the common cases are:
| Mesh | Parameter placements | Meaning |
|---|---|---|
| 1D | (Shard(0),) | Pure FSDP: split tensor dimension 0 across all ranks |
| 2D | (Replicate(), Shard(0)) | HSDP: replicate shard groups on mesh dim 0 and shard on dim 1 |
| Larger named mesh | DP placements on named dimensions, other placements preserved | Compose FSDP with TP, EP, or CP |
The 1D/2D mapping is created by _get_mesh_info. Its FSDPMeshInfo and HSDPMeshInfo objects cache the relevant ranks, group sizes, and process groups (_fsdp_common.py:49–100).
For eight GPUs, pure FSDP can start with:
1
2
3
4
5
6
7
8
9
10
11
12
import os
import torch
import torch.distributed as dist
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.fsdp import fully_shard
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
dist.init_process_group("nccl")
mesh = init_device_mesh("cuda", (dist.get_world_size(),))
For a 2-by-4 HSDP topology, the same eight ranks can instead be described as:
1
2
3
4
5
mesh = init_device_mesh(
"cuda",
(2, 4),
mesh_dim_names=("replicate", "shard"),
)
Now four ranks cooperate to hold one sharded model, and that sharded model is replicated twice. This is useful when a single node has a fast scale-up interconnect while cross-node bandwidth is lower: shard within a locality and replicate across localities.
DTensor: global meaning plus local storage
A DTensor describes one logical global tensor with:
- a
DeviceMesh; - one placement per mesh dimension; and
- the local tensor held by this rank.
The principal placements are Shard, Replicate, and Partial. Shard(0) means that the logical tensor’s dimension 0 is partitioned over the corresponding mesh dimension. Replicate() means every rank in that mesh dimension owns the same value. Partial() represents a value that still needs a reduction before it becomes a regular replicated or sharded value.
FSDP2 uses DTensor for the persistent, sharded parameter. This is more than metadata for debugging: the registered nn.Parameter really is a DTensor outside computation. Its global shape remains the model’s shape, while param.to_local() exposes only this rank’s shard.
This is one of FSDP2’s simplifying ideas. The model’s normal state_dict() sees sharded DTensor parameters, and tensor-parallel placements can remain in the same spec instead of being hidden behind an FSDP-specific flat parameter.
Apply fully_shard bottom-up
FSDP2 communication granularity is determined by calls to fully_shard. A call claims all parameters reachable from that module except parameters already claimed by an earlier call on a nested module. Therefore the normal Transformer setup is bottom-up:
1
2
3
4
for block in model.blocks:
fully_shard(block, mesh=mesh)
fully_shard(model, mesh=mesh)
Each block becomes a group. The final call claims embeddings, final normalization, output projection, and any other parameters not already owned by a block group. PyTorch’s public docstring explicitly recommends this order (_fully_shard.py:144–163).
The implementation is structural, not just a convention. The DFS in _get_managed_modules stops when it reaches a submodule that already has an FSDP state. The outer group cannot accidentally absorb that inner group’s parameters.
Calling fully_shard only on the root technically shards the model, but it creates one giant group. That means one giant all-gather before useful compute and one giant reduce-scatter after useful backward compute. Per-block groups are what make overlap possible.
There is also a less common list form:
1
fully_shard([model.final_norm, model.output], mesh=mesh)
The list shares one parameter group and therefore one set of collectives, while each module receives its own forward hooks. Current FSDP2 has explicit bookkeeping for a grouped module that does not execute on every invocation, including chunked-loss patterns (_fsdp_state.py:390–406).
Part 2 — What fully_shard() installs
It is a composable API, not a wrapper object
The entry point is decorated with @contract(state_cls=FSDPState). The generic composable contract checks that applying the API preserves module, parameter, and buffer FQNs and associates side-state with the existing module through a weak map.
The setup path is:
1
2
3
4
5
6
7
8
9
10
fully_shard(module)
├─ validate the module and DeviceMesh
├─ derive FSDP or HSDP mesh information
├─ discover modules and parameters not claimed by inner groups
├─ move managed state to the mesh device
├─ initialize FSDPState and register module hooks
├─ build one or more FSDPParamGroups
├─ convert every managed parameter into an FSDPParam
├─ annotate managed modules for Dynamo
└─ inject FSDPModule into each module's class
Most of that orchestration is visible in fully_shard():291–313 and _fsdp_init.py:433–569.
The final class change is unusual but useful. _apply_to_module synthesizes a class whose MRO starts with FSDPModule followed by the original class, then assigns it to module.__class__ (_fsdp_init.py:404–432). As a result:
- the object identity does not change;
- existing references remain valid;
isinstance(module, FSDPModule)becomes true; and- methods such as
unshard(),reshard(), and prefetch configuration become available.
FSDPState owns lifecycle; FSDPParamGroup owns communication
The state is deliberately split:
| Object | Scope | Main responsibility |
|---|---|---|
FSDPState | One fully_shard application | Module hooks, root discovery, iteration-wide coordination |
FSDPParamGroup | One group using one communication topology | Unshard/reshard, gradient reduction, stream and prefetch ordering |
FSDPParam | One original parameter | Sharded/unsharded representations, dtype, placement, storage |
FSDPCommContext | Shared by the FSDP tree | Communication streams, events, outstanding collective state |
FSDPStateContext | Shared by the FSDP tree | Root, all states, final callback, gradient-reduction status |
The fields are defined in FSDPState and FSDPParamGroup. One state may contain multiple parameter groups when a shard_placement_fn routes different parameters onto different process groups, which is useful for mixtures of experts.
FSDPState.init() registers a forward pre-hook and a forward hook on every managed module (_fsdp_state.py:113–144). Backward boundaries are installed later using tensor hooks and autograd functions. There is no replacement forward() method around the user’s module.
How one parameter becomes a sharded DTensor
FSDPParam._init_sharded_param is the core setup routine (_fsdp_param.py:277–405). For a normal tensor on a 1D mesh it:
- chooses
Shard(0)unlessshard_placement_fnsays otherwise; - constructs a
DTensorSpecfor the mesh and placement; - chunks the tensor along the selected dimension;
- pads the local chunk to a uniform size;
- flattens that padded chunk as the all-gather backing storage;
- wraps the unpadded local view as a
DTensor; - wraps that
DTensoras annn.Parameter; and - installs it back under the original parameter name.
Why pad first? Collective buffers need equal sizes from all ranks. If a tensor has 10 rows and is sharded over 4 ranks, the real row counts are 3, 3, 3, and 1, but the communication slot is sized as 3 rows on every rank. Padding once during initialization avoids rebuilding a padded input before every all-gather.
Under HSDP, the spec is (Replicate(), Shard(0)). If the input is already a DTensor from tensor or expert parallelism, FSDP2 preserves those placements and adds its data-parallel placement. The setup code handles same-tensor-dim composition with _StridedShard so two mesh dimensions can shard the same logical dimension without interpreting the layout as two unrelated contiguous splits (_fsdp_param.py:611–791).
Three storage states
Each parameter tracks a ShardedState:
| State | Registered on the module | Memory meaning |
|---|---|---|
SHARDED | Sharded DTensor parameter | Normal persistent state |
UNSHARDED | Full N-D parameter | Ready for forward/backward compute |
SHARDED_POST_FORWARD | Intermediate shard, not the normal registered parameter | reshard_after_forward=<int> optimization |
After all-gather, init_unsharded_param() views the flat collective output with the original shape and stride (_fsdp_param.py:915–972). When FSDP2 reshares, to_sharded() puts the persistent DTensor back and frees unsharded storage (_fsdp_param.py:974–999).
A subtle autograd constraint explains why FSDP2 does not simply allocate a new Python tensor every time. Autograd may save a reference or a view of the unsharded parameter for backward. PyTorch therefore constructs the unsharded parameter object once and frees or allocates its storage by resizing it, preserving object identity and aliasing. The source records this invariant in [Note: FSDP and autograd].
Part 3 — One eager iteration, line by line
First forward: lazy root discovery
Setup cannot know which FSDP state is the runtime root in every composition. The first state whose forward pre-hook runs calls _lazy_init. It walks the module tree, finds all FSDP states, shares the root’s communication and iteration contexts with them, validates that no parameter was assigned to two groups, initializes FQNs, and lazily initializes each parameter group.
This is also where the default reshard_after_forward policy becomes concrete:
- non-root groups default to
True; - the root group defaults to
False.
The root will be needed again almost immediately at the start of backward, so keeping its full parameters avoids an unhelpful free-and-re-all-gather cycle. Inner blocks benefit much more from releasing their full parameters while later blocks execute.
Forward pre-hook: all-gather and install full parameters
The forward path is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
FSDPState._pre_forward
├─ _root_pre_forward
├─ cast forward inputs if configured
└─ FSDPParamGroup.pre_forward
├─ unshard
├─ wait_for_unshard
├─ install unsharded parameters
└─ register the post-backward boundary on inputs
user module forward
FSDPState._post_forward
├─ FSDPParamGroup.post_forward
│ ├─ reshard if configured
│ └─ record post-forward order
├─ register pre-backward hooks on outputs
└─ cast output dtype if configured
The module-level implementation is _fsdp_state.py:309–389; the group-level implementation is _fsdp_param_group.py:627–664.
FSDPParamGroup.unshard() first checks whether the parameter is already unsharded or an asynchronous all-gather is already in flight. Otherwise it calls foreach_all_gather; wait_for_unshard() waits only at the point the full parameter is actually needed, copies out each result, creates the full parameter views, and changes the registered parameters to those views (_fsdp_param_group.py:450–579).
The all-gather implementation uses separate copy-in and communication streams:
1
2
3
4
5
6
7
8
9
all_gather_copy_in_stream:
pack each rank's padded local shards into collective input
all_gather_stream:
all_gather_into_tensor(input, output)
current computation stream:
wait before first use
view output slices as original N-D parameters
foreach_all_gather and its input fast path are in _fsdp_collectives.py:351–461. For ordinary BF16/FP32 parameters without extensions or CPU offload, current FSDP2 batches the local copies with torch._foreach_copy_ to reduce eager CPU overhead.
Forward post-hook: decide how much to free
reshard_after_forward controls the memory-versus-communication tradeoff:
| Value | After forward | Before backward |
|---|---|---|
True | Free full parameter and restore normal shard | Full all-gather |
False | Keep full parameter | No backward all-gather |
positive int | Reshard onto a smaller world size | All-gather within that smaller domain |
None | True for non-root, False for root | Automatic policy |
The public semantics and constraints are documented at _fully_shard.py:195–224, and the state transition itself is FSDPParamGroup.reshard.
The integer form is a hybrid option. For example, a model sharded over 64 GPUs may reshard after forward to groups of 8. It retains one eighth of the full parameter rather than one sixty-fourth, but backward all-gather stays within a faster 8-GPU locality.
How backward hooks are placed
Forward hooks are straightforward; backward needs more precision. FSDP2 must unshard immediately before gradients flow through a module and reduce the parameter gradients immediately after that module’s backward computation.
It marks the two graph boundaries differently:
- On module outputs,
_register_pre_backward_hookinstalls a tensor hook. When backward first reaches an output, it invokesFSDPState._pre_backward. - On module inputs,
RegisterPostBackwardFunctionis inserted as a nearly identity autograd function. Its backward runs after the module’s parameter gradients have been computed and callsFSDPParamGroup.post_backward.
The registration code and custom autograd functions are at _fsdp_state.py:581–702 and _fsdp_param_group.py:1164–1181, with RegisterPostBackwardFunction defined at _fsdp_param_group.py:1390–1411.
Both FSDPState and FSDPParamGroup track a four-state TrainingState:
1
IDLE → FORWARD → PRE_BACKWARD → POST_BACKWARD → IDLE
The state exists at both levels because activation-checkpoint recomputation can run a module’s forward while the overall iteration is already in backward. FSDP2 must treat that as a recomputation requiring an unshard, not as the start of a second independent training iteration.
Pre-backward: all-gather just in time
When backward reaches a wrapped module’s output:
1
2
3
4
5
6
FSDPState._pre_backward
├─ queue the root final callback once
└─ FSDPParamGroup.pre_backward
├─ unshard (or consume an already-prefetched all-gather)
├─ wait_for_unshard
└─ prefetch the next group in backward order
The code is in _fsdp_state.py:407–421 and _fsdp_param_group.py:673–687.
If forward kept the parameter unsharded, this is nearly a no-op. If forward freed it, pre-backward all-gathers it again before autograd needs the parameter to compute input and parameter gradients.
Post-backward: reduce-scatter full gradients into sharded gradients
After the module’s backward computation, the input-side autograd function calls FSDPParamGroup.post_backward. The common pure-FSDP sequence is:
- collect the full gradients for parameters in the group;
- reshard parameters if configured;
- flatten and pack gradients into a reduce-scatter input;
- launch reduce-scatter on the reduction stream;
- view this rank’s reduced slice as each sharded parameter’s gradient; and
- accumulate into an existing local gradient for microbatch accumulation.
If rank $p$ computes a full gradient $G_p$ and the sharding group has size $S$, rank $r$ receives:
\[\operatorname{grad}_r = \operatorname{shard}_r\left( \frac{1}{S}\sum_{p=0}^{S-1}G_p \right)\]The reduction and sharding are one collective instead of an all-reduce followed by throwing away $S-1$ shards on every rank.
foreach_reduce handles pure FSDP, HSDP, and pure replication in one path. For HSDP it first reduce-scatters within the shard group, then all-reduces the resulting shard across the replicate group. It also handles pre/post division factors, mixed reduction dtype, CPU gradient copies, gradient accumulation, and post-accumulate-grad hooks.
The collective is asynchronous. A root callback queued on the autograd engine runs after graph execution, covers groups whose ordinary post-backward boundary was not reached, waits the computation stream on outstanding communication events, finalizes each group, and releases collective state (_fsdp_state.py:422–567). Only then is the iteration fully reduced.
Where overlap comes from
With block-sized groups, a backward timeline looks like:
1
2
3
4
5
6
7
compute block N backward
reduce-scatter block N ───────────────┐
compute block N-1 backward ────────────────────────┐ │
reduce-scatter block N-1 ─┼───────────┤
compute block N-2 backward ────────────────────────┼────┐ │
▼ ▼ ▼
asynchronous communication
Forward and backward both use ordering recorded by hooks:
- Forward naturally all-gathers the next group as execution enters it. FSDP2 defers release of the previous all-gather state so copy-in and communication can safely pipeline on separate streams.
- Backward records forward completion order, reverses it, and prefetches the group that should execute next. The implementation is in
_backward_prefetch. - Users can request more aggressive ordering with
set_modules_to_forward_prefetchandset_modules_to_backward_prefetch, trading additional reserved memory for earlier communication.
This explains why grouping matters so much. A single root group has no next group with which to overlap. Hundreds of tiny groups pay too much launch and Python overhead. Transformer-block granularity is a useful starting point, not a universal optimum.
Part 4 — Mixed precision, offload, and checkpoint state
Mixed precision controls communication as well as compute
MixedPrecisionPolicy has separate controls for:
param_dtype: dtype used for all-gathered parameters and forward/backward parameter computation;reduce_dtype: dtype used for gradient communication;output_dtype: optional module-boundary output cast;cast_forward_inputs: whether to cast floating-point inputs; andparam_dtype_override_fn: a per-parameter override.
For example:
1
2
3
4
5
6
7
8
9
10
from torch.distributed.fsdp import MixedPrecisionPolicy
mp_policy = MixedPrecisionPolicy(
param_dtype=torch.bfloat16,
reduce_dtype=torch.float32,
)
for block in model.blocks:
fully_shard(block, mesh=mesh, mp_policy=mp_policy)
fully_shard(model, mesh=mesh, mp_policy=mp_policy)
This all-gathers parameters in BF16 but reduces gradients in FP32. The policy is independent of autocast: it determines FSDP’s parameter and communication dtypes, not only operator dispatch inside the forward body.
CPU offload changes the persistent side of the transition
CPUOffloadPolicy moves persistent parameter shards and reduced gradient shards to CPU, with pinned memory by default. The compute state is still unsharded on the accelerator, so each iteration adds host-to-device parameter traffic and device-to-host gradient traffic. This saves accelerator memory at a potentially large bandwidth cost.
The reduction path carefully chooses blocking versus non-blocking CPU copies: gradient accumulation or a CPU-side post-accumulate hook may require the data synchronously, while the ordinary path can overlap the copy (_fsdp_collectives.py:748–779).
state_dict() snapshots the sharded representation
FSDP2 registers the sharded DTensor parameter on the module during normal idle state. A state-dict pre-hook and load-state-dict pre-hook force the group back to that representation before serialization (_fsdp_param_group.py:1182–1206). A post-load hook then rebuilds the padded backing storage if loading replaced the parameter data (_fsdp_param.py:255–267).
That design is why FSDP2 checkpointing feels less like switching among FSDP-specific state-dict modes: the model’s ordinary registered state already describes globally-shaped, sharded tensors.
Part 5 — What happens under torch.compile
The compile boundary is deliberate
The easiest incorrect mental model is:
torch.compile(model)traces FSDP2’s Python hooks and puts all-gather, reshard, and reduce-scatter into one giant compiled graph.
That is not how the current implementation works.
FSDP2 defines _dynamo_disable as torch._dynamo.disable(..., recursive=True, reason="skipping FSDP hooks"). It decorates the forward pre/post hooks, pre-backward hook, post-backward path, root final callback, and iteration reset path. Those lifecycle methods run eagerly and create intentional graph boundaries.
The user module’s tensor computation is compiled. The orchestration around it remains eager:
1
2
3
4
5
6
7
8
9
10
11
12
13
eager FSDP pre-forward hook
└─ all-gather, wait, install unsharded parameters
compiled user forward graph
eager FSDP post-forward hook
└─ reshard, register backward boundary
compiled-autograd regions, if enabled
interrupted at eager FSDP pre/post-backward boundaries
eager root final callback
└─ wait/finalize/release
This separation protects the stream, storage, aliasing, Python state-machine, and autograd-engine ordering on which FSDP2 relies. It also means changing a grouping or communication option does not require Inductor to rediscover the whole lifecycle protocol.
The compile regression test test_disable_compiling_hooks asserts that Dynamo’s trace-rule checker is never entered for FSDP state hook frames. This is an explicit contract, not an accidental graph break.
How Dynamo sees an FSDP-managed module
During setup, fully_shard sets _is_fsdp_managed_module and _fsdp_use_orig_params on each managed module (_fully_shard.py:304–310). Dynamo’s variable builder recognizes those flags and constructs an FSDPManagedNNModuleVariable.
The reason is parameter identity across iterations. FSDP2 installs fresh unsharded views backed by the current all-gather output. A compiled graph must receive the current parameter views as inputs instead of specializing on the views observed during the first trace. Treating the managed module as an unspecialized module lets Dynamo trace its computation functionally and pass parameters at runtime.
This is the key connection between the eager state machine and compiled model body:
- eager pre-hook produces valid current-iteration full parameter views;
- Dynamo/Inductor executes a graph parameterized by those views;
- eager post-hook may free their storage after the graph returns.
Why FSDP2 still defines custom torch.ops.fsdp.* operators
The collectives package registers a small torch.library namespace with operators such as:
fsdp.all_gather_copy_in;fsdp.split_with_sizes_copy;fsdp.record_grad_output_stream; andfsdp.copy_.
Definitions and backend implementations are in _fsdp_collectives.py:34–350 and _fsdp_param.py:113–141.
These operators give mutations and buffer packing explicit dispatcher schemas, Meta implementations, and Functionalize implementations where needed. That makes the operations legible to FX/AOTAutograd when they cross a compiler boundary, instead of presenting an opaque Python mutation. It does not mean the normal FSDP hook state machine is swallowed into the model graph.
The test test_trace_fsdp_copy_ specifically verifies that fsdp.copy_ can be traced through an aot_eager compile while preserving its in-place result.
Compiled autograd still sees two eager boundaries
Compiled autograd captures a larger backward graph than ordinary eager autograd, but FSDP2 intentionally punctures that graph at its lifecycle hooks. The current source test spells out the expected result for a four-layer MLP with one fully_shard group:
- one graph break for
_pre_backward, registered on the FSDP module output; - one graph break for
post_backward, reached throughRegisterPostBackwardFunction.backward; and - the root final callback runs outside compiled autograd as an autograd-engine callback.
test_compiled_autograd_fsdp2_backward asserts one compiled-autograd capture but two separately compiled backend regions. So compiled autograd is supported; it simply does not erase the eager FSDP control points.
This differs from the DDP compilation problem. DDP’s reducer depends on per-parameter grad-accumulator hooks and uses DDPOptimizer graph partitioning to recover bucket overlap. FSDP2 already has explicit module/group boundaries, custom pre/post-backward insertion, and collectives launched from its eager state machine. It does not route through DDPOptimizer.
A practical setup order
For a model using only FSDP2:
1
2
3
4
5
6
7
8
mesh = init_device_mesh("cuda", (dist.get_world_size(),))
for block in model.blocks:
fully_shard(block, mesh=mesh, mp_policy=mp_policy)
fully_shard(model, mesh=mesh, mp_policy=mp_policy)
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
model.compile()
The important ordering is:
- apply model transforms that establish parameter layouts, such as tensor parallelism;
- apply
fully_shardbottom-up; - construct the optimizer from the now-sharded parameters; and
- compile the managed module’s computation.
Current tests cover TP plus mixed-precision FSDP2 both with and without compilation (test_fully_shard_compile.py:162–222). They also cover compiled optimizer steps for uneven shards, where a local parameter can be a narrowed N-D view while the reduced local gradient is a view of a flat buffer (test_fully_shard_compile.py:128–160).
What compilation does and does not optimize
| Concern | Eager FSDP2 | With torch.compile |
|---|---|---|
| Root/group discovery | Eager | Eager |
| Parameter all-gather | Eager hook path | Eager hook path |
| User forward operators | Eager kernels | Dynamo/AOTAutograd/Inductor region |
| Forward reshard | Eager hook path | Eager hook path |
| Pre/post-backward state transitions | Eager autograd hooks/functions | Intentional compiled-autograd graph breaks |
| Reduce-scatter / HSDP all-reduce | Eager hook path | Eager hook path |
| Root final callback | Autograd engine callback | Outside compiled-autograd region |
| Current unsharded parameter views | Installed per iteration | Passed into compiled computation |
This architecture gives up fusion across FSDP hook boundaries. In exchange, it keeps communication scheduling explicit and preserves block-level overlap while Inductor optimizes the expensive tensor programs inside each boundary.
Part 6 — Constraints worth knowing from the source
The current implementation documents several sharp edges:
- Parameter dtype and
grad_dtypemay change only before lazy initialization, meaning before first forward or an explicitunshard()(_fully_shard.py:132–138). - Writing parameters between forward and backward is unsafe when the unsharded representation is retained because backward communication is not ordered after arbitrary writes (
_fully_shard.py:217–220). - A custom nonzero sharding dimension currently requires even sharding (
_fsdp_param.py:349–356). - Resharding an already-
DTensorparameter onto a smaller post-forward mesh is not implemented (_fsdp_param.py:1000–1009). FSDPModuledeliberately does not supportdeepcopy; use state dicts for serialization (_fully_shard.py:314–317).- If an iteration throws midway through forward or backward, call
reset_iter_state()on the root before continuing. It waits outstanding work, reshares groups, and discards the failed iteration’s partial gradient state.
Reading a profiler trace after this deep dive
An FSDP2 trace can now be read as a storage-and-communication pipeline:
| Trace region | Interpretation |
|---|---|
| FSDP forward pre-hook | Materialize the group’s full parameters |
all_gather_copy_in | Pack padded local parameter shards |
all_gather_into_tensor | Exchange shards across the sharding process group |
| User module kernels | Compute with ordinary full parameter views |
| FSDP forward post-hook | Free or partially reshard those full parameters |
| FSDP pre-backward hook | Materialize parameters again if forward freed them |
| User backward kernels | Produce full gradients |
reduce_scatter_tensor | Sum/average gradients and retain only the local shard |
HSDP all_reduce | Synchronize that shard across replicas |
| Root final callback | Join events, finalize gradient views, release state |
The core mental model is:
fully_shardmakes the persistent parameter a shardedDTensor, then eager hooks temporarily lend each module a full ordinary parameter exactly when its computation needs one.
DeviceMesh says which ranks cooperate. DTensor says what each local shard means globally. FSDPState decides when the module crosses a lifecycle boundary. FSDPParamGroup schedules communication. FSDPParam preserves the parameter’s storage and aliasing invariants. torch.compile optimizes the tensor computation between those boundaries while intentionally leaving the distributed lifecycle eager.