flowchart TB
classDef default color:#0081c2, stroke:#0081c2;
subgraph G0 [GPU 0]
S0[stores shard 0 of every parameter] --> A
A([all-gather: this layer's parameters, in full]) --> C0[forward + backward]
C0 --> R([reduce-scatter: each GPU keeps<br>its shard of the gradients])
R --> O0[optimizer updates<br>the local shards only]
end
subgraph G1 [GPU 1]
S1[stores shard 1 of every parameter] --> A
C1[forward + backward] --> R
R --> O1[optimizer updates<br>the local shards only]
end
When the model does not fit one GPU
DDP replicates: every GPU holds the whole model, so per-GPU memory is whatever one GPU would need. When that is too much — the arithmetic says a 7-billion-parameter model wants about 104 GiB for weights, gradients, and optimizer state before a single activation — replication is the wrong strategy. Fully sharded data parallel (FSDP) splits the training state across GPUs, and each GPU stores only its fraction.
Example
Our course CNN trains comfortably on one GPU, so sharding it would be artificial. The following script demonstrates the mechanics on a synthetic model instead, and it runs on plain CPUs (the sharding logic does not need GPUs):
Here are the key points in that script:
mesh = init_device_mesh("cpu", (world_size,)) # "cuda" and NCCL in production
for block in model.blocks: # shard the children first...
fully_shard(block, mesh=mesh)
fully_shard(model.head, mesh=mesh)
fully_shard(model, mesh=mesh) # ...the root lastThe order matters: sharding the root module first would freeze its view of unsharded children. After this loop, the model’s parameters are DTensors: tensors with a global shape and local storage. Code that reads p.shape still sees the global tensor; p.to_local() exposes the shard this rank actually holds.
You can run the script quickly from the command line on 2 CPUs with:
$ torchrun --nproc-per-node 2 fsdp_demo.pymodel created: 8,407,050 parameters
parameters visible per rank after sharding: 8,407,050 (global shape)
parameters actually stored per rank: 4,203,525 (~1/2 of the model)
one sharded step OK, loss 2.308
distributed checkpoint written to fsdp_ckpt/
Half the parameters stored per rank, as promised. The rest of the demo takes one training step, and the code for it is exactly the single-GPU code — loss, backward(), optimizer.step() — because the gathering and scattering happen inside the sharded modules. FSDP’s whole point is that the training loop does not know about the sharding.
Distributed checkpoints
torch.save(model.state_dict()) would silently save each rank’s local view of the DTensors, incomplete on its own. Distributed checkpoints (DCP) handle sharded state: every rank writes its own shards, and a load can even re-shard into a different world size (resume your 8-GPU training on 4):
state = {"model": get_model_state_dict(model)}
save(state, storage_writer=FileSystemWriter("fsdp_ckpt"))The fsdp_ckpt/ directory of the demo holds one .distcp file per rank. For long training runs, DCP also has an asynchronous variant that saves on a background thread, so checkpoints do not stall the training loop.
From DDP to FSDP
Nothing from the DDP section is discarded; four things change:
- Replace the
DDP(model, ...)wrap with thefully_shardcalls (children first, root last). Do not use both on one model. - If the GPUs are recent (Ampere and later), add a mixed-precision policy so gathered parameters compute in bf16:
fully_shard(..., mp_policy=MixedPrecisionPolicy(param_dtype=torch.bfloat16))— the same hardware gate as our autocast decisions, one level down. - Replace
torch.savecheckpoints with DCP, and load withdcp.load+set_model_state_dict. - Keep everything else:
torchrun, theDistributedSampler, rank-0-only printing, the all-reduced metrics.
When does FSDP beat DDP? Only when the model does not fit. The sharded flow gathers and scatters parameters at every layer of every step, which is more communication than DDP’s one gradient all-reduce — so FSDP is slower than DDP on a model that fits on one GPU. The two levers answer different questions: DDP buys speed, FSDP buys capacity.
The wider map
Data parallelism (DDP, FSDP) is one axis of a small map. Tensor parallelism splits individual matrix multiplications across GPUs; pipeline parallelism splits the layers into stages; context parallelism shards very long input sequences. At transformer scale they are combined; torchtitan is PyTorch’s reference implementation of such recipes, and a good place to see FSDP2 used in earnest. For research training up to a few billion parameters, what this page covers is the standard answer.
Your turn:
Run the demonstrator with 4 ranks (torchrun --nproc-per-node 4 fsdp_demo.py). Predict the two parameter counts and the number of files in fsdp_ckpt/ before you run it. Then break it on purpose: shard the root module first and try again.
- Hint:
fully_shardre-shards what it is given; a root sharded before its children sees modules it can no longer wrap.