FSDP2 in Practice: Training Trillion-Parameter Multimodal Models
A practical guide to training trillion-parameter multimodal models with PyTorch FSDP2, covering GPU memory estimation, per-parameter sharding versus FSDP1, sharding granularity, runnable skeleton code, communication topology, distributed checkpointing, an OOM troubleshooting checklist, and performance profiling.
1. Do the Memory Math First
Before training a trillion-parameter model, estimate the memory footprint. With mixed-precision AdamW, each parameter typically consumes 16 bytes: 2 bytes for the bf16 parameter, 2 bytes for the bf16 gradient, 4 bytes for the fp32 master weight, 4 bytes for the fp32 first moment, and 4 bytes for the fp32 second moment.
For a 2.8-trillion-parameter model, model states alone require roughly 44.8 TB (2.8×10¹² × 16 bytes). With full sharding across 1,024 GPUs, each GPU holds about 44 GB of model states, and you still need headroom for activations, communication buffers, and fragmentation. With only 512 GPUs, per-GPU model states exceed 80 GB, which no longer fits on a single card. The sharding group must therefore be large enough—confirm this during cluster planning.
These numbers cover only model states. Activations grow with batch size and sequence length, and usually require activation checkpointing to stay under control.
2. How FSDP2 Differs from FSDP1
FSDP1 wraps the model at the module level: parameters within a module are flattened into a single FlatParameter and then sharded. FSDP2 instead shards per parameter: each parameter tensor is split along dimension 0 and represented as a DTensor, so sharded parameters keep their original names and logical shapes.
This has three practical implications. First, the wrapping approach differs. In FSDP2 you call fully_shard on submodules one by one—for example, on each Transformer block first, and finally on the root module. Second, the optimizer must be created after sharding; otherwise it will hold references to unsharded parameters. Third, checkpoints are saved as DTensors, so use torch.distributed.checkpoint for saving and loading instead of manually reassembling full weights.
Regarding versions: in PyTorch 2.6 and later, the API lives under torch.distributed.fsdp. In PyTorch 2.4 and 2.5, it is available as an experimental API under torch.distributed._composable.fsdp. When migrating a legacy project from FSDP1, first verify on a small model that the loss curve closely matches FSDP1, then scale up.
3. Choosing Sharding Granularity for Multimodal Models
Sharding granularity determines the size and number of all-gather operations. Finer granularity means smaller individual communications and lower peak memory, but more collective calls, so launch overhead takes a larger share. Coarser granularity means fewer communications and better bandwidth utilization, but more full parameters must be temporarily materialized, raising peak memory.
When choosing granularity, compare two durations: the forward or backward compute time of a single sharding unit, and the all-gather communication time for that unit. If communication is shorter than computation, it can be hidden by overlapping, and the granularity is roughly appropriate. Otherwise, merge adjacent units to reduce the number of communications, or switch to a higher-bandwidth communication group.
A vision encoder (such as a ViT) has relatively few parameters and modest per-block compute; common practice is to shard per block, or to treat the entire encoder as one unit. The language model is much larger, so sharding per decoder layer is more suitable. The exact boundary must be determined empirically—no single granularity works for every model.
Tensor parallelism (TP) is often combined with FSDP2. A typical setup confines TP within a single node, using NVLink for the large partitioned matrix multiplications, while FSDP2 handles data-parallel sharding across nodes. This keeps TP’s high-frequency communication on high-bandwidth links, leaving only FSDP parameter and gradient traffic on the inter-node network.
4. Runnable Skeleton Code
This code targets PyTorch 2.6 and later, launched with torchrun across multiple nodes, for example:
torchrun --nnodes=4 --nproc_per_node=8 train.py
The code assumes the model exposes vision_encoder.blocks and language_model.layers; replace these with the actual attribute names. Very large models should be built on the meta device first, with weights loaded per shard, to avoid host memory exhaustion.
import osimport torchimport torch.distributed as distimport torch.nn as nnfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicydef build_fsdp2_model(model: nn.Module) -> nn.Module:world_size = dist.get_world_size()# 1D device mesh: all GPUs participate in parameter shardingmesh = init_device_mesh("cuda", (world_size,))mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, # forward and backward in bf16reduce_dtype=torch.float32, # gradient reduction in fp32 to limit accumulation error)# Shard submodules first, then the root modulefor block in model.vision_encoder.blocks:fully_shard(block, mesh=mesh, mp_policy=mp_policy, reshard_after_forward=True)for layer in model.language_model.layers:fully_shard(layer, mesh=mesh, mp_policy=mp_policy, reshard_after_forward=True)fully_shard(model, mesh=mesh, mp_policy=mp_policy)return modeldef main():dist.init_process_group("nccl")torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))model = build_multimodal_model() # placeholder: returns an unsharded multimodal modelmodel = build_fsdp2_model(model)# Create the optimizer only after sharding is completeoptimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0.1)for batch in dataloader: # placeholder: data loaderloss = model(**batch).lossloss.backward()optimizer.step()optimizer.zero_grad()dist.destroy_process_group()if __name__ == "__main__":main()
For gradient accumulation, call model.set_requires_gradient_sync(False) on the root module for all but the last micro-batch, then call set_requires_gradient_sync(True) before the last one. This avoids a gradient reduction on every micro-batch.
5. Gradient Synchronization and Communication Topology
FSDP2 relies on two main collectives: all-gather to materialize full parameters before forward and backward computation, and reduce-scatter to reduce gradients back to each shard during the backward pass. Ring-AllReduce mainly appears in full-replica data parallelism such as DDP; it is a different communication pattern from sharded training, and the two should not be conflated.
In multi-node settings, a 2D device mesh enables hybrid sharded data parallelism (HSDP). The intra-node dimension shards parameters, while the inter-node dimension replicates them and all-reduces gradients. This confines parameter all-gather and reduce-scatter to intra-node NVLink, leaving only gradient all-reduce traffic between replicas on the inter-node network.
mesh = init_device_mesh("cuda", (num_nodes, gpus_per_node), mesh_dim_names=("replicate", "shard"))fully_shard(model, mesh=mesh)
The communication group size should align with the number of GPUs per node. Before deployment, run nvidia-smi topo -m to inspect GPU interconnects, and set NCCL_DEBUG=INFO to confirm which algorithms and channels NCCL selects.
6. Checkpointing and Resuming Training
The larger the cluster, the more frequent hardware failures become. The checkpoint interval trades save overhead against lost progress. Given a per-save duration T_save and a mean time between failures (MTBF), a common estimate for the optimal interval is √(2 × T_save × MTBF), known as Young’s formula. For example, with a 2-minute save and a 6-hour (360-minute) MTBF, the optimal interval is about 38 minutes. In practice, also consider whether storage bandwidth is sufficient and whether saving blocks training.
Use distributed checkpointing so each rank writes only the shards it owns, avoiding the single-node bottleneck of gathering full weights. When resuming with a different GPU count, use an API that supports resharding on load; otherwise the shard layout must remain consistent.
7. OOM Troubleshooting Checklist
When OOM occurs, check in the following order:
- Confirm the model is built on the meta device and weights are loaded per shard, rather than building the full model on a single GPU before sharding.
- Print per-GPU bytes of parameters, gradients, and optimizer states after sharding, and compare against the estimates in Section 1. If the deviation is large, check dtypes and optimizer settings.
- Enable
reshard_after_forwardon every sharding unit and confirm full parameters are released after the forward pass. - Enable activation checkpointing and verify the granularity covers the largest layers.
- Reduce the micro-batch size and use gradient accumulation to keep the global batch size unchanged.
- Set
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:Trueto mitigate fragmentation-induced OOM. - Record the peak with
torch.cuda.max_memory_allocated()to determine whether it occurs during forward, backward, or the optimizer step. - If model states alone exceed per-GPU capacity, increase the number of sharding GPUs.
8. Performance Profiling
Use torch.profiler to capture an end-to-end timeline, export a Chrome Trace, and inspect it in TensorBoard or Perfetto. Focus on three things: whether all-gather overlaps with the previous layer’s forward computation; whether reduce-scatter overlaps with subsequent layers’ backward computation; and in which phase the GPU idle gaps within each step are concentrated.
If all-gather sits exposed on the critical path for long periods, first try merging adjacent small sharding units, adjusting the communication group size, and checking the NCCL version and network configuration. If GPU idle time concentrates in data loading, increase prefetching and the number of data loader workers.
Conclusion
Three things matter most in building a training pipeline for trillion-parameter multimodal models. First, use byte-level memory estimates to determine the sharding scale. Second, choose sharding granularity based on the ratio of communication to computation time, and use HSDP to keep high-frequency communication within nodes. Third, ensure long-term stability through distributed checkpointing, an OOM checklist, and timeline profiling. FSDP2’s per-parameter sharding makes these steps more straightforward, but version differences and migration details still need to be validated one by one in small-scale experiments.
