FSDP2 in Practice: Key Points for Training Trillion-Parameter Multimodal Models
This article covers practical considerations for using FSDP2 to train trillion-parameter multimodal models. It discusses the target environment, why FSDP2 is needed, sharding differences from FSDP1, core implementation patterns for initialization, training loops, distributed checkpointing, HSDP topology, and communication overlap, as well as heterogeneous accelerator adaptation and troubleshooting for OOM and collective timeouts. Readers will learn the main implementation steps and validation points for production training.
FSDP2 in Practice: Key Points for Training Trillion-Parameter Multimodal Models
1. Scope and Environment
Multimodal large-model training is typically constrained by two issues. The first is the memory wall. Traditional DDP requires every accelerator to store the full model and optimizer state, so training cannot run once the model exceeds single-accelerator memory. The second is cross-node communication overhead. Pure tensor parallelism is limited by intra-node interconnect bandwidth, and scaling across nodes is often limited. FSDP2 is PyTorch’s fully sharded data parallel approach. It shards parameters, gradients, and optimizer states across all accelerators, gathers parameters through All-Gather before computation, and distributes gradients through Reduce-Scatter during backward.
The environment assumed in this article is as follows.
- PyTorch 2.6 or later. Starting from 2.6,
fully_shardcan be imported viafrom torch.distributed.fsdp import fully_shard. In earlier versions, the function was located in the private moduletorch.distributed._composable.fsdp; parameter names and behavior may differ, so consult the documentation for the version you use before deployment. - A PyTorch build provided by the accelerator vendor, with a collective communication library compatible with the NCCL API.
- Multi-node training is launched with
torchrun, with one process per accelerator.
The launch command template is below. Replace the node count and accelerators per node with actual cluster values.
torchrun --nnodes=4 --nproc_per_node=8 --node_rank=$NODE_RANK \--master_addr=$MASTER_ADDR --master_port=29500 train.py
The device type is referred to as device_type throughout this article. Its actual value is determined by the vendor’s PyTorch build, commonly "cuda" or a vendor-defined device name.
2. Why FSDP2 Is Needed
Memory usage can be estimated with a rough formula. For mixed-precision Adam, each parameter needs about 16 bytes: bf16 parameter and gradient at 2 bytes each, and fp32 master weight, first moment, and second moment at 4 bytes each. For 1 trillion parameters, the full training state is about 16 TB. When sharded across 512 accelerators, each accelerator holds about 31 GB, excluding activations and communication buffers. This number is only for order-of-magnitude illustration; actual usage must be measured at runtime.
FSDP2 shards this state across accelerators, and each accelerator stores only its own segment. Its communication volume is higher than DDP because parameters must be re-collected in every forward and backward pass. Training efficiency depends on whether communication can be hidden under computation, which is why prefetch and topology selection are discussed later.
3. Sharding Differences Between FSDP1 and FSDP2
Understanding the differences helps troubleshoot weight saving, loading, and memory anomalies.
| Item | FSDP1 | FSDP2 |
|---|---|---|
| Sharding object | Parameters within a wrapping unit are concatenated into a 1D FlatParameter and then sharded | Each original parameter is sharded along dim 0 across the device mesh |
| Parameter shape | Each rank holds a segment of the FlatParameter, which does not correspond to the original shape | Parameters are represented as DTensor with unchanged shape |
| Usage | Wrap the model with FullyShardedDataParallel |
Annotate modules in place with fully_shard |
| Weight saving | Requires handling the flattened structure and often relies on specific state dict configuration | Works with DTensor and distributed checkpointing to save shards directly |
| Debugging | Requires restoring the flattened structure first | Parameter shape and placement can be inspected directly |
An FSDP2 training step is roughly divided into the following stages.
- Forward: before entering a
fully_shardunit, All-Gather collects the full parameters of that unit. After computation, ifreshard_after_forward=Trueis set, parameters not in the local shard are released. - Backward: if parameters were released, All-Gather is performed again. After gradient computation, Reduce-Scatter is executed, and each accelerator keeps only the gradient corresponding to its own shard.
- Optimizer: updates are performed on sharded parameters, and each accelerator updates only its own segment.
4. Core Implementation
4.1 Initialization and Sharding
The following code provides a skeleton for one-dimensional sharding. device_type and the backend name need to be replaced with vendor-provided values.
import osfrom datetime import timedeltaimport torchimport torch.distributed as distfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicydevice_type = "cuda" # Replace with vendor-adapted valuelocal_rank = int(os.environ["LOCAL_RANK"])world_size = int(os.environ["WORLD_SIZE"])dist.init_process_group(backend="nccl", timeout=timedelta(minutes=10))getattr(torch, device_type).set_device(local_rank)mesh = init_device_mesh(device_type, (world_size,))mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)# Build the model on the meta device without allocating real memorywith torch.device("meta"):model = build_model(config) # User-defined model builder# Shard bottom-up; process the root module lastfor block in model.blocks:fully_shard(block, mesh=mesh, mp_policy=mp)fully_shard(model, mesh=mesh, mp_policy=mp)# Allocate real memory, then load weights from a checkpoint or run custom initializationmodel.to_empty(device=device_type)
There are three key points. First, the model must be built on the meta device; otherwise full weights land on a single accelerator first and may cause OOM during initialization. Second, submodules must be sharded first, and the root module last. Third, the optimizer must be created after sharding because parameters are already DTensor at that point.
optim = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0.1)
4.2 Training Loop
for step, batch in enumerate(loader):loss = model(**batch).lossloss.backward()torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)optim.step()optim.zero_grad(set_to_none=True)
When using gradient accumulation, gradient synchronization should be disabled for non-final micro-batches to reduce the number of Reduce-Scatter operations.
model.set_requires_gradient_sync(False) # Non-final micro-batchloss.backward()model.set_requires_gradient_sync(True) # Final micro-batch
4.3 Distributed Checkpointing
Distributed checkpointing (DCP) lets each rank write only its own shard without first aggregating the full model to rank 0. All ranks must call save and load; otherwise, the job will hang due to mismatched collectives.
import torch.distributed.checkpoint as dcpfrom torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dictdef save_ckpt(model, optim, ckpt_dir):model_sd, optim_sd = get_state_dict(model, optim)dcp.save({"model": model_sd, "optim": optim_sd}, checkpoint_id=ckpt_dir)def load_ckpt(model, optim, ckpt_dir):model_sd, optim_sd = get_state_dict(model, optim)state = {"model": model_sd, "optim": optim_sd}dcp.load(state, checkpoint_id=ckpt_dir)set_state_dict(model, optim,model_state_dict=state["model"],optim_state_dict=state["optim"],)
DCP supports loading the same checkpoint with a different number of accelerators, i.e., resharding. This capability depends on the PyTorch version in use and should be validated in a test environment before production use.
4.4 HSDP Topology Selection
HSDP (hybrid sharded data parallel) uses a two-dimensional device mesh. The shard dimension runs within a node, and the replicate dimension runs across nodes.
mesh_2d = init_device_mesh(device_type,(num_nodes, gpus_per_node),mesh_dim_names=("replicate", "shard"),)for block in model.blocks:fully_shard(block, mesh=mesh_2d, mp_policy=mp)fully_shard(model, mesh=mesh_2d, mp_policy=mp)
The following principles can guide topology selection.
- The shard dimension should align with the intra-node high-speed interconnect so that frequent parameter All-Gather stays within the node as much as possible.
- A larger replicate dimension increases per-accelerator memory usage because the shard share becomes smaller. Cross-node gradient synchronization also increases network pressure.
- If communication has become a bottleneck under full sharding and memory headroom exists, consider HSDP. If memory is tight, prioritize full sharding.
4.5 Compute and Communication Overlap
FSDP2 automatically prefetches parameters for adjacent sharded units, overlapping the next unit’s All-Gather with current computation. When finer control is needed, the prefetch order can be set explicitly.
blocks = list(model.blocks)for cur, nxt in zip(blocks[:-1], blocks[1:]):cur.set_modules_to_forward_prefetch([nxt])for cur, prev in zip(blocks[1:], blocks[:-1]):cur.set_modules_to_backward_prefetch([prev])
Deeper prefetch provides more overlap but also raises peak memory because more parameters reside in memory at the same time. When tuning, record both per-step time and peak memory. The last unit usually enters backward immediately after forward, so consider setting reshard_after_forward=False for it to avoid one repeated collection. The benefit should be confirmed by measurement.
5. Heterogeneous Accelerator Adaptation
Most issues in heterogeneous environments appear at the version and library level. Check in the following order.
- Verify the mapping between the vendor PyTorch version and the upstream version, and confirm that DTensor, DCP, and
fully_shardwork correctly. - Confirm bf16 compute and communication support. If the vendor library has an incomplete Reduce-Scatter implementation for certain dtypes, use another
reduce_dtypeand record the impact. - Confirm that the collective communication library covers all data type and shape combinations for All-Gather and Reduce-Scatter.
- Avoid mixing different accelerator models in the same job. When memory capacity differs, sharding is configured according to the smaller-capacity accelerators, reducing utilization.
- Before scaling up, align the loss curve with a small single-node model. Use results from a reference platform as a control and confirm that numerical error is within an acceptable range.
6. Troubleshooting OOM and Collective Timeouts
The following table lists common failures, diagnosis methods, and resolutions.
| Symptom | Possible cause | Diagnosis | Resolution |
|---|---|---|---|
| OOM during initialization | The model was not built on the meta device, so full weights landed on a single accelerator first | Check whether construction code is inside a torch.device("meta") context |
Wrap in the meta context, shard, then call to_empty |
| OOM in forward or backward, with peak memory growing with sequence length | Activation memory is too large | Record peak memory at different sequence lengths | Enable activation checkpointing (torch.utils.checkpoint) or reduce micro-batch size |
| Memory savings below expectation | reshard_after_forward=False or prefetch too deep, causing parameters to remain resident for too long |
Check parameter placement and release timing for each unit | Keep default resharding for middle layers and reduce prefetch depth |
| Optimizer state OOM | The optimizer was created before fully_shard |
Check whether optimizer parameters are DTensor | Create the optimizer after sharding |
| Startup hangs and then times out | Inconsistent number of collectives across ranks, e.g., different data amounts lead to different step counts, or one rank throws an exception early | Compare step counts and last call stacks across ranks | Ensure the same step count per rank; on exception, exit all ranks together |
| Multi-node collective timeout | NIC, routing, or communication library misconfiguration | Run the vendor bandwidth test and enable communication library debug logs to inspect path selection | Pin the NIC and correct communication library environment variables |
| Checkpoint save timeout | Only some ranks enter dcp.save, or storage bandwidth is insufficient |
Check whether all ranks execute the save branch | All ranks call save; use shared storage and verify write bandwidth |
| Abnormal loss after loading | state dict key mismatch or inconsistent precision policy | Compare mean and variance of parameters before and after loading | Use get_state_dict consistently for keys and fix the precision policy |
When debugging collective timeouts, temporarily increase the timeout so that logs retain more information.
dist.init_process_group(backend="nccl", timeout=timedelta(minutes=30))
The following environment variables use NVIDIA NCCL as an example. Other vendor libraries may use different variable names; follow the vendor documentation.
NCCL_DEBUG=INFO: outputs initialization and path selection information.NCCL_SOCKET_IFNAME: specifies the NIC used for communication.NCCL_IB_HCA: specifies InfiniBand devices.
7. Risks and Validation Criteria
The following items should be validated in a test environment before entering production training.
- Checkpoint consistency: after saving, load with the original accelerator count and with a different accelerator count, and compare parameter checksums and the loss for the first few steps after loading.
- Version compatibility: after upgrading PyTorch or the vendor library, rerun a minimal case for sharding, saving, and loading.
- Communication correctness: confirm that the vendor library’s All-Gather and Reduce-Scatter results match a reference implementation.
- Performance measurement: fix the batch size, skip warmup steps, and report the median per-step time and communication share. This article does not provide speedup numbers; actual numbers depend on the cluster network and accelerator type.
8. Summary
FSDP2 reduces per-accelerator memory through parameter sharding and uses All-Gather and Reduce-Scatter to move parameters and gradients during forward and backward passes. In deployment, first ensure the model is built on the meta device, shard bottom-up, and create the optimizer after sharding. Use DCP for checkpoints and have all ranks participate. Align the shard dimension with the intra-node high-speed interconnect. When troubleshooting, first check whether each rank follows the same execution path, then inspect network and communication library configuration.
