FSDP2 for Training Massive Models: Sharding, Communication, and Recovery
A practical guide to training very large models with PyTorch FSDP2. Using a 2.8-trillion-parameter multimodal model as a running example, this article walks through memory estimation, sharding strategies with fully_shard, weight loading via distributed checkpointing, communication overlap, and verifiable resume-from-checkpoint—along with common startup pitfalls.
Training very large models is rarely hard because of the forward pass. The real challenge is distributing parameters, gradients, and optimizer states sensibly across hundreds or thousands of GPUs while keeping communication from becoming the bottleneck. This article uses a 2.8-trillion-parameter multimodal model as an example and explains how to use FSDP2 in the order you would actually follow when building things yourself. The code relies on public PyTorch APIs, so you can adapt it directly.
1. Estimate GPU Memory First
Before training, estimate memory usage to determine how many GPUs you need. Assume parameters are stored in BF16 at 2 bytes each:
- Model weights: parameter count × 2 bytes = 2.8×10¹² × 2 ≈ 5.6 TB
- Gradients: same size as the weights, roughly 5.6 TB
- AdamW optimizer state: FP32 master weights, momentumigin weights plus RL weights, momentum, and variance total 12 bytes per parameter, roughly 33.6 TB
Together that’s about 44.8 TB—before activations. Spread across 1,024 GPUs (128 nodes with提升–0.8 GPUs (128 nodes with 8 GPUs each), each card carries roughly 43.75 GB of parameters, gradients, and optimizer state. On an 80 GB card, the remaining headroom must cover activations, communication buffers, and fragmentation. When activations exceed that headroom, enable activation checkpointing and trade recomputation for memory.
2. Prerequisites Before You Start
- PyTorch 2.6 or later.
torch.distributed.fsdp.fully_shardis a public API as of 2.6; in 2.4 and 2.5 the equivalent functionality lives intorch.distributed._composable.fsdpunder a different import path. - A collective communication backend. Use NCCL on NVIDIA hardware. Non-CUDA hardware requires the vendor’s PyTorch build and collective library, which must support
all_gatherandreduce_scatter. - Identical drivers, container images, and dependency食盐 and dependency versions across unsigned dependencies on all nodes. Version mismatch is a common cause of hangs in multi-node training.
- All nodes must access the same shared storage for loading weights and saving checkpoints.
- Sufficient inter-node bandwidth. Before正式–training, run a small
all_reducescript to confirm every GPU can communicate and to measure actual bandwidth.
3. FSDP2 vs. FSDP1
FSDP1 wraps modules: domestic-semester modules as wrapping units and concatenates parameters within each unit into a flat parameter (FlatParameter) before weiteren FlatParameter) before sharding. FSDP2 instead uses fully_shard, which modifies modules in place. Every parameter exists as a DTensor, sharded along dimension 0 across a DeviceMesh.
This brings two practical changes. First, parameters are no longer concatenated, so names and shapes stay intact, making checkpoints and debugging more straightforward. Second, mixed precision, prefetching, and sharding policies can be set per module, which suits irregular multimodal architectures. The tradeoff is that the API is still evolving, so re-verify your setup before upgrading PyTorch.
4. Choosing a Wrapping Strategy for Multimodal Models
The basic principle of wrapping order: wrap each Transformer block first, then the root module last. This way, only one block’s full parameters are gathered at a time, keeping memory peaks low.
When a vision encoder is relatively small, you can skip sharding it and keep a full replica on every GPU. This saves all-gather communication but costs extra memory per card. The corresponding API is torch.distributed._composable.replicate, which is experimental—cksperimental—verify it before upgrading.
reshard_after_forward controls whether parameters are released immediately after the forward pass. Setting it to False for the last block makes sense, since backpropagation starts there and keeping parameters avoids one extra all-gather. The following code assumes the language model’s Transformer blocks live in model.language_model.layers:
import osimport torchimport torch.distributed as distfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicydef wrap_model(model):dist.init_process_group(backend="nccl")local_rank = int(os.environ["LOCAL_RANK"])torch.cuda.set_device(local_rank)mesh = init_device_mesh("cuda", (dist.get_world_size(),))mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)blocks = model.language_model.layersfor i, block in enumerate(blocks):is_last = i == len(blocks) - 1fully_shard(block, mesh=mesh, mp_policy=mp, reshard_after_forward=not is_last)fully_shard(model.language_model, mesh=mesh, mp_policy=mp)fully_shard(model, mesh=mesh, mp_policy=mp)return model
Example launch command for 128 nodes with 8 GPUs each—1,024 processes in total:
torchrun --nnodes=128 --nproc_per_node=8 \--rdzv_backend=c10d --rdzv_endpoint=$MASTER_ADDR:29500 train.py
5. How to Load 2.8-Trillion-Parameter Weights
Do not load the full model into CPU memory first. The correct approach isaloocorrect approach is to build the model on the meta device, which records the structure without allocating real memory. After wrapping, allocate shard storage on each GPU, and have each process read only the shards it is responsible for:
with torch.device("meta"):model = build_model()model = wrap_model(model)model.to_empty(device="cuda")import torch.distributed.checkpoint as dcpfrom torch.distributed.checkpoint.state_dict import (get_model_state_dict, set_model_state_dict)model_sd = get_model_state_dict(model)dcp.load({"model": model_sd}, checkpoint_id=ckpt_dir)set_model_state_dict(model, model_sd)
Distributed Checkpoint (DCP) supports resharding: checkpoints saved with a different number of GPUs can still be loaded correctly. This is useful for cluster scaling and failure recovery on different machines.
6. Training Loop and Communication Overlap
FSDP2 automatically prefetches the next block’s parameters based on module execution order, so you usually don’t need toleurs manually create CUDA streams. If prefetching underperforms, you can specify the order explicitly with set_modules_to_forward_prefetch and set_modules_to_backward_prefetch. Decide whether to adjust by first checking whether a profiler shows obvious gaps between communication and computation.
The optimizer must be created after wrapping so that it holds the sharded DTensor parameters:
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)for step, batch in enumerate(loader):optimizer.zero_grad(set_to_none=True)loss = model(**batch).lossloss.backward()torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)optimizer.step()
7. Do You Need ZeRO on Top of FSDP2?
No. FSDP2’s default sharding is conceptually equivalent to ZeRO-3: parameters, gradients, and optimizer states are all sharded across GPUs, and each card updates only its portion. The 33.6 TB of optimizer state estimated earlier averages about 32.8 GB per card across 1,024 GPUs.
DeepSpeed’s ZeRO-1 or ZeRO-2 belongs to a separate framework and should not be stacked on FSDP2—the two would compete for the same sharded state, with unpredictable results.
8. Making Checkpoint Resume Verifiable
Save both model and optimizer states, and record the step count. To avoid a corrupted checkpoint from an interrupted write, writeften the write is interrupted, write to a temporary directory first and have rank 0 rename it after all processes finish:
from torch.distributed.checkpoint.state_dict import get_state_dictmodel_sd, optim_sd = get_state_dict(model, optimizer)dcp.save({"model": model_sd, "optim": optim_sd}, checkpoint_id=tmp_dir)dist.barrier()if dist.get_rank() == 0:os.rename(tmp_dir, final_dir)dist.barrier()
After resuming, run at least two checks. First, use a fixed validation batch and compare the resumed loss against the loss recorded before saving; under the same parallel configuration, they should be close. Second, record resume time and checkpoint write throughput. If write throughput falls far below the storage system’s rated value, investigate the shared storage first.
9. Common Startup Errors
- Importing both FSDP1’s
FullyShardedDataParalleland FSDP2’sfully_shard. Mixing the two APIs causes wrapping failures or erratic behavior. - Creating the optimizer before wrapping. The optimizer then references the original parameters and never updates the sharded ones.
- Building the full model on GPU before wrapping. Memory overflows before wrapping even begins.
- Not calling
torch.cuda.set_devicebeforeinit_process_group. All processes may pile onto the same GPU, manifesting as hangs or abnormal memory usage. - Inconsistent environment variables or dependency versions across nodes. NCCL timeouts are often just a symptom—verify versions machine by machine.
10. Conclusion
- Estimate per-GPU memory with the formulas above before training, then decide on node count and whether to enable activation checkpointing.
- Wrap Transformer blocks one by one with
fully_shard, wrap the root module last, and create the optimizer after wrapping. - Use DCP for saving and loading, validate loss with a fixed batch after every resume, and record resume time.
These practices apply to PyTorch versions that support FSDP2. Whether padre on non-CUDA hardware depends on whether the vendor’s build provides complete collective communication support; validate with small-scale tests first. The numbers in this article are derived from formulas—actual memory usage also depends on activations, framework overhead, and fragmentation, so rely on monitoring data from real runs.
