FSDP2 Training Adaptation for Trillion-Parameter Multimodal Models
This article explains how to adapt FSDP2 for training a 2.8-trillion-parameter multimodal model. It covers memory accounting, parameter sharding, meta-device initialization, sharding granularity across vision and LLM modules, gradient synchronization and communication overlap, DCP checkpointing, monitoring, and common troubleshooting.
1. Start with the Memory Budget
Take a 2.8-trillion-parameter model as an example. Memory requirements need to be considered separately. BF16 weights alone are about 5.6 TB (2.8 × 10^12 parameters × 2 bytes). This is the size of all parameters fully expanded during a single forward computation, not the resident training memory.
Mixed-precision training usually stores master weights in FP32 and keeps two FP32 momentum states for the Adam optimizer. The resident overhead per parameter is approximately: FP32 master weight 4 bytes, FP32 gradient 4 bytes, and Adam momentum 8 bytes, for a total of 16 bytes. On this basis, parameters, gradients, and optimizer states alone require about 44.8 TB. Activations, communication buffers, and fragmentation add further memory use. Therefore, a single GPU or a single node cannot hold the full model, and training must shard states across a large number of accelerators.
2. FSDP2 Shards by Parameter
The FSDP2 interface is torch.distributed.fsdp.fully_shard. It shards by parameter. Each parameter is represented as a DTensor and split along dimension 0 into world_size shards, with each GPU storing only its own shard. Model parameter names and structure remain unchanged, so optimizer and state_dict handling are relatively straightforward.
FSDP1 works differently. It concatenates parameters within an FSDP unit into a flat parameter and then shards that large tensor. This makes the correspondence between parameter names, gradients, and optimizer states harder to manage. FSDP2 avoids this problem, but you still need to understand the boundaries of sharding units because they determine communication timing and peak memory.
3. Environment Preparation
Before starting, confirm the following:
- PyTorch 2.6 or later.
fully_shardis undertorch.distributed.fsdpfrom this version onward. Earlier experimental interface paths and arguments may differ, so upgrading is recommended. - The CUDA version used to compile PyTorch matches the driver, and the NCCL version is consistent with the cluster.
- All nodes use the same image, driver, network configuration, and Python environment. Version inconsistency is a common cause of multi-node hangs.
- The checkpoint directory is on shared storage accessible from all nodes, and write permission is confirmed.
- Use
torchrunfor launch. Set the samemaster_addrandmaster_porton each node, and change onlynode_rank.
Example launch command:
torchrun --nnodes=4 --nproc_per_node=8 \--node_rank=$NODE_RANK \--master_addr=$MASTER_ADDR \--master_port=29500 \train.py
4. Build the Model on the meta Device
Instantiating a 2.8-trillion-parameter model directly on GPU will immediately cause OOM. Build the model structure on the meta device first, where no real GPU memory is allocated:
with torch.device("meta"):model = build_multimodal_model(cfg)
After sharding is complete, move the model to the real device:
model.to_empty(device="cuda")
to_empty only allocates memory and does not write valid values. Parameters must be loaded from a checkpoint or reassigned by initialization functions. Non-persistent buffers, such as position encoding caches, also need to be recomputed. Skipping this step can make the loss in the first few training steps NaN or abnormally large.
5. Sharding Granularity and Multimodal Modules
Within each sharding unit, FSDP2 evenly divides parameters across GPUs along dimension 0. It does not provide a configuration option for non-uniform sharding. Therefore, when the vision encoder, cross-modal alignment layers, and LLM backbone differ greatly in parameter count, you should balance memory by controlling the granularity of sharding units.
Specifically: make each LLM decoder layer a separate sharding unit; group the vision encoder by several blocks; and merge very small modules, such as projection layers and normalization layers, into adjacent units.
The code below shows this grouping approach. Attribute names need to be adjusted for your model structure:
import torchfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicydef apply_fsdp2(model, world_size):mesh = init_device_mesh("cuda", (world_size,))mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, # Parameter precision for forward and backward computereduce_dtype=torch.float32, # Gradient reduction precision; conservative setting)for block in model.vision_encoder.blocks:fully_shard(block, mesh=mesh, mp_policy=mp_policy)for layer in model.llm.layers:fully_shard(layer, mesh=mesh, mp_policy=mp_policy,reshard_after_forward=True)fully_shard(model, mesh=mesh, mp_policy=mp_policy)return model
There are two choices to note in this code.
First, master parameters are stored as FP32 shards and all-gathered in BF16 for computation. This way, the optimizer updates FP32 master weights with less precision loss.
Second, reduce_dtype is set to FP32 for more accurate gradient reduction, but communication volume is twice that of BF16. When bandwidth is tight, it can be changed to BF16, but you need to watch whether loss becomes unstable.
To check whether sharding is balanced, print the parameter byte count for each sharding unit. If the largest unit clearly exceeds the average, continue splitting it.
6. Gradient Synchronization and Communication Overlap
FSDP2 has two types of communication.
- Forward phase: each sharding unit performs all-gather before computation to retrieve full parameters.
- Backward phase: after the backward computation of each sharding unit completes, reduce-scatter is performed immediately to reduce gradients and shard them back to each GPU.
This streaming synchronization avoids network congestion caused by concentrated gradient transfer after backward completes. To overlap communication and computation, set up prefetching:
model.set_modules_to_forward_prefetch(prefetch_list)model.set_modules_to_backward_prefetch(prefetch_list)
reshard_after_forward controls whether full parameters are released after forward completes:
- Set to
True: parameters are released after forward, lowering memory use, but another all-gather is needed during backward. Use this when memory is tight. - Set to
False: full parameters are retained until backward, reducing communication count but increasing memory use. This is suitable for smaller units.
With gradient accumulation, earlier microsteps do not need gradient synchronization. You can disable synchronization during these microsteps and enable it only on the last microstep:
model.set_requires_gradient_sync(False) # Non-final microstepmodel.set_requires_gradient_sync(True) # Final microstep
Gradient clipping can directly use torch.nn.utils.clip_grad_norm_, which supports DTensor parameters.
limit_all_gathers is an FSDP1 configuration option and has no corresponding parameter in FSDP2. For tuning, use the prefetch and reshard_after_forward interfaces above.
7. Checkpoint Saving and Recovery
Training needs to be recoverable after interruption. For large models, checkpoints should use torch.distributed.checkpoint (DCP) to save sharded states. Each GPU writes its own shard, avoiding OOM caused by one GPU gathering the full model.
Both saving and recovery must be executed on all processes. After recovery, it is recommended to compare the loss of a fixed batch with the value before saving, and then continue training. When the checkpoint format or shard count changes, the recovery method also needs to be confirmed.
8. Monitoring Metrics
During training, record the following metrics:
- Peak memory per GPU, obtained with
torch.cuda.max_memory_allocated(). If peak values differ greatly across GPUs, sharding units are unevenly divided. - Time per step and token throughput.
- MFU (model compute utilization), i.e., actual compute divided by hardware peak compute. If MFU remains low for a long time, communication is usually not overlapping with computation.
- NCCL communication time. When debugging hangs or timeouts, set
NCCL_DEBUG=INFOto view detailed communication logs.
9. Common Troubleshooting
OOM during initialization. This usually means the model was not built on the meta device, or some large modules were not wrapped by fully_shard. Unwrapped parameters remain fully resident on each GPU. Check module wrapping one by one.
Loss is NaN or numerically abnormal at the first step. This often happens when parameters are not reinitialized or loaded from a checkpoint after to_empty, or when non-persistent buffers are not recomputed.
The first step hangs. Common causes are inconsistent world_size, master_addr, or port configuration across nodes, or a firewall blocking communication. First use NCCL_DEBUG=INFO to inspect connections on each node.
Memory peak is too high. Check whether a large unit has reshard_after_forward=False, or whether too many units are prefetched. Prefetching occupies memory in advance.
Throughput is low. Use a profiler to check whether all-gather and computation run in parallel. If they execute serially, try adjusting the prefetch list or appropriately reducing the sharding unit size.
