Training FSDP2 for Trillion-Parameter Multimodal Models
This article explains how to train trillion-parameter multimodal models using PyTorch's FSDP2 (Fully Sharded Data Parallel, tensor-level sharding). It covers the key challenges of massive multimodal training, environment setup, the differences between FSDP1 and FSDP2, practical model sharding with code examples, distributed checkpointing, prefetching and communication overlapping, gradient sync and HSDP, CPU offload boundaries, and optimization tips. The guide is hardware-agnostic and focuses on scalable, production-ready training techniques using PyTorch 2.6+ and torch.distributed.
Why Trillion-Parameter Multimodal Training Is Hard
Multimodal large models have reached trillion-parameter scale. The model weights alone occupy several terabytes of storage. Adding optimizer states, gradients, and activations, the memory of a single accelerator is far from sufficient. Traditional pure data parallelism keeps a full copy of the model on every GPU, which becomes impossible at this scale.
Training issues typically fall into three categories:
- Insufficient memory: Parameters, gradients, and optimizer states all need to reside in accelerator memory. The larger the model, the more each device must hold.
- High communication overhead: After parameter sharding, forward and backward passes require frequent all-gather and reduce-scatter operations. If the sharding granularity is not well chosen, the network becomes a bottleneck and cluster scaling efficiency drops.
- Hardware diversity: Different accelerator vendors have different communication libraries, memory hierarchies, and kernel implementations. A training script written for one platform often does not achieve optimal performance on another.
This article does not target any specific hardware vendor. It discusses general training framework usage. The code examples use PyTorch. Choose the communication backend that matches your hardware platform (e.g., nccl for NVIDIA GPUs).
Environment and Version Requirements
FSDP2 is PyTorch’s tensor-level sharded data parallel implementation. We recommend PyTorch 2.6 or later, importing directly from torch.distributed.fsdp. In PyTorch 2.4 to 2.5, the equivalent interfaces live under torch.distributed._composable.fsdp, with mostly identical APIs, but these early paths are not recommended for long-term production use.
The training script depends on the following components:
- PyTorch 2.6 or newer, matching the communication library version of your platform
- A distributed communication library that supports your selected backend
- A distributed file system or object storage client for reading and writing checkpoints
Launch multi-node jobs with torchrun:
torchrun \--nnodes=4 \--nproc_per_node=8 \--rdzv_backend=c10d \--rdzv_endpoint=${MASTER_ADDR}:29500 \train.py --ckpt-dir /data/ckpt
Each process obtains its local device ID via the LOCAL_RANK environment variable. The global rank identifies the process in the entire cluster and should not be used directly as a device ID.
FSDP2 vs. FSDP1
FSDP1 wraps the model at module granularity, and its interface is a wrapper class. Internally it uses FlatParameter to pack parameters. FSDP2 applies fully_shard directly to modules, and parameters are stored as DTensor on each rank. Key differences are:
- API: FSDP2 uses a functional API. No model wrapping is needed; the original module structure and parameter names remain intact.
- Sharding granularity: FSDP2 allows different sharding settings for different submodules. This is especially useful for multimodal models where the vision encoder, language model, and alignment layers have very different structures.
- State dict: FSDP2 parameters are DTensors, so distributed checkpointing can save and load per-shard directly without gathering to a single rank first.
If your project already runs on FSDP1, validate on a small model that the loss and gradient curves match after migration. New projects can use FSDP2 directly.
Model Building and Sharding Example
The following code assumes the model has three parts: vision_encoder, language_model, and align_proj. The vision encoder and language model each contain repeated blocks or layers. Replace the attribute names with those in your own model.
import osimport torchimport torch.distributed as distfrom torch.distributed.fsdp import (fully_shard,CPUOffloadPolicy,MixedPrecisionPolicy,OffloadPolicy,)def setup_distributed(backend="nccl"):dist.init_process_group(backend=backend)local_rank = int(os.environ["LOCAL_RANK"])torch.cuda.set_device(local_rank) # bind to the local devicereturn local_rankdef build_fsdp2_model(model_cls, model_cfg, device, offload_params=False):# Build the structure on the meta device without allocating real storagewith torch.device("meta"):model = model_cls(model_cfg)mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16,reduce_dtype=torch.float32, # use fp32 for gradient reduction to reduce numerical error)offload = CPUOffloadPolicy(pin_memory=True) if offload_params else OffloadPolicy()# First shard the innermost repeated modules, then move outwardfor block in model.vision_encoder.blocks:fully_shard(block, mp_policy=mp_policy, offload_policy=offload)for layer in model.language_model.layers:fully_shard(layer, mp_policy=mp_policy, offload_policy=offload)fully_shard(model.vision_encoder, mp_policy=mp_policy, offload_policy=offload)fully_shard(model.language_model, mp_policy=mp_policy, offload_policy=offload)fully_shard(model.align_proj, mp_policy=mp_policy, offload_policy=offload)fully_shard(model, mp_policy=mp_policy, offload_policy=offload)# Allocate real storage for the local shards, then load weightsmodel.to_empty(device=torch.device("cpu") if offload_params else device)return model
The sharding order matters. Shard inner modules first so that the outer module only manages the parameters not already managed by inner modules, avoiding duplicate management of the same parameter.
The vision encoder and language model can use different sharding granularities. For example, if the vision encoder has a relatively small number of parameters, you can shard the entire encoder at once, reducing the number of communication operations. The language model has large per-layer parameters and should be sharded per layer to allow prefetching of the next layer during computation. The optimal granularity depends on measured throughput; there is no fixed answer.
Sharded Loading and Checkpoints
For trillion-parameter models, you must not load the full weights into a single process. The correct approach is to let each rank load only its own shard. PyTorch’s distributed checkpoint module supports this: each rank writes its own shard during saving, and during loading each rank reads the part it needs, with no full-model aggregation step at any point.
import torch.distributed.checkpoint as dcpfrom torch.distributed.checkpoint.state_dict import (get_model_state_dict,set_model_state_dict,)def load_sharded_checkpoint(model, ckpt_dir):model_state = get_model_state_dict(model)state = {"model": model_state}dcp.load(state_dict=state, checkpoint_id=ckpt_dir)set_model_state_dict(model, state["model"])def save_sharded_checkpoint(model, ckpt_dir):state = {"model": get_model_state_dict(model)}dcp.save(state_dict=state, checkpoint_id=ckpt_dir)
With this approach, during loading each rank only holds its own shards. During forward passes, FSDP2 gathers full parameters layer by layer on demand and releases them after computation. Therefore, the peak memory during loading is directly related to the per-rank shard size, not the total model size.
The checkpoint directory contains metadata and per-rank data files. The training script should record the world size and sharding configuration at save time. If you resume with a different cluster size, the distributed checkpoint module can repartition the data, but you should first verify on a small environment that the loss resumes smoothly.
Sharding Scheduling and Computation Overlap
FSDP2 execution can be summarized as: during forward, each layer performs All-Gather to collect parameters, computes, then releases non-local shards; during backward, it computes gradients and uses Reduce-Scatter to reduce gradients to the corresponding shards. To reduce waiting, communication should overlap with computation.
A common practice is prefetching. FSDP2 provides interfaces to set forward and backward prefetch order. For example:
layers = list(model.language_model.layers)for prev, nxt in zip(layers[:-1], layers[1:]):prev.set_modules_to_forward_prefetch([nxt])for prev, nxt in zip(layers[1:], layers[:-1]):prev.set_modules_to_backward_prefetch([nxt])
Whether prefetching helps depends on the ratio of compute time to communication time. If each layer computes very quickly, the prefetched parameters may not arrive before they are used. In that case, increase the computation per sharded layer or reduce the sharding granularity.
CUDA Graphs can reduce kernel launch overhead, but they require the computation graph to remain identical across iterations. Multimodal inputs often have variable sequence lengths, making graph capture invalid. Only enable graph capture if input shapes are fixed and your backend explicitly supports it. Compare loss and throughput with and without capture before committing.
Gradient Synchronization and Communication Optimization
With FSDP2, gradient synchronization is performed automatically during the backward pass; no manual All-Reduce is needed. At large cross-node scales, you can use Hybrid Sharded Data Parallel (HSDP), which organizes devices into a 2D grid: sharded within a node, replicated across nodes. This keeps most communication inside the node, and only gradients are synchronized across nodes.
from torch.distributed.device_mesh import init_device_meshmesh = init_device_mesh("cuda",(num_nodes, gpus_per_node),mesh_dim_names=("dp_replicate", "dp_shard"),)fully_shard(model, mesh=mesh)
In multimodal models, interactions between different modalities can be sparse. You may use smaller communication domains for those layers, but this requires custom sharding functions and adds code complexity. Do not do this unless you have measured benefits.
Gradient compression can reduce communication traffic, but it introduces quantization error, potentially affecting convergence speed and final accuracy. If you try it, use a toggle to enable/disable it, and compare loss curves against an uncompressed baseline.
When using gradient accumulation, you can disable gradient synchronization for non-final micro-batches to reduce communication:
for i, batch in enumerate(loader):is_last = (i + 1) % accum_steps == 0model.set_requires_gradient_sync(is_last)loss = model(batch) / accum_stepsloss.backward()if is_last:optimizer.step()optimizer.zero_grad()
When to Use CPU Offloading
CPU offloading moves unused parameters and optimizer states to host memory, significantly reducing accelerator memory usage. The cost is data movement between host memory and accelerators, limited by PCIe bandwidth and host memory bandwidth.
CPU offloading is suitable in the following scenarios:
- Memory is severely limited, and reducing the shard count or lowering the batch size still does not allow training. This is a fallback rather than a performance optimization. Only use it when saving accelerator memory is more important than training speed.
```
(Note: The original text ends mid-sentence. We have preserved the meaning and completed the logical flow without adding new content.)
