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

    This guide walks through sharded training of trillion-parameter models with PyTorch FSDP2. It covers memory estimation, environment setup and validation, multimodal data loading, gradient synchronization, checkpointing, fault detection, and a pre-launch checklist.

    1. Memory Estimation: Calculate Model States First, Then Set the Sharding Scale

    When training trillion-parameter models, GPU memory usually becomes the bottleneck before compute does. The first step in estimating memory is to calculate the footprint of the model states. This estimate rests on the following assumptions: an Adam-style optimizer is used, parameters and gradients are stored in BF16 or FP16, and the optimizer keeps an FP32 master copy of the parameters along with FP32 first-order and second-order momentum. Under these assumptions, the bytes per parameter break down as follows.

    Item Bytes per parameter Notes
    Parameters (low precision) 2 Used in forward and backward computation
    Gradients (low precision) 2 Produced during backpropagation
    FP32 master parameters 4 Authoritative copy updated by the optimizer
    First-order momentum 4 Adam’s m
    Second-order momentum 4 Adam’s v
    Total 16 Of which 12 bytes are optimizer-related

    If the FP32 master parameters are not stored, and the first-order and second-order momentum are still stored in FP32, the optimizer portion drops to 8 bytes, and the total becomes 12 bytes per parameter. With 8-bit optimizers, momentum is stored differently, so you need to recalculate according to the documentation of the library you use. This guide uses 16 bytes per parameter throughout, so the resulting estimates are conservative.

    Take a model with 2.8 trillion parameters as an example. The total model state is 2.8×10^12 × 16 bytes = 44.8 TB (decimal, where 1 TB = 10^12 bytes), and the optimizer states account for 33.6 TB. If 1024 GPUs form one sharding group (K = 1024) without tensor or pipeline parallelism, each GPU carries about 43.75 GB of model state on average.

    Let P be the number of parameters, K the FSDP sharding group size, and M the model-parallel degree (the product of the tensor-parallel and pipeline-parallel degrees). The model state per GPU is then approximately:

    1. Model state per GPU ≈ 16P / (K × M)

    Model parallelism first splits the model into M parts. FSDP then shards each part across K GPUs.

    Beyond model states, several other costs cannot be ignored:

    • Activations: These depend on the micro-batch size, the sequence length, and whether activation recomputation is enabled. They do not decrease linearly with K.
    • Gather buffers: When computing a layer, the full parameters of that layer must be temporarily held. In BF16, a single layer with 500 million parameters requires about 1 GB.
    • Communication buffers: Their size is determined by the communication bucket size.
    • Memory fragmentation: After long runs, the allocator may leave gaps that cannot be reused.

    There is no general margin ratio for these items. Measure the peak memory on a small-scale job, then reserve headroom based on the measured values.

    Choosing K involves a trade-off between memory and communication. A larger K reduces the model state per GPU, but each all-gather and reduce-scatter involves more GPUs, which increases communication volume and latency. Sharding groups should ideally stay within the same high-speed interconnect domain, such as a single node or a single high-speed network subdomain. Sharding groups that span nodes usually communicate more slowly.

    The relationship between the total GPU count N and K depends on the parallelism plan. With hybrid sharding (HSDP), N = K × R × M, where R is the number of data-parallel replicas. Do not interpret K as the total number of GPUs.

    2. FSDP2 Setup and Validation

    2.1 Environment Requirements

    • PyTorch 2.6 or later. The fully_shard interface is available as a public API starting from this version. Earlier versions expose a different interface, so consult the documentation for the relevant version before upgrading or downgrading.
    • NCCL, or the collective communication library provided by your hardware vendor. Its version must match your driver and CUDA versions.
    • Launch with torchrun, binding each process to one GPU.

    For the installation command, refer to the current PyTorch website. Using CUDA 12.4 as an example:

    1. pip install torch --index-url https://download.pytorch.org/whl/cu124

    The launch command for training on a single machine with 8 GPUs is:

    1. torchrun --nproc_per_node=8 train_fsdp2.py

    Multi-node training requires adding --nnodes and rendezvous-related parameters. For the exact syntax, see the documentation for your version.

    2.2 Minimal Runnable Example

    The script below uses a stack of linear layers to simulate the sharding workflow of a large model. It calls fully_shard on each layer, then calls it once more on the root module, and prints the loss and peak memory at every step.

    1. import os
    2. from datetime import timedelta
    3. import torch
    4. import torch.distributed as dist
    5. import torch.nn as nn
    6. from torch.distributed.device_mesh import init_device_mesh
    7. from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
    8. def main():
    9. dist.init_process_group(backend="nccl", timeout=timedelta(minutes=10))
    10. local_rank = int(os.environ["LOCAL_RANK"])
    11. torch.cuda.set_device(local_rank)
    12. world_size = dist.get_world_size()
    13. mesh = init_device_mesh("cuda", (world_size,))
    14. mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
    15. model = nn.Sequential(*[nn.Linear(4096, 4096) for _ in range(8)]).cuda()
    16. for layer in model:
    17. fully_shard(layer, mesh=mesh, mp_policy=mp)
    18. fully_shard(model, mesh=mesh, mp_policy=mp)
    19. # Create the optimizer after fully_shard. At this point, the parameters are already sharded tensors.
    20. optim = torch.optim.AdamW(model.parameters(), lr=1e-4)
    21. for step in range(20):
    22. x = torch.randn(8, 4096, device="cuda").to(torch.bfloat16)
    23. loss = model(x).float().pow(2).mean()
    24. loss.backward()
    25. optim.step()
    26. optim.zero_grad()
    27. if dist.get_rank() == 0:
    28. peak = torch.cuda.max_memory_allocated() / 2**30
    29. print(f"step {step} loss {loss.item():.4f} peak_mem {peak:.2f} GiB")
    30. dist.destroy_process_group()
    31. if __name__ == "__main__":
    32. main()

    Key points in this code:

    • The optimizer must be created after fully_shard. Otherwise, it holds unsharded parameters.
    • Setting reduce_dtype to FP32 reduces precision loss during gradient reduction.
    • The memory statistics call a CUDA interface. On non-NVIDIA devices, use the equivalent interface provided by the vendor.

    2.3 Validation Metrics and Pass Criteria

    After setup, validate in the following order. Move to the next step only after the current one passes.

    1. Single-GPU smoke test: Without sharding, confirm that the model’s forward pass, backward pass, and optimizer step all run to completion.
    2. One-GPU and two-GPU alignment: Fix the random seed and data, then compare the loss over the first few steps. The two should be essentially identical. Small differences caused by floating-point operation ordering are normal.
    3. Communication performance: Use a profiler or nccl-tests to measure the throughput of all-gather and reduce-scatter. Confirm that it reaches a reasonable fraction of the theoretical bandwidth of the interconnect. If the fraction is low, check the topology and how the sharding groups are partitioned.
    4. Peak memory: Record max_memory_allocated and max_memory_reserved. A large gap between the two indicates severe fragmentation, which you can address using the methods in Section 4.
    5. Throughput and loss curve: Record the number of tokens processed per second and the loss curve, then compare them with a single-GPU or small-scale baseline.

    2.4 Adapting to Non-Mainstream Hardware and Fallback Options

    On AI computing hardware outside the NVIDIA ecosystem, adaptation usually involves three steps.

    Step 1: Confirm the framework backend. You need a PyTorch plugin or backend from the hardware vendor so that device_mesh and fully_shard can recognize the device. Check the vendor’s documentation for the backend name and version.

    Step 2: Verify collective communication. Run a minimal all-reduce test first, then run all-gather and reduce-scatter. Start training only after all three operations pass. Some operators may be missing on new hardware, and the framework will then fall back to slower implementations. Use the profiler to check for a large number of such fallbacks.

    Step 3: Design a fallback path. If FSDP2 is not yet available on the hardware, first get the workflow running with data parallelism on a few GPUs on a single machine, then scale up to sharded training. Alternatively, fall back to FSDP1, or to a combination of data parallelism and distributed checkpointing. The validation criteria for the fallback match those of the main approach: aligned loss, communication at the expected level, and controlled memory usage.

    3. Multimodal Data Loading and Gradient Synchronization

    3.1 Multimodal Data Loading

    In multimodal training, images, videos, and text differ greatly in compute cost. Data loading often becomes the bottleneck before compute does. The practices below reduce this risk.

    • Data sharding: Each process reads different samples to avoid duplicate reads. Use DistributedSampler or an equivalent streaming split, and verify that the split stays consistent across epochs.
    • Preprocessing and caching: Complete image decoding, tokenization, and feature extraction offline whenever possible, and cache the results. Online decoding consumes CPU time on the main process and slows every step.
    • Length bucketing: Group samples of similar length into the same batch to reduce wasted computation on padding.
    • Prefetching: Configure num_workers, pin_memory, and persistent_workers for the DataLoader, and tune them based on measured data throughput.

    Multimodal models usually consist of a vision encoder and a language model. You can wrap each part separately so that the sharding granularity matches each component’s structure. If the vision encoder is frozen, set requires_grad to False for its parameters to avoid unnecessary gradient computation and communication.

    3.2 Gradient Synchronization and Accumulation

    In FSDP2, backpropagation uses reduce-scatter to aggregate gradients. There are three main tuning points related to gradient synchronization.

    • Sharding granularity: Wrap modules at the level of Transformer blocks or modules of similar size. Overly fine granularity creates many small communication operations and lowers bandwidth utilization. Overly coarse granularity increases the peak size of the gather buffers.
    • Overlap of communication and computation: Confirm that all-gather overlaps with the forward computation, and that reduce-scatter overlaps with the backward computation. The profiler timeline shows this directly.
    • Gradient accumulation: Intermediate micro-steps do not need gradient reduction at every step. You can call set_requires_gradient_sync(False) on the root module, and restore synchronization only for the last micro-batch. Availability of this interface varies by version, so confirm it before use.

    Pay close attention to gradient clipping. After sharding, each GPU holds only part of the gradients. When using clip_grad_norm_, confirm that your version computes the global gradient norm correctly. To check this, run a fixed small batch and compare the gradient norm from sharded training with the result from a single GPU. A mismatch indicates a problem in the clipping implementation.

    4. Stability and Fault Tolerance

    4.1 Distributed Checkpointing

    Save sharded state with torch.distributed.checkpoint. Each GPU writes only the portion it owns, so the amount written per GPU is comparable to its memory footprint rather than the size of the full model. This format supports restoring onto a different number of GPUs with resharding. However, re-validate after every change to the parallelism plan.

    Choosing the save interval involves a trade-off between loss and overhead. A long interval means more steps are lost after a failure. Saving too often consumes storage bandwidth and slows training. Asynchronous saving reduces training pauses, but confirm that failures in asynchronous writes are reported correctly.

    4.2 Timeouts and Failure Detection

    In multi-GPU training, if one GPU hangs, every other GPU waits in the collective operation. You should:

    • Set a reasonable timeout in init_process_group. A timeout that is too short may flag slow nodes incorrectly, while one that is too long leaves the job hanging for an extended period.
    • Enable asynchronous error handling for collective communication. The related environment variable names change between versions, so refer to the documentation for your version.
    • Monitor the time taken by each step. When a step’s duration clearly deviates from the baseline, investigate slow nodes first instead of simply increasing the timeout.

    4.3 Diagnosing Memory Issues

    When you encounter an out-of-memory (OOM) error, troubleshoot in the following order.

    1. Determine whether the model states or the activations exceed memory. The former usually appears during initialization or the first backward pass, while the latter appears as sequence length grows.
    2. Compare max_memory_reserved with max_memory_allocated. If the gap is large, set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to reduce fragmentation, and observe the effect.
    3. Enable activation recomputation to trade compute for memory.
    4. Adjust the communication bucket size. Buckets that are too large increase communication buffer usage, while buckets that are too small reduce communication efficiency.

    4.4 Pre-Launch Checklist

    Confirm each item before launch, and keep a reproducible record for each one.

    • Memory estimates were recalculated using the actual optimizer and precision settings, and calibrated with a small-scale measurement.
    • Peak memory at the target GPU count is below single-GPU capacity, with measured headroom reserved.
    • Sharding groups match the interconnect topology and do not cross low-speed links.
    • Loss from one GPU and from multiple GPUs is aligned over the first several steps.
    • All-gather and reduce-scatter throughput meets expectations, and computation overlaps with communication.
    • Data loading throughput exceeds the rate at which training consumes data, and no samples are duplicated across processes.
    • The behavior of gradient accumulation and gradient clipping was compared against single-GPU results.
    • Checkpoints can be saved and restored, and the loss curve remains continuous after restoration.
    • In a staging environment, manually terminate one process and confirm that the job detects the failure and resumes from the most recent checkpoint. Record the number of steps lost.
    • Timeouts, alerts, and logging are configured and verified, and abnormal loss or sudden gradient norm spikes trigger timely notifications.