FSDP2 for Multimodal Model Training: Loading, Sharding, and Gradient Sync

    This article explores how FSDP2 (Fully Sharded Data Parallel v2) addresses the memory challenges of training massive multimodal models, using a 2.8-trillion-parameter model as a reference example. It breaks down the memory footprint of model states, explains FSDP2's per-parameter DTensor-based sharding mechanism compared to FSDP1's FlatParameter approach, details how computation and communication overlap with all-gather and reduce-scatter operations, and provides a practical code example for sharding, loading, and saving distributed checkpoints.

    Training models at the scale of trillions of parameters puts immense pressure on GPU memory. Using a 2.8-trillion (2.8T) parameter model as an example, we can estimate the memory required for model states alone. With weights stored in BF16 format, memory usage is approximately 2.8 × 10¹² × 2 bytes, or 5.6 TB. Gradients saved in BF16 also require another 5.6 TB. If the Adam optimizer is used with FP32-precision first-order momentum (m) and second-order momentum (v), those two states together add roughly 22.4 TB. Storing FP32 master weights would further require 11.2 TB. In total, model states consume about 33.6 TB without master weights, and approximately 44.8 TB with them.

    These figures cover only model states. Activation values, communication buffers, and memory fragmentation make real-world requirements even higher. A single server’s GPUs fall far short of this scale, so model states must be sharded across many accelerators, with each device holding only a portion of the data.

    How FSDP2 Shards Parameters

    FSDP2 (Fully Sharded Data Parallel v2) is built on DTensor (Distributed Tensor). It shards each parameter individually, with every GPU storing only a slice of that parameter along a specific dimension. The global shape and sharding layout of each parameter are tracked by DTensor.

    FSDP1 takes a different approach. To improve communication efficiency, FSDP1 concatenates multiple parameters within a module into a single flattened FlatParameter before sharding. This blurs boundaries between parameters and complicates state lookup and restoration by parameter name. FSDP2 avoids this concatenation, so the mapping between parameters and their shards is more direct.

    Finer sharding units mean smaller regions must be aggregated into full parameters at any given time, reducing peak memory usage. In practice, fully_shard is typically applied to each Transformer layer individually, followed by one outer call on the whole model, forming a nested sharding structure.

    Overlapping Computation and Communication

    A single training step roughly follows this flow. When computing the forward pass for layer i, FSDP2 asynchronously pulls the full parameters needed for layer i+1 via all-gather, allowing communication to overlap with computation. After computation completes, the system releases the full parameters that are no longer needed, keeping only the local shards.

    During backpropagation, parameters must be aggregated again. Once gradients are computed, FSDP2 uses reduce-scatter to sum and shard the gradients, with each GPU retaining only the gradient portion it is responsible for. This differs from the common all-reduce approach, as it does not require every GPU to hold the full gradient, resulting in lower memory usage.

    Prefetching can be enabled through the framework’s forward and backward prefetch settings. More prefetching layers make it easier to hide communication behind computation, but they also increase the number of full parameters resident in memory at once, raising memory usage. The prefetch depth requires a trade-off between memory and communication latency, ideally determined through benchmarking.

    Code Example for the Training Pipeline

    The following code illustrates how to use FSDP2. It must be validated in your target environment. The fully_shard interface requires a relatively recent PyTorch version—2.6 or later is recommended—with matching PyTorch, CUDA, and NCCL versions.

    1. import torch
    2. import torch.distributed as dist
    3. import torch.distributed.checkpoint as dcp
    4. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    5. from torch.distributed.checkpoint.state_dict import (
    6. get_model_state_dict,
    7. set_model_state_dict,
    8. )
    9. def build_sharded_model(model, layers):
    10. mp_policy = MixedPrecisionPolicy(
    11. param_dtype=torch.bfloat16, # Parameter precision for forward and backward
    12. reduce_dtype=torch.float32, # FP32 gradient reduction to reduce accumulation error
    13. )
    14. # Shard inner layers first, then the outermost model
    15. for layer in layers:
    16. fully_shard(layer, mp_policy=mp_policy)
    17. fully_shard(model, mp_policy=mp_policy)
    18. return model
    19. def load_distributed_checkpoint(model, ckpt_dir):
    20. # Each rank loads only the shards it owns; layout is determined by checkpoint metadata
    21. model_sd = get_model_state_dict(model)
    22. dcp.load({"model": model_sd}, checkpoint_id=ckpt_dir)
    23. set_model_state_dict(model, model_sd)
    24. dist.barrier()
    25. return model
    26. def save_distributed_checkpoint(model, ckpt_dir):
    27. # Saving is a collective operation; all ranks must participate
    28. dcp.save({"model": get_model_state_dict(model)}, checkpoint_id=ckpt_dir)

    Distributed checkpointing (DCP) saves and restores state based on parameter names and sharding layouts.