What does PyTorch 2.14's FSDP2 fully_shard do to a model's parameters, and what changes for code written against FSDP1?
answer
- per-parameter, nothing flattened
- DTensor sharded on dim 0
- each block first, then the root
- build the optimizer afterwards
- reshard_after_forward None: True except the root
basics
~20 sfully_shard swaps each parameter in place for a DTensor sharded on dim 0 across the mesh and all-gathers each call's group around forward and backward. FSDP1's wrapper, FlatParameter and ShardingStrategy give way to per-block calls and reshard_after_forward.
solid answer
~40 sIn PyTorch 2.14, `fully_shard(module)` does not wrap the model: it replaces `model.parameters()` in place with DTensors sharded on dim 0 over the device mesh, keeps the parameter names, and adds hooks that all-gather each call's group before forward and backward, free it afterwards and reduce-scatter the gradients. You call it on each transformer block, then on the root, and only then build the optimizer from the DTensor parameters. FSDP1's `FullyShardedDataParallel` flattened each wrapped unit into one `FlatParameter` and chose behaviour with `ShardingStrategy`; in FSDP2 `FULL_SHARD` becomes `reshard_after_forward=True`, `SHARD_GRAD_OP` becomes `False`, `HYBRID_SHARD` becomes a 2D mesh, `MixedPrecision` becomes `MixedPrecisionPolicy` and `no_sync()` becomes `set_requires_gradient_sync(False)`. Left unset, `reshard_after_forward` is `None`: true for every block, false for the root.
code
python · 22 linesimport torch
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
mesh = init_device_mesh("cuda", (256,))
mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
with torch.device("meta"):
model = Decoder70B() # model.layers: 80 transformer blocks
for block in model.layers:
fully_shard(block, mesh=mesh, mp_policy=mp)
fully_shard(model, mesh=mesh, mp_policy=mp) # root: embeddings, norm, head
model.to_empty(device="cuda")
model.reset_parameters()
optim = torch.optim.AdamW(model.parameters(), lr=1e-4) # DTensor params
for i, batch in enumerate(micro_batches):
model.set_requires_gradient_sync(i == len(micro_batches) - 1)
model(batch).backward() # model returns the loss
optim.step()
optim.zero_grad()go deeper
Recall that fully_shard turns each parameter into a DTensor shard and that you apply it to every transformer block before the root.
Explain the hook cycle — gather before forward, free after, gather again in backward, reduce-scatter gradients — and why the optimizer must be built from the sharded parameters.
Show the migration judgment: map ShardingStrategy onto reshard_after_forward and meshes, choose an int reshard for multi-node backward gathers, and weigh skipped gradient sync against the memory it costs.
Decide whether a team's FSDP1 code base moves to FSDP2 now, weighing composability with DTensor tensor parallelism and new state-dict handling against retesting a stable pipeline.
## What `fully_shard` does to the parameters **FSDP2** is PyTorch's per-parameter implementation of fully sharded data parallelism, exposed as `torch.distributed.fsdp.fully_shard`. Its contract in PyTorch 2.14: - It converts `model.parameters()` **in place** from plain tensors to **DTensors** sharded on dim 0 across the device mesh — placement `(Shard(0),)` on a 1D mesh — so each of N ranks stores 1/N of every parameter. - It does not wrap the module. The module's class becomes one that is also an `FSDPModule`, and the fully qualified parameter names in `model.state_dict()` stay exactly as they were. - Each call forms one **communication group**. A pre-forward hook all-gathers the group's shards into full tensors and a post-forward hook frees them; in backward the group is gathered again when needed, gradients are computed, the full weights are freed and the gradients are **reduce-scattered** so each rank keeps the shard it owns. - The optimizer must be built from the DTensor parameters, after sharding, and its step updates only the local shard. ## Applying it to a 70B decoder 1. Build the model on the `meta` device so no rank materializes 70B parameters. 2. Call `fully_shard` on every transformer block. 3. Call `fully_shard` on the root; it groups what is left — embeddings, final norm, output head. 4. Materialize with `model.to_empty(device="cuda")` and initialize, or load weights (loading a checkpoint is the checkpointing material's subject). 5. Create the optimizer from `model.parameters()`. Calling `fully_shard` only on the root puts every parameter in one group: one all-gather of the whole model before forward, one reduce-scatter after backward and no overlap with compute. Per-block groups let the next block's gather overlap the current block's compute. FSDP2 has no `bucket_cap_mb`; the groups you create **are** the buckets. ## `reshard_after_forward`: memory against communication - `True` — free each block's full weights after forward and gather them again in backward. - `False` — keep them until backward, saving one all-gather per block at the cost of holding full weights. - `None`, the 2.14 default — `True` for non-root modules and `False` for the root, because the root's parameters are needed as soon as backward begins. - An `int` — after forward, keep the weights sharded over a smaller group, such as the 8 GPUs of one node, so the backward gather stays inside the node; it must be a non-trivial divisor of the shard dimension's size. ## Mixed precision, offload and accumulation - `MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)` gathers and computes in bf16 while the sharded parameters and the optimizer step stay in their original dtype, fp32 here; `reduce_dtype` sets the precision of the gradient reduction. The policy acts at module boundaries, not per operation as autocast does. - `CPUOffloadPolicy()` keeps sharded parameters, gradients and optimizer states in host memory and runs the optimizer step on the CPU; its `pin_memory` defaults to `True`. - `model.set_requires_gradient_sync(False)` on accumulation micro-steps skips the gradient reduction. FSDP2 then holds the unreduced, unsharded gradients until the micro-step that syncs, so skipping communication costs memory. ## Moving FSDP1 code FSDP1 (`FullyShardedDataParallel`) still ships and is still documented in PyTorch 2.14; the FSDP2 page points its users to a migration guide. | FSDP1 | FSDP2 (`fully_shard`) | |---|---| | wrapper class with an `auto_wrap_policy` | call `fully_shard` on each block, then the root | | one `FlatParameter` per wrapped unit | the original parameters, as DTensors | | `ShardingStrategy.FULL_SHARD` | `reshard_after_forward=True` | | `ShardingStrategy.SHARD_GRAD_OP` | `reshard_after_forward=False` | | `ShardingStrategy.HYBRID_SHARD` | `reshard_after_forward=True` on a 2D mesh | | `MixedPrecision` | `MixedPrecisionPolicy` (no `buffer_dtype`; buffers are not sharded) | | `CPUOffload(offload_params=True)` | `offload_policy=CPUOffloadPolicy()` | | `no_sync()` | `set_requires_gradient_sync(False)` | | `state_dict_type(...)` with `StateDictType` | `model.state_dict()` already returns DTensor shards | In 2.14, FSDP1's `state_dict_type()` emits a `FutureWarning` that points to the `get_state_dict` / `set_state_dict` helpers; how sharded checkpoints are written and resharded is a separate subject. ## Mistakes interviewers listen for - Building the optimizer before `fully_shard`: it holds the tensors that sharding replaced, which never receive gradients. - Calling `fully_shard` only on the root and wondering why nothing overlaps. - Saying `reshard_after_forward` is `True` everywhere by default. - Describing FSDP2 as flattening parameters, or FSDP1 as removed.
- When would you pass an int to `reshard_after_forward` on a 256-GPU run of eight-GPU nodes?When the backward all-gather across 256 ranks on 32 nodes is the bottleneck and memory has room. `reshard_after_forward=8` keeps each block sharded across the eight GPUs of a node between forward and backward, so the backward re-gather runs inside the node. The cost is holding 1/8 of each block instead of 1/256 until backward; the int must be a non-trivial divisor of the shard size.
- What happens to memory when FSDP2 skips gradient sync on accumulation micro-steps?With `set_requires_gradient_sync(False)` FSDP2 does not reduce-scatter, so each rank keeps the full, unsharded gradients of every group until the micro-step that syncs; with `reduce_dtype` set, it accumulates them in that dtype. You trade communication for memory — on a model that only fits because gradients are sharded, syncing every micro-step can be the only option.
- An FSDP1 job used `ShardingStrategy.HYBRID_SHARD`. What is the FSDP2 equivalent on 32 nodes of eight GPUs?A 2D device mesh of shape (32, 8) passed to `fully_shard`, which places parameters as `(Replicate(), Shard(0))`: sharded across the eight GPUs of a node and replicated across nodes, with `reshard_after_forward=True`. Gathers stay inside the node; gradients are reduce-scattered within the node and all-reduced across nodes.
- fully_shard wraps the model, so parameter names gain a wrapper prefix
- Calling fully_shard once on the root module is enough for good overlap
- reshard_after_forward is True for every module, the root included, by default
- FSDP2 still flattens each wrapped unit into a FlatParameter
- The optimizer can be built before fully_shard and still sees the shards
- FSDP1 was removed from PyTorch in the 2.x line
Assumes PyTorch 2.14.1: fully_shard's reshard_after_forward=None default, its DTensor parameters and FSDP1 still shipping beside it are checked against that release.