A Guide to Training Trillion-Parameter Multimodal Models with FSDP2
This article provides a comprehensive guide to training trillion-parameter multimodal models using PyTorch FSDP2. It covers memory estimation strategies, key differences between FSDP2 and FSDP1, and the four main phases of the training pipeline: model loading, parameter sharding, activation recomputation, and gradient synchronization. A runnable code example is included to demonstrate the complete workflow.
1. Estimate Memory First, Then Decide on a Sharding Strategy
In a common mixed-precision AdamW configuration, each parameter occupies approximately 16 bytes: 4 bytes for the FP32 parameter, 4 bytes for the FP32 gradient, and 4 bytes each for the Adam first and second-order moments. For a 2.8 trillion parameter model, the model states alone amount to about 44.8 TB (2.8×10^12 × 16 bytes). This figure does not include activations, communication buffers, or memory fragmentation, meaning the actual usage will be higher.
If you use FULL_SHARD to evenly distribute the model states across 1,024 GPUs, each GPU handles about 43.75 GB. When using 80 GB GPUs, the remaining space must accommodate activations, the fully expanded parameter buffers per layer, and communication buffers. If you only have 512 GPUs, the model states per GPU increase to about 87.5 GB. Sharding alone cannot satisfy this, requiring the introduction of activation recomputation or a larger sharding granularity.
When estimating, three conditions must be specified: parameter precision, optimizer type, and the number of shards. Switching to SGD with momentum or using 8-bit optimizers will change the number of bytes per parameter, altering the estimation accordingly.
Multimodal models have another characteristic: the layer shapes of the vision encoder and the language model are different. A single sharding strategy can easily waste memory. It is recommended to shard layer-by-layer per module rather than applying the same granularity to the entire model.
2. Key Differences Between FSDP2 and FSDP1
The public entry point for FSDP2 is torch.distributed.fsdp.fully_shard, which can be imported directly from this path starting in PyTorch 2.6. In PyTorch 2.4 and 2.5, this function was located at torch.distributed._composable.fsdp, a private path where the interface might change. For production environments, you should pin to PyTorch 2.6 or higher.
FSDP1 uses the FullyShardedDataParallel wrapper class, flattening multiple parameters into a FlatParameter before sharding. FSDP2 is based on DTensor and shards individual parameters, eliminating the need for flattening. This brings two main changes:
- Calling
fully_shardmodifies the module in place. The return value is the same module object, and the optimizer can directly usemodel.parameters(). - The
use_orig_paramsargument is no longer needed, and the original parameter names and structure remain unchanged.
Activation recomputation is also not a constructor parameter in FSDP2. You need to use torch.utils.checkpoint.checkpoint and set use_reentrant to False. Mixed precision is configured via MixedPrecisionPolicy, specifying the parameter precision during computation and the gradient reduction precision.
Applicability Boundaries: FSDP2 relies on PyTorch’s DTensor and collective communication operators. Heterogeneous computing platforms require vendor-provided builds matching this PyTorch version, and you must confirm that all_gather, reduce_scatter, and related operators can be called normally. If the vendor version only supports FSDP1, you must verify the operators and communication libraries before migrating.
3. Four Phases of the Training Pipeline
1. Model Loading
It is recommended to first build the model on a meta device, where parameters only record shapes without consuming memory. Subsequently, call fully_shard module by module, then materialize the sharded parameters, and finally restore the values from the sharded weight files.
Weights are typically saved as safetensors shard files, accompanied by an index file recording which file each parameter is located in. During loading, each process only reads the shards it is responsible for, which can be accomplished using dcp.load from torch.distributed.checkpoint. Load concurrency needs to be limited; for example, the number of files read simultaneously per node should not exceed 8 to avoid overwhelming the storage system. If a single read fails, use exponential backoff retry. If it still fails after 3 retries, terminate the task and preserve the logs. After loading, compare the parameter count, shapes, and checksums to ensure nothing is missing.
Unified Virtual Memory (UVM) allows CPU and GPU to share an address space, but it depends on the combination of drivers, runtime, and framework versions. Enable it only after it has been verified on the target GPU. If verification fails, fall back to chunked host-to-device copies, copying a few hundred megabytes at a time, and include synchronization points to control the memory peak.
2. Sharding and Activation Recomputation
The sharding granularity in FSDP2 is usually a Transformer layer or a block in the vision encoder. Before the forward pass, the parameters of this unit are gathered into a complete tensor via AllGather; after the forward pass, the parameters are released back to the sharded state, controlled by reshard_after_forward.
Activation recomputation discards some intermediate activations and recomputes them during the backward pass. Full recomputation adds roughly the computational cost of one extra forward pass. The overall increase in time consumption should be measured on the actual model. It is recommended to initially enable recomputation only on the language model layers, which have the highest memory footprint, and observe the time impact before deciding whether to expand the scope.
Prefetching can hide some communication latency. FSDP2 provides set_modules_to_forward_prefetch and set_modules_to_backward_prefetch to specify the modules to be prefetched for the next step. Overlapping only becomes noticeably effective when the compute time of a single layer is not shorter than the communication time of a single layer.
3. Gradient Synchronization and Communication Domain
In each training step, FSDP2 typically executes two AllGather operations (one for forward, one for backward) and one ReduceScatter. Under the ring algorithm, the data sent and received by each GPU is approximately 3 × (N−1)/N × parameter_bytes, where N is the number of shards. If the gradient reduction precision is FP32, the data volume for ReduceScatter is twice that of BF16.
Cross-node bandwidth is much lower than intra-node bandwidth, so large-scale training often uses Hybrid Sharded Data Parallel (HSDP). Using a 2D device mesh, sharding is done intra-node while replication is done across nodes, limiting high-volume AllGather to the high-speed interconnects and only transmitting gradients across nodes.
NCCL tuning parameters must correspond to the hardware. You can use torch.cuda.nccl.version() to confirm the version, and then set NCCL_SOCKET_IFNAME and NCCL_IB_HCA based on the network interface cards. When troubleshooting communication issues, set NCCL_DEBUG to WARN, and only increase it to INFO when actively diagnosing problems.
4. Runnable Example
The following code uses a small multimodal toy model to demonstrate the complete pipeline, including meta initialization, block-by-block sharding, mixed precision, activation recomputation, and the training loop. To replace it with a real model, simply modify the model definition and use dcp.load instead of random initialization.
# train_fsdp2.py# Dependencies: PyTorch >= 2.6, CUDA or vendor-adapted versionimport osimport torchimport torch.distributed as distimport torch.nn as nnfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicyfrom torch.utils.checkpoint import checkpointclass Block(nn.Module):def __init__(self, dim):super().__init__()self.norm = nn.LayerNorm(dim)self.ff = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))def forward(self, x):return x + self.ff(self.norm(x))
