FSDP2 Deployment Guide for 2.8 Trillion Parameter Multimodal Models

    This guide details the deployment of a 2.8 trillion parameter multimodal model using FSDP2 in PyTorch. It covers environment prerequisites, memory estimation, meta device loading for weight allocation, distributed checkpointing for sharded weights, and techniques for overlapping communication and computation through prefetching and gradient synchronization.

    1. Scope and Prerequisites

    This example is based on PyTorch 2.6 and above, utilizing NVIDIA GPUs and NCCL. The code provides structural examples and has not been tested on a 2.8 trillion parameter scale; the numbers in the text are derived from formulas. You must re-measure with your own configuration before going live.

    Before starting, verify the following items:

    Check Item Requirement Verification Method
    PyTorch 2.6+, can import torch.distributed.fsdp.fully_shard python -c "import torch; print(torch.__version__)"
    CUDA and NCCL Matches PyTorch distribution python -c "import torch; print(torch.version.cuda, torch.cuda.nccl.version())"
    GPU Model and single GPU memory known, driver normal nvidia-smi
    Node Interconnect InfiniBand or RoCE, inter-node bandwidth tested all_reduce_perf in nccl-tests
    Storage Checkpoint directory writable, write bandwidth tested fio or dd test
    Permissions Multi-node passwordless SSH or scheduler permissions, checkpoint directory write permissions Run a test before launching

    Startup example:

    1. export NCCL_DEBUG=WARN
    2. export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
    3. export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
    4. torchrun --nnodes=$NNODES --nproc-per-node=8 \
    5. --rdzv-backend=c10d --rdzv-endpoint=$MASTER_ADDR:29500 \
    6. train.py --config configs/2p8t.yaml

    Heterogeneous accelerators require replacing the device type ("cuda"), communication backend, and device mesh. Ensure the platform’s software stack implements the all-gather, reduce-scatter, and BF16 basic operators used by FSDP2. If any are missing, stop and resolve them first; do not discover this mid-training.

    2. Memory Estimation: Calculate Before Acting

    Taking a common mixed precision configuration as an example, the memory footprint for model states per parameter is as follows:

    Item Bytes per parameter
    BF16 weights 2
    BF16 gradients 2
    FP32 master weights 4
    Adam first and second order states 8
    Total 16

    This 16-byte value is an assumption. If the optimizer’s master weights or states use different precisions, recalculate. Units are in decimal, where 1 GB is 10^9 bytes.

    2.8 trillion parameters multiplied by 16 bytes is approximately 44.8 TB. FSDP2 evenly shards model states across each GPU in the shard group. The formula is:

    Per-GPU model state = Total state ÷ Shard group size

    Calculated for an 80GB GPU, the results are as follows:

    GPU Count Per-GPU Model State Remaining Space on 80GB GPU Conclusion
    512 87.5 GB Insufficient, model state exceeds GPU capacity Cannot fit
    560 80 GB 0 Theoretical lower limit, practically unusable
    1024 43.75 GB Approx. 36.25 GB Needs to deduct other overheads listed below
    2048 21.875 GB Approx. 58.125 GB Large margin, suitable for activations and communication

    Model states are only part of the equation; space must also be reserved for the following overheads:

    • Single chunk all-gather temporary buffer: Before computing a chunk, FSDP2 gathers the full BF16 weights for that chunk to the local GPU. Assuming a chunk has 5 billion parameters, the temporary buffer is about 10 GB. With forward prefetch enabled, adjacent chunks may exist simultaneously, taking about 20 GB.
    • Activations: Depends on sequence length, micro-batch size, and whether activation recomputation is enabled.
    • Communication buffers: The size of NCCL internal buffers depends on configuration and requires empirical testing.
    • Memory fragmentation: Memory retained but unused by the PyTorch caching allocator.
    • CUDA context and driver overhead.

    Taking 1024 GPUs as an example: per-GPU model state is 43.75 GB, minus about 20 GB for temporary buffers, leaving only about 16 GB for activations and other overheads. This margin is very tight; 1024 GPUs does not guarantee it will run. With 2048 GPUs, per-GPU model state is 21.875 GB, minus the same temporary buffer, leaving about 38 GB for activations, which is more reliable.

    The number of GPUs also relates to the parallelism strategy. If tensor parallelism (TP) or pipeline parallelism (PP) is used simultaneously, the parameter volume per GPU must be further divided by the respective parallelism degree. If using HSDP (shard group smaller than total GPUs), calculate per-GPU state based on the shard group size, not the total GPU count. Please verify based on your actual sharding strategy instead of directly applying the table above.

    3. Meta Device Loading: Avoid Allocating the Full Model on Every GPU

    Build the model on the meta device, which occupies no GPU memory. Allocate space to individual GPUs after sharding.

    1. import os
    2. import torch
    3. from torch.distributed.device_mesh import init_device_mesh
    4. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    5. world_size = int(os.environ["WORLD_SIZE"])
    6. local_rank = int(os.environ["LOCAL_RANK"])
    7. torch.cuda.set_device(local_rank)
    8. mesh = init_device_mesh("cuda", (world_size,))
    9. with torch.device("meta"):
    10. model = build_model(config) # build_model is the user's custom model building function
    11. mp_policy = MixedPrecisionPolicy(
    12. param_dtype=torch.bfloat16,
    13. reduce_dtype=torch.float32,
    14. )
    15. for block in model.blocks:
    16. fully_shard(block, mesh=mesh, mp_policy=mp_policy)
    17. fully_shard(model, mesh=mesh, mp_policy=mp_policy)
    18. model.to_empty(device="cuda")
    19. torch.manual_seed(config.seed)
    20. model.init_weights() # Or change to restore from checkpoint, see the next section

    Note the following points:

    • to_empty only allocates memory and does not initialize values. After calling it, parameter contents are random undefined values and must be populated via init_weights or checkpoint loading.
    • Non-parameter buffers (e.g., Rotary Position Embedding caches) are also created on meta. After to_empty, their contents are undefined and must be recalculated in the initialization function.
    • All ranks use the same random seed, but sharded parameters will only initialize the portion each rank holds. Verify initialization results on a single-GPU small model to ensure that the concatenated shards from all ranks match expectations.
    • The optimizer must be created after fully_shard, otherwise it will reference unsharded parameters.

    4. Sharded Weight I/O: Use Distributed Checkpoints, Do Not Gather to One GPU

    Both saving and restoring use torch.distributed.checkpoint, where each rank only reads and writes its own shards.

    Save:

    1. from torch.distributed.checkpoint.state_dict import (
    2. get_model_state_dict,
    3. get_optimizer_state_dict,
    4. StateDictOptions,
    5. )
    6. import torch.distributed.checkpoint as dcp
    7. opts = StateDictOptions(full_state_dict=False)
    8. state = {
    9. "model": get_model_state_dict(model, options=opts),
    10. "optim": get_optimizer_state_dict(model, optimizer, options=opts),
    11. }
    12. dcp.save(state, checkpoint_id=ckpt_path)

    Restore:

    1. from torch.distributed.checkpoint.state_dict import (
    2. get_model_state_dict,
    3. get_optimizer_state_dict,
    4. set_model_state_dict,
    5. set_optimizer_state_dict,
    6. StateDictOptions,
    7. )
    8. import torch.distributed.checkpoint as dcp
    9. opts = StateDictOptions(full_state_dict=False)
    10. state = {
    11. "model": get_model_state_dict(model, options=opts),
    12. "optim": get_optimizer_state_dict(model, optimizer, options=opts),
    13. }
    14. dcp.load(state, checkpoint_id=ckpt_path)
    15. set_model_state_dict(model, state["model"], options=opts)
    16. set_optimizer_state_dict(model, optimizer, state["optim"], options=opts)

    Do not use full_state_dict=True. It gathers the entire model to rank 0, which far exceeds single-machine memory for a 2.8 trillion parameter model.

    Checkpoint size and write time can be estimated. Assuming FP32 weights (4 bytes) and Adam optimizer states (8 bytes), that’s 12 bytes per parameter, totaling about 33.6 TB. If the aggregate write bandwidth is 10 GB/s, a single save takes about 56 minutes. This time directly impacts checkpoint frequency, so replace the assumed bandwidth with your storage’s measured bandwidth.

    5. Prefetching and Gradient Synchronization: Overlapping Communication and Computation

    Prefetching allows the next chunk’s parameters to be gathered in advance while the current chunk is being computed. The following code sets the prefetch order for forward and backward passes:

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

    Backpropagation executes from back to front, so later chunks are responsible for prefetching earlier chunks.

    reshard_after_forward controls whether the full parameters are released immediately after the forward pass. Enabling it saves memory but requires re-gathering during the backward pass, increasing communication volume. For a 2.8 trillion parameter model, it is usually enabled for all chunks and only disabled for the last chunk.

    Gradient accumulation requires special care. During set_requires_gradient_sync(False), gradients accumulate locally in an unsharded form, with memory usage approaching the full gradient of that portion of parameters. At this scale, this memory footprint may exceed estimates. Before using gradient accumulation, recalculate the memory usage of the non-synchronized phases using the formulas in section 2. If it doesn’t fit, a safer approach is to synchronize every micro-batch or increase the number of shards.

    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()
    6. optimizer.step()
    7. optimizer.zero_grad(set_to_none=True)

    Before going live, check the following:

    • The prefetch list only contains adjacent chunks, with no omissions or duplicates.
    • The memory peak during gradient accumulation has been confirmed through empirical testing.
    • The function used for gradient clipping supports DTensor and has been validated on a small model to ensure results match single-GPU execution.

    6. Quantized Communication A/B Testing: Measure Before Adopting

    FSDP2 controls communication precision via param_dtype and reduce_dtype. The A/B testing in this article focuses on the gradient redu