Training a Trillion-Parameter Multimodal Model with FSDP2: A Practical Guide
A practical guide to training very large multimodal models with PyTorch FSDP2, covering memory and communication estimation, MFU calculation, model initialization and sharding, communication-computation overlap, and checkpoint saving, loading, and verification.
Training a Trillion-Parameter Multimodal Model with FSDP2: A Practical Guide
1. First, Estimate Memory, Communication, and MFU
Before training a 2.8-trillion-parameter multimodal model, start by estimating memory usage. Note that 2.8 trillion is an assumed scale used in this article and does not correspond to any public model—use your own model configuration for actual numbers.
With BF16 weights, the parameters alone take about 2.8×10¹² × 2 bytes = 5.6TB. With mixed-precision AdamW, each parameter also requires a BF16 gradient (2 bytes), FP32 master weights (4 bytes), and Adam’s first and second moments (4 bytes each), for roughly 16 bytes in total. Total model state is therefore 2.8×10¹² × 16 bytes ≈ 44.8TB. This figure excludes activations, communication buffers, and memory fragmentation.
Take 1,020 GPUs with 80GB each as an example: on average, each GPU must hold about 44GB of model state, leaving roughly 36GB for activations, communication buffers, and fragmentation. A single GPU cannot hold all the state, so parameters must be sharded across multiple GPUs.
Communication volume also needs to be estimated up front. Each FSDP2 training step involves two AllGathers (one in the forward pass, one in the backward pass) and one ReduceScatter. DDP requires only one AllReduce per step, and an AllReduce can be decomposed into a ReduceScatter plus an AllGather, giving communication unit counts of 3 versus 2. FSDP2 full sharding therefore has roughly 1.5× the theoretical communication volume of DDP. This ratio is based on data volume; actual time also depends on bandwidth and how well communication overlaps with computation.
Training efficiency is measured with MFU (Model FLOPs Utilization):
MFU = (tokens processed per second × training compute per token) / (total number of GPUs × peak FLOPS per GPU)
For a dense Transformer, the training compute per token can be approximated as 6N FLOPs, where N is the number of parameters involved in the computation; this ignores attention terms. For MoE models, use the parameters actually activated per token. MFU is the core metric for diagnosing performance issues—recompute it after every configuration change.
2. Environment and Versions
This article assumes PyTorch 2.6 or later, where fully_shard lives under torch.distributed.fsdp. In earlier versions, FSDP2 is located at torch.distributed._composable.fsdp with a different API. Before upgrading or downgrading, consult the official documentation for your version.
Recommended practices:
- Use the same container image on all nodes so that PyTorch, CUDA, and NCCL versions match.
- The checkpoint directory must be on a shared filesystem readable and writable by all nodes.
- Launch the training script with
torchrun:
torchrun --nnodes=$NNODES --nproc_per_node=8 \--rdzv_backend=c10d --rdzv_endpoint=$MASTER_ADDR:29500 \train.py
Useful environment variables:
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True: reduces memory fragmentation; try this first when you hit OOM.NCCL_DEBUG=WARN: for normal runs. Temporarily switch to INFO when debugging communication issues.NCCL_SOCKET_IFNAMEandNCCL_IB_HCA: configure according to your cluster’s network interfaces to ensure NCCL uses the high-speed network rather than regular Ethernet.
3. Initialization and Sharding
The traditional approach—building the full model on CPU or a single GPU and then sharding it—creates a memory spike. A more reliable workflow is:
- Build the model on the meta device, which records structure without allocating real memory.
- Call
fully_shardon each Transformer layer first, then on the root module. - Call
to_emptyto allocate the sharded storage on the local GPU. - Load weights with distributed checkpointing (DCP), where each GPU reads only its own shard.
The code structure is as follows. This is illustrative code that assumes the model has an llm.layers attribute and an init_non_persistent_buffers method:
import osimport torchimport torch.distributed as distimport torch.distributed.checkpoint as dcpfrom torch.distributed.checkpoint.state_dict import (get_model_state_dict,set_model_state_dict,)from torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicydef build_sharded_model(make_model, ckpt_dir):dist.init_process_group("nccl")local_rank = int(os.environ["LOCAL_RANK"])torch.cuda.set_device(local_rank)mesh = init_device_mesh("cuda", (dist.get_world_size(),))with torch.device("meta"):model = make_model()mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16,reduce_dtype=torch.float32,)for layer in model.llm.layers:fully_shard(layer, mesh=mesh, mp_policy=mp_policy)fully_shard(model, mesh=mesh, mp_policy=mp_policy)model.to_empty(device="cuda")state = {"model": get_model_state_dict(model)}dcp.load(state, checkpoint_id=ckpt_dir)set_model_state_dict(model, state["model"])# Non-persistent buffers are not in the checkpoint;# the model must regenerate them itselfmodel.init_non_persistent_buffers()return model
A few notes:
- Sharding is decided automatically by the framework based on the mesh; you don’t need to manually compute which GPU owns each parameter.
- Parameters are represented as DTensors, which record the full shape and sharding layout, so parameter names and shapes remain unchanged.
- Non-persistent buffers (e.g., certain positional encoding caches) are not saved and must be reinitialized after loading, otherwise results will be wrong.
For multimodal models, the sharding granularity can vary by module. Wrap each Transformer layer of the LLM individually so parameters can be gathered and released layer by layer. The vision encoder and projection layers have fewer parameters and can each be wrapped as a single unit to reduce communication rounds. Wrap the root module last to manage any parameters not covered by child units.
Larger sharding units mean fewer AllGathers but higher peak memory; smaller units save memory but increase communication rounds. Measure each module’s parameter and activation sizes before deciding on the sharding units.
Common parallelism strategies:
- FSDP2 full sharding: best for single-node multi-GPU or medium-scale clusters; the simplest to implement.
- HSDP (shard plus replicate): use when you have many nodes with limited inter-node bandwidth. Keep shard groups within a node and replication groups across nodes to reduce inter-node communication.
- FSDP2 plus tensor parallelism: consider when individual linear layers are especially large. Tensor parallelism communicates frequently and requires high intra-node bandwidth.
- Pipeline parallelism: consider when the model has many layers and needs to be split across nodes. It introduces pipeline bubbles and is more complex to implement and debug.
4. Forward, Backward, and Communication Overlap
During the forward pass, FSDP2 issues an AllGather before entering a sharded unit to collect its full parameters, then releases non-local parameter shards after the computation. During the backward pass, it AllGathers the required parameters again, and after computing gradients, uses ReduceScatter to shard gradients back to each GPU’s local shard. Gradient reduction uses FP32 to reduce numerical error.
Whether communication can be hidden behind computation depends on prefetching. By default, FSDP2 issues communication for the next unit while computing the current one. You can also set the prefetch order explicitly to ensure communication between adjacent layers has computation to overlap with:
layers = list(model.llm.layers)for cur, nxt in zip(layers[:-1], layers[1:]):cur.set_modules_to_forward_prefetch([nxt])for cur, prev in zip(layers[1:], layers[:-1]):cur.set_modules_to_backward_prefetch([prev])
With gradient accumulation, synchronizing gradients only on the last micro-batch reduces the number of ReduceScatters. Example training loop (assuming the object returned by the model’s forward contains a loss field):
def train(model, optimizer, loader, accum_steps, max_norm=1.0):model.train()for step, batch in enumerate(loader):is_sync = (step + 1) % accum_steps == 0model.set_requires_gradient_sync(is_sync)loss = model(**batch).loss / accum_stepsloss.backward()if is_sync:torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)optimizer.step()optimizer.zero_grad(set_to_none=True)
Whether communication and computation truly overlap must be confirmed with torch.profiler. In the trace, check whether NCCL AllGather and ReduceScatter kernels overlap in time with the forward and backward compute kernels. If communication always comes after computation, check the prefetch settings and sharding unit sizes.
5. Checkpoint Saving, Loading, and Verification
When saving, use DCP to save both model and optimizer state. When dcp.save returns, all ranks have finished writing. Rank 0 then writes a completion marker, and the loading side should only read checkpoints that carry the marker:
import jsonfrom torch.distributed.checkpoint.state_dict import get_state_dictdef save_checkpoint(model, optimizer, step, root):model_sd, optim_sd = get_state_dict(model, optimizer)path = f"{root}/step_{step}"dcp.save({"model": model_sd, "optim": optim_sd}, checkpoint_id=path)if dist.get_rank() == 0:meta = {"step": step, "world_size": dist.get_world_size()}with open(f"{path}/meta.json", "w") as f:json.dump(meta, f)open(f"{path}/.complete", "w").close()
There is an easily overlooked issue when loading. AdamW’s optimizer state is only created at the first step, so a freshly created optimizer has no state to load. You can run one step with zero gradients to allocate the state first; the checkpoint will then overwrite both parameters and state. This step changes parameters due to weight decay, but since the parameters are subsequently overwritten by the checkpoint, it does not affect the result.
from torch.distributed.checkpoint.state_dict import set_state_dictdef load_checkpoint(model, optimizer, path):for p in model.parameters():if p.requires_grad:p.grad = torch.zeros_like(p)optimizer.step()optimizer.zero_grad(set_to_none=True)model_sd, optim_sd = get_state_dict(model, optimizer)state = {"model": model_sd, "optim": optim_sd}dcp.load(state, checkpoint_id=path)set_state_dict(model,optimizer,model_state_dict=state["model"],optim_state_dict=state["optim"],)
After loading, verification is mandatory and should include at least two checks:
- Metadata verification: compare
world_sizeand the total number of elements across all parameters against what’s recorded inmeta.json. The total parameter count can be obtained by summing each rank’s local element counts. Ifworld_sizechanges, DCP can load with resharding, but this must be tested separately. - Numerical verification: when saving, record the loss on a fixed validation batch; after loading, recompute the loss on the same batch in eval mode under
no_gradand compare the two values. Small numerical differences are expected under BF16, and the tolerance threshold should be determined by your team’s baseline tests rather than set arbitrarily.
@torch.no_grad()def verify_loss(model, batch, expected, rtol=1e-2):model.eval()loss = model(**batch).loss.item()assert abs(loss - expected) <= rtol * abs(expected), (f"loss mismatch: got {loss}, expected {expected}")model.train()
