FSDP2 Training Guide for Trillion-Parameter Models

    A practical guide to adapting trillion-parameter model training with PyTorch FSDP2. It covers memory estimation, hardware and software requirements, FSDP1 versus FSDP2, meta-device initialization, checkpoint loading, activation recomputation, communication overlap, OOM troubleshooting, cloud infrastructure, fault tolerance, and an implementation checklist.

    Training a trillion-parameter model starts with a realistic memory budget. Consider a 2.8-trillion-parameter model. Storing its weights in BF16 alone requires approximately 5.6 TB. Training also requires gradients and optimizer states. Using a common mixed-precision estimate, each parameter needs roughly 16 bytes, including FP32 master weights, gradients, and the two AdamW momentum states. The total is therefore about 44.8 TB of device memory.

    This is far beyond the capacity of any single accelerator, so parameters, gradients, and optimizer states must be sharded across multiple devices.

    This estimate is only a lower bound. Actual training also requires memory for activations, communication buffers, and allocator fragmentation. Multimodal inputs often have different sequence lengths, causing activation peaks to fluctuate. Before production deployment, measure peak memory with representative data at a smaller scale.

    1. Hardware and Software Requirements

    Cluster performance depends on three categories of conditions.

    Per-device resources

    Accelerator memory capacity and memory bandwidth determine how much of the model each device can hold and whether forward computation can keep the accelerator fully utilized.

    Interconnects

    Within a node, training typically relies on NVLink or a similar high-speed interconnect. Across nodes, it usually relies on InfiniBand or RoCE. FSDP parameter gathering and gradient reduction both require cross-device communication. If network bandwidth is insufficient, GPUs will spend significant time waiting.

    Software compatibility

    Vendor-provided operator libraries and collective communication libraries must be compatible with the PyTorch version. Before selecting a stack, verify support for the DTensor mechanisms required by FSDP2 and the relevant NCCL-style collective communication interfaces.

    2. FSDP1 vs. FSDP2

    FSDP1 wraps the entire model with the FullyShardedDataParallel class. Internally, it manages parameters as large flattened tensors. After wrapping, parameter names and structures change, which can make debugging more difficult.

    FSDP2 uses the fully_shard function to shard modules layer by layer. Parameters are stored as DTensors while retaining their original shapes and names, making debugging and checkpoint management easier.

    FSDP2 also provides the reshard_after_forward option, which controls whether full parameters are released after forward computation. Mixed precision is configured with MixedPrecisionPolicy.

    PyTorch 2.6 or later is recommended. Import paths may differ between versions, so check the version documentation first when an import error occurs.

    3. Minimal Example

    The following example demonstrates the basic FSDP2 workflow. The MultimodalLargeModel class must be implemented separately; the important part is the ordering of sharding and initialization.

    1. import os
    2. import torch
    3. import torch.distributed as dist
    4. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    5. def main():
    6. # 1. Initialize the process group; each process is bound to one device
    7. dist.init_process_group(backend="nccl")
    8. local_rank = int(os.environ["LOCAL_RANK"])
    9. torch.cuda.set_device(local_rank)
    10. # 2. Build the model structure on the meta device without allocating real memory
    11. with torch.device("meta"):
    12. model = MultimodalLargeModel() # User-defined
    13. # 3. Use BF16 for forward and backward computation, and FP32 for gradient reduction
    14. mp_policy = MixedPrecisionPolicy(
    15. param_dtype=torch.bfloat16,
    16. reduce_dtype=torch.float32,
    17. )
    18. # 4. Shard child modules first, then shard the root module
    19. for block in model.blocks:
    20. fully_shard(block, mp_policy=mp_policy, reshard_after_forward=True)
    21. fully_shard(model, mp_policy=mp_policy)
    22. # 5. Materialize meta tensors on the current device, then load the weights
    23. model.to_empty(device="cuda")
    24. model.init_weights() # User-defined initialization or checkpoint loading
    25. # 6. Create the optimizer after sharding so its state matches parameter shards
    26. optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
    27. for batch in dataloader: # Constructed by the user
    28. loss = model(**batch).loss
    29. loss.backward()
    30. optimizer.step()
    31. optimizer.zero_grad(set_to_none=True)
    32. dist.destroy_process_group()
    33. if __name__ == "__main__":
    34. main()

    An example launch command is:

    1. torchrun --nproc_per_node=8 --nnodes=4 --node_rank=$NODE_RANK \
    2. --master_addr=$MASTER_ADDR --master_port=29500 train.py

    The example highlights three important rules:

    1. Apply fully_shard to child modules before the root module. Otherwise, large parameter groups may be gathered as a whole, significantly increasing peak memory.
    2. Create the optimizer after sharding. If it is created earlier, it may retain references to unsharded parameters.
    3. Real memory allocation occurs after to_empty, not when the model structure is created on the meta device.

    4. Loading a Model: From the Meta Device to Real Weights

    The meta device records tensor shapes and data types without allocating device memory. A correct loading sequence is:

    1. Build the model on the meta device.
    2. Call fully_shard on the relevant modules to establish the sharding plan.
    3. Call to_empty to allocate each device’s assigned shards. This allocates memory only; the contents are uninitialized.
    4. Load weights from a checkpoint. The torch.distributed.checkpoint state-dict APIs, such as set_model_state_dict, are recommended. Each process should read only the data assigned to it.
    5. If training from scratch, call the model’s initialization function.

    A common mistake is to call to_empty without initializing the weights. The first training step may then produce random or invalid values.

    Another easily overlooked issue is non-persistent buffers, such as cached rotary positional-encoding tables. These buffers are not saved in checkpoints and must be recomputed after to_empty.

    5. Sharding Policy and Activation Recomputation

    During the forward pass, each layer gathers its full parameters. When reshard_after_forward=True, the layer releases those parameters immediately after computation, reducing peak memory.

    The trade-off is additional communication during backward propagation because the parameters must be gathered again. If memory capacity is sufficient, the option can be set to False for the final few layers to avoid one additional gather.

    Activations are often another major source of memory usage. Applying torch.utils.checkpoint to selected modules enables activation recomputation, exchanging additional computation for lower memory consumption.

    In multimodal models, the image encoder and text decoder can have very different activation shapes. Decide whether to recompute activations separately for each module instead of applying one setting uniformly across the model.

    6. Gradient Synchronization and Communication Overlap

    In FULL_SHARD mode, FSDP2 follows this communication pattern:

    • Before forward and backward computation, each layer uses all-gather to collect its full parameters.
    • After backward computation, each layer uses reduce-scatter to reduce gradients.
    • Each device retains only its assigned gradient shard.

    This differs from standard data parallelism with all-reduce. All-reduce leaves a complete copy of the gradients on every device, resulting in higher memory usage.

    For cross-node replication groups, HSDP can be used to shard within each node and replicate across nodes. In that configuration, all-reduce occurs between nodes.

    Overlapping communication with computation depends on two conditions:

    1. NCCL uses a separate communication stream that can execute in parallel with the computation stream.
    2. Prefetching starts gathering the next layer’s parameters in advance.

    If overlap is ineffective, use torch.profiler to inspect the timeline and check for gaps in the computation stream. You can also set NCCL_DEBUG=INFO to verify that communication is using the expected network path.

    7. A Practical OOM Troubleshooting Order

    When an out-of-memory error occurs, troubleshoot in the following order instead of immediately changing the learning rate or model architecture:

    1. Compare actual usage with the estimate from Section 1 and verify that static memory is within expectations.
    2. Use torch.cuda.max_memory_allocated() to record the peak on every device and determine whether it occurs during forward propagation, backward propagation, or the optimizer step.
    3. Reduce the per-device batch size or use gradient accumulation to preserve the effective batch size.
    4. Enable activation recomputation for memory-intensive modules.
    5. Set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to reduce apparent OOM errors caused by fragmentation.
    6. Check the maximum sequence length and image resolution of multimodal inputs. Long-tail samples are often the real cause of OOM errors, so impose limits at the data layer.

    8. Cloud Infrastructure and Fault Tolerance

    Training stability at large scale depends heavily on the underlying infrastructure.

    Container orchestration

    Use Kubernetes or a similar scheduler to manage heterogeneous compute resources and automatically reschedule workloads after node failures. The rescheduled processes must be able to access the same checkpoints.

    Data pipeline

    Object storage is suitable for reliable storage of raw data. During training, use a distributed cache to prefetch data to local NVMe SSDs and reduce latency caused by many small files. Image and video preprocessing should be performed asynchronously in the data-loading pipeline whenever possible.

    Checkpointing

    Checkpoint frequency requires a balance between storage overhead and the amount of work lost after a failure.

    A commonly used estimate based on Young’s formula is:

    [
    \text{optimal interval} \approx \sqrt{2 \times \text{checkpoint time} \times \text{mean time between failures}}
    ]

    If saving a checkpoint takes 5 minutes and the cluster’s mean time between failures is 12 hours, or 720 minutes, the estimated interval is:

    [
    \sqrt{2 \times 5 \times 720} \approx 85 \text{ minutes}
    ]

    The actual interval should also account for storage bandwidth and the importance of the training job.

    Monitoring

    Continuously monitor accelerator temperature, memory usage, network throughput, and step-time variation on every device. A sudden increase in step time often indicates a problem with a specific device or network link and should be investigated promptly.

    9. Deployment Checklist

    • Memory estimation: Static memory, activations, and communication buffers are included, with sufficient headroom.
    • Version compatibility: PyTorch, NCCL, and vendor operator libraries are compatible and have been validated on a small cluster.
    • Sharding order: Child modules are sharded before the root module, and the optimizer is created after sharding.
    • Initialization: Meta tensors have been materialized, weights have been loaded from a checkpoint or initialized, and non-persistent buffers have been recomputed.
    • Communication: Profiling confirms the effectiveness of computation and communication overlap.
    • Fault tolerance: The checkpoint interval has been estimated based on failure rates, and the recovery process has been tested end to end.
    • Data pipeline: Long-sequence samples have defined limits, and data prefetching is not a bottleneck.

    Conclusion

    Adapting training for trillion-parameter models involves hardware, communication libraries, distributed frameworks, and cloud infrastructure. FSDP2 provides layer-wise sharding, DTensor-based parameter storage, and flexible controls for recomputation and communication, making large-scale training easier to understand and debug.

    Actual throughput, utilization, and stability depend on the specific cluster and model configuration. Production decisions should therefore be based on measurements from the target environment.