FSDP2 Sharding for Trillion-Parameter Multimodal Training: A Practical Guide

    This article explains how to adapt multimodal model training with PyTorch’s native FSDP2 on AI accelerator cards and their general software stacks. It covers memory-budget estimation, FSDP2 sharding mechanics, multimodal sharding granularity, distributed checkpoint loading, prefetch and compute-communication overlap, gradient synchronization, and checkpoint interval planning.

    As model scale continues to grow, parameter counts have reached the trillion level. A team recently released a 2.8-trillion-parameter open-source multimodal model, bringing ultra-large-scale training infrastructure back into focus. A single accelerator card cannot hold such a model in memory, so distributed training is mandatory. This article explains how to adapt multimodal model training with PyTorch’s native FSDP2 on domestic AI accelerator cards and their corresponding general software stacks, and gives the design rationale for each step.

    1. Start with a Clear Memory Budget

    Before training, estimate memory usage. Taking 2.8 trillion parameters as an example and using decimal units, the BF16 weights alone occupy about 5.6 TB (2.8 × 10¹² parameters × 2 bytes).

    When AdamW is used in mixed-precision training, each parameter also needs an FP32 master weight, an FP32 gradient, and Adam’s first- and second-order moments, totaling about 16 bytes. The optimizer-related state is therefore approximately:

    2.8 × 10¹² × 16 bytes ≈ 44.8 TB

    Fully sharded data parallel partitions these states evenly across all cards. The per-card state under different card counts is as follows:

    • 512 cards: about 87.5 GB
    • 1024 cards: about 43.8 GB
    • 2048 cards: about 21.9 GB

    These numbers do not include activations, communication buffers, or memory fragmentation. In actual planning, reserve headroom above these results and refine the estimate through short trial runs.

    2. Hardware and Software Foundation

    Training efficiency depends on coordination between accelerator cards and the software stack. When selecting hardware, focus on three metrics: usable memory per card, inter-card interconnect bandwidth, and framework support for collective communication.

    The value of the software stack is that upper-layer code can remain unchanged. Take general-purpose compute software stacks such as MUSA as an example. Ideally, PyTorch operators, communication, and device management interfaces can be called directly. However, vendors define device type names and collective communication backend names differently. In the code below, "cuda" and "nccl" are used only as NVIDIA examples. When migrating to another platform, replace them with the corresponding vendor names and confirm that the platform supports the FSDP2 features being used.

    3. How FSDP2 Sharding Works

    FSDP2 uses parameter-wise sharding. It shards parameters, gradients, and optimizer states by tensor across the cards in the data parallel group. During forward computation, required parameters are all-gathered on demand; after computation, nonessential parameter shards can be released immediately. During backward computation, gradients are distributed to the corresponding shards via reduce-scatter, so each card does not need to store full gradients.

    Compared with FSDP1, there are three main differences:

    1. Different interfaces. FSDP1 wraps an entire module with FullyShardedDataParallel, while FSDP2 applies sharding module by module with the fully_shard function and can configure submodules separately.
    2. Different parameter representation. FSDP1 flattens a group of parameters and manages them together. FSDP2 preserves the independent tensor form of each parameter, so configurations such as use_orig_params are no longer required.
    3. Different device mesh. FSDP2 uses DeviceMesh to describe the sharding dimension, making it easier to combine multiple parallelism methods in the same training job.

    The following code sketch uses public interfaces from PyTorch 2.6 and later. Earlier versions have different module paths and need to be adjusted according to the actual version.

    1. import os
    2. import torch
    3. import torch.distributed as dist
    4. from torch.distributed.device_mesh import init_device_mesh
    5. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    6. local_rank = int(os.environ["LOCAL_RANK"])
    7. world_size = int(os.environ["WORLD_SIZE"])
    8. torch.cuda.set_device(local_rank) # On non-NVIDIA cards, replace with the vendor's device setup API
    9. dist.init_process_group(backend="nccl") # The backend name is determined by the vendor's collective communication library
    10. mesh = init_device_mesh("cuda", (world_size,))
    11. mp_policy = MixedPrecisionPolicy(
    12. param_dtype=torch.bfloat16, # Parameter precision used in forward and backward
    13. reduce_dtype=torch.float32, # Use FP32 for gradient reduction to reduce accumulation error
    14. )
    15. # Build the model on the meta device to record shapes only, without allocating physical memory
    16. with torch.device("meta"):
    17. model = build_multimodal_model() # User-defined model builder
    18. # Shard submodules first, then the root module
    19. for block in model.vision_encoder.blocks:
    20. fully_shard(block, mesh=mesh, mp_policy=mp_policy)
    21. for layer in model.language_model.layers:
    22. fully_shard(layer, mesh=mesh, mp_policy=mp_policy, reshard_after_forward=True)
    23. fully_shard(model, mesh=mesh, mp_policy=mp_policy)
    24. # Allocate real storage for the shards, then load the weights owned by this rank
    25. model.to_empty(device="cuda")

    An example launch command is shown below. Taking 4 nodes with 8 cards per node as an example, the world size is 32:

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

    Here, --max_restarts means that torchrun will try to restart training after a process exits abnormally, provided that the training script supports checkpoint recovery.

    The reshard_after_forward parameter is a trade-off between memory and communication. When set to True, parameter shards are released immediately after forward computation and must be all-gathered again during backward computation, which saves more memory but adds communication. For language model backbones with tight memory, True is usually the choice. For small modules with sufficient memory headroom, setting it to False can reduce repeated all-gathers.

    4. Sharding Strategy for Multimodal Scenarios

    Multimodal models usually contain a vision encoder, a language model backbone, and a modality alignment module. Their parameter scales and compute characteristics differ greatly. The vision encoder has far fewer parameters than the language model, but its attention computation and input resolution affect the size of activations. If every module is sharded very finely, the number of communications increases noticeably and slows training instead.

    The choice of sharding granularity can follow these principles:

    • Vision encoder with fewer parameters: shard by Transformer block; no further subdivision is needed. If its parameters fit fully on a single card, it can also be left unsharded and only data parallelism can be used.
    • Language model backbone: shard by layer and enable reshard_after_forward to lower peak memory.
    • Modality alignment module: the parameter count is usually very small, so it can be merged with the upper-level module for sharding to avoid extra communication caused by separate all-gathers.

    If the cluster is large, HSDP (Hybrid Sharded Data Parallel) can be used. It divides DeviceMesh into replicate and shard dimensions. Sharding occurs only within the shard dimension, and replicas synchronize gradients through AllReduce. This approach confines large-scale reduce-scatter to a smaller communication domain and is suitable for scenarios with limited cross-node bandwidth.

    5. End-to-End Flow: Loading, Scheduling, Synchronization, and Fault Tolerance

    5.1 Model Loading

    Instantiating a 2.8-trillion-parameter model directly on CPU is infeasible. FP32 weights alone require more than 11 TB of host memory, far beyond normal node configurations. Therefore, the loading flow should be:

    • Build the model structure on the meta device without allocating physical storage;
    • After shard wrapping is complete, use to_empty to allocate accelerator memory for this rank’s shards;
    • Read weights through a distributed checkpoint interface such as torch.distributed.checkpoint, with each rank reading only the shard it is responsible for.

    Shard file names should include the model version, shard index, and world size to facilitate validation and rollback. If loading fails midway, clean up incomplete shards and reload from the last valid version instead of continuing training from a partial state.

    5.2 Prefetch and Compute-Communication Overlap

    FSDP2 supports explicitly setting prefetch modules, for example:

    1. for cur, nxt in zip(model.language_model.layers[:-1], model.language_model.layers[1:]):
    2. cur.set_modules_to_forward_prefetch([nxt])

    The larger the prefetch window, the higher the degree of overlap between computation and communication, but the more memory is occupied at the same time. Each additional prefetched layer requires keeping one more layer’s unsharded parameters. Therefore, the window size should be based on measurements: start from 1 layer and increase gradually until GPU utilization no longer improves or memory approaches the safety threshold.

    5.3 Gradient Synchronization and Checkpointing

    FSDP2 performs gradient synchronization as reduce-scatter per parameter group, which differs from DDP’s gradient bucketing mechanism. In FSDP2, adjusting the sharding granularity itself affects the size of communication blocks. In HSDP scenarios, AllReduce among replicas can be tuned separately.

    Checkpoint frequency can be estimated with the Young-Daly formula:

    Optimal interval ≈ √(2 × C × M)

    where C is the write time for one checkpoint and M is the mean time between failures. Assuming C is 120 seconds and M is 6 hours, the optimal interval is about 2277 seconds, or about 38 minutes. Actual values should be based on the cluster’s failure statistics and storage write speed.

    Recovery time also needs to be included in planning. Recovery time includes rescheduling, loading checkpoints, and rebuilding communication groups. Before formal training, it is advisable to inject node failures and measure the time required for the complete recovery flow, then set an acceptable recovery objective based on the results.