Training a Trillion-Parameter Multimodal Model with FSDP2: A Practical Guide

    This guide walks through the practical steps for scaling FSDP2 (fully sharded data parallelism) to train a 2.8-trillion-parameter multimodal model across hundreds of GPUs. It covers memory and communication estimation, constructing and sharding models on meta devices, choosing shard granularity per module, overlapping gradient sync with computation, handling data loading and cluster orchestration, and saving reliable checkpoints using PyTorch 2.6+ built‑in APIs.

    Intended Audience and Prerequisites

    This article is for engineers who have successfully run PyTorch training on a single multi‑GPU node and are ready to scale to multiple nodes. The code examples use PyTorch 2.6 or later, relying on the built‑in interface torch.distributed.fsdp.fully_shard. Before you start, measure the actual intra‑node and inter‑node bandwidth using nccl‑tests. All communication estimates in this article should be adjusted to your measured values.

    Estimating Memory and Communication First

    Knowing your model’s scale before training tells you how many GPUs you need. The estimates below assume a mixed‑precision AdamW optimizer.

    Memory per parameter:

    • BF16 weights: 2 bytes
    • BF16 gradients: 2 bytes
    • FP32 master weights: 4 bytes
    • FP32 first‑order momentum: 4 bytes
    • FP32 second‑order momentum: 4 bytes

    Total: about 16 bytes per parameter. For a 2.8‑trillion‑parameter model:

    • BF16 weights only: 2.8×10¹² × 2 bytes ≈ 5.6 TB
    • Full training state: 2.8×10¹² × 16 bytes ≈ 44.8 TB

    Assume 1024 GPUs with 80 GB each (128 nodes × 8 GPUs). The static state occupies about 43.75 GB per GPU, leaving roughly 36 GB for activations, full layers during the forward pass, and communication buffers. Activations grow with sequence length and batch size, so activation checkpointing is usually required to free space.

    Communication also needs careful estimation. With FSDP2, each step performs one parameter AllGather in the forward pass, another in the backward pass, and a ReduceScatter for gradients. For a ring‑based communication algorithm, the data sent/received by each GPU per step is about 3× the weight size (in BF16), i.e. about 16.8 TB per step. If the shard domain spans all nodes, inter‑node links quickly become the bottleneck. Therefore large‑scale training typically combines FSDP2 with tensor parallelism, pipeline parallelism, or HSDP (hybrid sharded data parallelism).

    Building the Model on Meta Device and Sharding

    A 2.8‑trillion‑parameter model cannot be allocated in CPU memory. The correct approach consists of five steps: initialize the process group and device mesh, build the model on the meta device, apply fully_shard module by module, allocate sharded storage and load weights with to_empty, and finally create the optimizer.

    1. # Environment: PyTorch >= 2.6, CUDA and NCCL versions compatible
    2. # Launch: torchrun --nnodes=128 --nproc_per_node=8 \
    3. # --rdzv_backend=c10d --rdzv_endpoint=$MASTER_ADDR:29500 train.py
    4. import os
    5. import torch
    6. import torch.distributed as dist
    7. from torch.distributed.device_mesh import init_device_mesh
    8. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    9. def main():
    10. dist.init_process_group(backend="nccl")
    11. local_rank = int(os.environ["LOCAL_RANK"])
    12. torch.cuda.set_device(local_rank)
    13. world_size = dist.get_world_size()
    14. # 1D device mesh: all GPUs participate in sharding
    15. mesh = init_device_mesh("cuda", (world_size,))
    16. # Build on meta device: only shapes and structure, no memory allocation
    17. with torch.device("meta"):
    18. model = build_multimodal_model() # user defined, returns an nn.Module
    19. mp_policy = MixedPrecisionPolicy(
    20. param_dtype=torch.bfloat16, # forward and backward compute in BF16
    21. reduce_dtype=torch.float32, # gradient reduction in FP32
    22. )
    23. # Wrap submodules first, then the root module
    24. for layer in model.language_model.layers:
    25. fully_shard(layer, mesh=mesh, mp_policy=mp_policy)
    26. fully_shard(model.vision_encoder, mesh=mesh, mp_policy=mp_policy)
    27. fully_shard(model.projector, mesh=mesh, mp_policy=mp_policy)
    28. fully_shard(model, mesh=mesh, mp_policy=mp_policy)
    29. # Replace meta tensors with actual sharded storage, then load weights
    30. model.to_empty(device="cuda")
    31. # Non‑persistent buffers (e.g. RoPE caches) have undefined content and must be recomputed here
    32. load_distributed_checkpoint(model, ckpt_dir) # user defined, based on torch.distributed.checkpoint
    33. # The optimizer must be created after sharding; optimizer states are sharded with the parameters
    34. optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)

    Three important points about this code:

    1. FSDP2 does not have an auto_wrap_policy argument. Automatic wrapping is implemented by manually calling fully_shard for each module.
    2. Inside build_multimodal_model() you must not create tensors with device="cuda" directly; otherwise you bypass the meta device.
    3. After to_empty, parameter content is undefined — you must immediately load weights or reinitialize them.

    Choosing Sharding Granularity per Module

    The components of a multimodal model have very different parameter distributions and communication patterns, so the shard granularity should be designed separately.

    • Transformer layers of the language model: Each layer acts as one communication unit. The parameter AllGather of the forward pass can overlap with the computation of the previous layer.
    • Vision encoder and projector: They have far fewer parameters than the language model. Wrap them as one unit to reduce the number of small messages and lower communication startup overhead.
    • Frozen modules: Frozen parameters are still sharded and undergo AllGather in the forward pass, but no gradients are produced, thereby reducing the ReduceScatter overhead in the backward pass.

    CPU offloading can also break through the memory bottleneck. fully_shard accepts offload_policy=CPUOffloadPolicy() to move unused shards to host memory. However, once offloaded, PCIe bandwidth becomes the new bottleneck. With a 44.8 TB training state, each of 128 nodes would hold on average about 350 GB in host memory. Reserve host memory accordingly, with extra headroom.

    Gradient Synchronization and Communication Overlap

    During the backward pass, FSDP2 performs a parameter AllGather for each unit, computes the gradient, and then performs a ReduceScatter, leaving only the sharded gradient on each GPU. This process is carried out unit by unit, so the communication of one unit can overlap with the computation of the previous unit.

    For the overlap to be effective, the following conditions must be satisfied:

    1. The computation time of the unit is greater than its communication time. If the unit is too small, the communication cannot be hidden behind computation.
    2. Prefetching is enabled. FSDP2 does implicit prefetch by default; you can also explicitly specify adjacent units with set_modules_to_forward_prefetch and set_modules_to_backward_prefetch.
    3. There is spare memory. Prefetching requires extra buffers; if memory is tight, OOM may occur.
    4. Inter‑node links are not saturated. The bandwidth of RoCE or InfiniBand must be checked against the results of nccl‑tests.

    To reduce inter‑node traffic, you can use HSDP. HSDP uses a 2D device mesh: sharding within a node, replication across nodes. Its gradient synchronization has two levels. Within a node, it uses ReduceScatter; between nodes, it performs AllReduce on the already‑sharded gradients. AllReduce only appears at the inter‑node level, not as a communication tree for all parameters. Intra‑node communication uses NVLink; inter‑node uses RoCE or InfiniBand.

    The HSDP mesh can be created as follows:

    1. mesh_2d = init_device_mesh("cuda", (num_nodes, 8), mesh_dim_names=("replicate", "shard"))
    2. fully_shard(layer, mesh=mesh_2d, mp_policy=mp_policy)

    If you observe periodic drops in GPU utilization per layer, or if communication kernels do not overlap with compute kernels in a profiler, the overlap is likely broken.

    Data Loading and Cluster Orchestration

    Image, video, and text pairs are usually stored in object storage. Directly reading many small files randomly will limit throughput. It is recommended to pack samples into larger shards, for example WebDataset tar format, and read them sequentially during training while caching them on local NVMe disks. The number of DataLoader workers and the prefetch depth should be determined by stress tests; the principle is to keep each GPU’s data supply rate at least as high as the GPU consumption rate.

    Message queues are suitable for offline preprocessing pipelines to decouple data cleaning and packaging. They should not be placed in the training read path, because the added latency would directly slow down every step.

    For cluster orchestration, you can use Kubernetes or Slurm. The monitoring system should collect GPU utilization, inter‑node bandwidth, and memory watermarks, and perform regular node health checks. Detect abnormal nodes, isolate them, and recover elastically.

    Checkpointing for Fault Tolerance

    Hardware failures are common in large‑scale training, so regular checkpoint saving is necessary. It is recommended to use torch.distributed.checkpoint (DCP) to write sharded checkpoints. Each GPU writes only its own parameter shards and optimizer states. Writes can be asynchronous to avoid blocking training.

    • Saving: All ranks use the same step number. After all shards are written, a commit marker is written. When resuming, ignore any incomplete checkpoints without a commit marker.