FSDP2 in Practice: Building a Trillion-Scale Multimodal Model Training Pipeline

    This article is a hands-on guide to training trillion-scale multimodal models with FSDP2 (PyTorch 2.6+). It covers GPU memory estimation, FSDP2 initialization with fully_shard and MixedPrecisionPolicy, key differences between FSDP1 and FSDP2 with a migration checklist, meta-device model loading with distributed checkpoints, compute-communication overlap via prefetching and gradient accumulation, checkpoint saving and recovery, and a troubleshooting checklist for OOM, communication bottlenecks, and training hangs.

    FSDP2 in Practice: Building a Trillion-Scale Multimodal Model Training Pipeline

    Scope and Environment Versions

    This article is based on PyTorch 2.6 and later. In this version, fully_shard and MixedPrecisionPolicy live under torch.distributed.fsdp. In PyTorch 2.4 and 2.5, the API is located in torch.distributed._composable.fsdp, and parameters and behavior may differ. Before migrating, check the official documentation for your specific version.

    Component Recommended requirement Check command
    Python Within the officially supported range of your PyTorch version python --version
    PyTorch 2.6 or later python -c "import torch; print(torch.__version__)"
    CUDA Match the version the PyTorch wheel was compiled with python -c "import torch; print(torch.version.cuda)"
    NCCL Prefer the version bundled with PyTorch python -c "import torch; print(torch.cuda.nccl.version())"
    GPU driver Meet the minimum requirement of the selected CUDA version nvidia-smi
    Network InfiniBand or RoCE between nodes ibstat or ibv_devinfo

    Versions must be identical across all nodes. Mismatched versions can cause collective communication to hang or produce numerical differences that are hard to reproduce.

    1. Memory Estimation

    Let P be the number of model parameters and b the bytes per parameter. Storing weights alone costs P × b. For a 2.8-trillion-parameter model, FP32 weights take about 11.2 TB and BF16 weights about 5.6 TB. This article uses decimal units, i.e., 1 TB = 10^12 bytes.

    Training state with BF16 mixed precision plus AdamW totals 16 bytes per parameter:

    Item Bytes per parameter Total for 2.8T parameters
    Weights (BF16) 2 5.6 TB
    Gradients (BF16) 2 5.6 TB
    Master weights (FP32) 4 11.2 TB
    Momentum (FP32) 4 11.2 TB
    Variance (FP32) 4 11.2 TB
    Total 16 44.8 TB

    The table above does not include: activations, communication buffers, temporary full-parameter copies created by all-gather, CUDA context, or memory fragmentation. Therefore 44.8 TB is a lower bound for training state, not the total memory requirement.

    FSDP shards the training state evenly across GPUs. With 512 GPUs, ideal sharding puts about 87.5 GB of training state per GPU. Actual sharding varies with parameter-group sizes, so rely on runtime statistics.

    Activations depend on batch size, sequence length, layer count, and hidden dimension. Without recomputation, activations grow with these quantities. Enabling activation checkpointing trades extra forward computation for memory; the savings depend on model architecture and must be measured empirically.

    Estimation checklist:

    • Run 10 training steps with a small batch on a single GPU and record torch.cuda.max_memory_allocated() and torch.cuda.max_memory_reserved().
    • In multi-GPU runs, compare the theoretical per-GPU sharded state against measured allocations. A large gap suggests unsharded large modules.
    • Peak memory consists of three parts: sharded state, activations, and all-gather temporary buffers. All three must be counted.

    2. FSDP2 Initialization

    The code below assumes the model’s Transformer blocks live in model.blocks. For multimodal models, the vision encoder, language model backbone, and modality-alignment module should each be sharded per block; do not merge all three into a single sharding unit.

    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. def apply_fsdp2(model):
    7. dist.init_process_group(backend="nccl")
    8. local_rank = int(os.environ["LOCAL_RANK"])
    9. torch.cuda.set_device(local_rank)
    10. mesh = init_device_mesh("cuda", (dist.get_world_size(),))
    11. mp_policy = MixedPrecisionPolicy(
    12. param_dtype=torch.bfloat16,
    13. reduce_dtype=torch.float32,
    14. )
    15. # Shard child modules first, then the root module
    16. for block in model.blocks:
    17. fully_shard(block, mesh=mesh, mp_policy=mp_policy, reshard_after_forward=True)
    18. fully_shard(model, mesh=mesh, mp_policy=mp_policy)
    19. return model

    Notes:

    • param_dtype determines the dtype of full-parameter copies during forward and backward. Sharded parameters keep the dtype used when the model was created.
    • If the model is created in FP32, sharded master weights, sharded gradients, and optimizer states are all FP32, totaling 16 bytes per parameter. This matches the byte count in the earlier BF16 calculation, but the allocation differs — BF16 is only used for full copies.
    • When inter-node communication is slow, you can use a 2D device mesh for hybrid sharding (HSDP). For example, init_device_mesh("cuda", (replicate_size, shard_size), mesh_dim_names=("replicate", "shard")) confines sharding groups within a node while replica groups synchronize gradients across nodes. The tradeoff is a larger sharded footprint per GPU, so memory must be re-estimated.

    3. Key Differences Between FSDP1 and FSDP2

    Dimension FSDP1 FSDP2
    Entry point FullyShardedDataParallel wrapper class; returns a new wrapper object fully_shard function; modifies the module in place and returns the same object
    Sharding representation Manages a module’s parameters via FlatParameter DTensor-based; represents sharding state per parameter
    Mixed precision MixedPrecision MixedPrecisionPolicy, including param_dtype, reduce_dtype, output_dtype
    Resharding after forward Determined by configs such as sharding_strategy Controlled by reshard_after_forward, which decides whether parameters are resharded after forward
    Sharding granularity Commonly uses auto_wrap_policy for automatic nested wrapping Manually call fully_shard on each module that needs separate sharding, from inner to outer
    State dict Managed via the state_dict_type context Uses functions in torch.distributed.checkpoint.state_dict

    Migration checklist:

    • Remove all code that depends on the wrapper object’s return value; use the original module directly.
    • Replace auto_wrap_policy with an explicit sharding loop, and confirm every block is sharded individually.
    • Replace MixedPrecision with MixedPrecisionPolicy, and verify the dtype used for gradient reduction.
    • Check for any direct access to FlatParameter; such code must be rewritten.
    • Do not assume FSDP1 checkpoints can be read directly by FSDP2 APIs; validate on a small-scale model first.

    4. Model Loading

    Very large models should not be fully constructed on CPU first. The recommended flow is: build the model on the meta device, shard it, allocate real storage on the local GPU, then load weights.

    1. import torch.distributed.checkpoint as dcp
    2. from torch.distributed.checkpoint.state_dict import (
    3. get_model_state_dict,
    4. set_model_state_dict,
    5. )
    6. with torch.device("meta"):
    7. model = build_model(cfg) # Records structure only; uses no GPU memory
    8. model = apply_fsdp2(model) # Shard the meta parameters
    9. model.to_empty(device="cuda") # Allocate storage on the local GPU; contents uninitialized
    10. model_sd = get_model_state_dict(model)
    11. dcp.load({"model": model_sd}, checkpoint_id=ckpt_dir)
    12. set_model_state_dict(model, model_sd)

    Notes:

    • After to_empty, non-persistent buffers (for example, cached rotary position embeddings) are uninitialized and must be recomputed manually after loading.
    • When training from scratch, call the model’s own parameter initialization function after to_empty.
    • If the original weights are a single monolithic file, convert them to distributed checkpoint format first, so that no process has to read the entire file.
    • After loading, compare outputs from single-GPU and distributed runs on a fixed input to confirm the weight mapping is correct.

    5. Overlapping Compute and Communication

    FSDP2 prefetches the next block’s parameters during forward and the previous block’s parameters during backward, so all-gather runs in parallel with computation. Prefetching is only effective when the sharding granularity is fine enough. If the whole model is a single sharding unit, there is nothing to prefetch.

    1. blocks = list(model.blocks)
    2. for cur, nxt in zip(blocks[:-1], blocks[1:]):
    3. cur.set_modules_to_forward_prefetch([nxt])
    4. for cur, prev in zip(blocks[1:], blocks[:-1]):
    5. cur.set_modules_to_backward_prefetch([prev])

    With gradient accumulation, synchronize gradients only on the last micro-batch and disable synchronization for the rest, reducing the number of reduce-scatter operations:

    1. for i, batch in enumerate(micro_batches):
    2. is_last = (i == len(micro_batches) - 1)
    3. model.set_requires_gradient_sync(is_last)
    4. loss = model(batch).loss / len(micro_batches)
    5. loss.backward()

    To determine whether overlap is effective, capture a training timeline with torch.profiler and check whether NCCL-related kernels overlap in time with compute kernels. Decision rule: if the difference in per-step latency with prefetching on versus off is smaller than the run-to-run variance over consecutive steps, treat it as no benefit and do not keep the configuration.

    6. Checkpointing and Recovery

    When saving, write both model and optimizer states, and write to a temporary directory first, renaming it only after completion, so an interruption does not leave a half-written checkpoint.

    1. from torch.distributed.checkpoint.state_dict import get_optimizer_state_dict
    2. def save_ckpt(model, optim, step, root):
    3. tmp_dir = f"{root}/step_{step}.tmp"
    4. final_dir = f"{root}/step_{step}"
    5. state = {
    6. "model": get_model_state_dict(model),
    7. "optim": get_optimizer_state_dict(model, optim),
    8. }
    9. dcp.save(state, checkpoint_id=tmp_dir)
    10. dist.barrier()
    11. if dist.get_rank() == 0:
    12. os.rename(tmp_dir, final_dir)
    13. dist.barrier()

    Checks before recovery:

    • Completeness: confirm the checkpoint directory contains a completion marker, and verify the file count or checksums. Skip incomplete checkpoints directly.
    • Version consistency: verify the PyTorch version, sharding strategy, mixed precision configuration, and parameter names. If any item differs, first confirm loadability in a test environment.
    • GPU-count changes: DCP supports resharding across different GPU counts when loading, but you should still run one small-scale recovery validation at the target GPU count.
    • Data progress: restore the data loader’s sampling position to avoid duplicated or skipped samples.

    Risk note: never overwrite the most recent checkpoint. Keep the last N checkpoints, and only delete older versions after a new checkpoint has been written and verified.

    7. Troubleshooting Checklist

    Out of Memory (OOM)

    1. Determine whether the error occurs in forward, backward, or the optimizer step.
    2. Compare max_memory_allocated with max_memory_reserved. A large gap indicates memory fragmentation; retry with PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True.
    3. Check whether the model was ever fully constructed on CPU, and confirm the meta-initialization flow in Section 4 is in effect.
    4. Check whether large modules (such as the embedding and output layers) are sharded individually. Unsharded large modules monopolize memory.
    5. Check whether reshard_after_forward is set to False. With False, full parameters are retained after forward, increasing memory usage.
    6. Enable activation checkpointing per block, or reduce micro-batch size and sequence length.

    Communication Bottlenecks

    1. Confirm the device mesh layout matches the physical topology. Intra-node communication should use NVLink; cross-node communication should use InfiniBand or RoCE.
    2. Set NCCL_DEBUG=INFO and inspect the logs to confirm the transport layer uses IB or RoCE rather than Socket.
    3. Measure baseline cluster bandwidth with all_gather_perf and reduce_scatter_perf from nccl-tests, then compare against measured communication time during training.
    4. Compare results with the prefetch configurations from Section 5 enabled and disabled.
    5. If sharding granularity is too fine, the number of small messages grows and communication efficiency drops. You can merge adjacent small modules, but this raises peak memory and must be re-validated.

    Training Hangs or Timeouts

    1. Check that all processes execute the same collective communication operations. Rank-conditional collective calls are the most common cause of hangs.
    2. Check that software versions are identical across nodes.
    3. When a hang occurs, capture the call stacks of all ranks and compare which collective operation they are stuck on.