A Practical Guide to Training Trillion-Parameter Multimodal Models with FSDP2

    This guide explores the practical steps for training trillion-parameter multimodal models using PyTorch's FSDP2. It covers estimating static VRAM requirements, understanding the differences between FSDP1 and FSDP2, the four key stages of the training pipeline, environment setup, and provides a complete, minimal training code example to help you get started efficiently.

    1. Estimating Static VRAM

    Using a 2.8 trillion parameter model as an example, the bytes occupied per parameter dictate the total VRAM requirement. The table below estimates static VRAM based on FSDP2’s default data layout, excluding activations.

    Item Bytes per Parameter Total for 2.8T Params
    FP32 Sharded Params (Master Weights) 4 11.2 TB
    FP32 Gradients 4 11.2 TB
    Adam 1st-order Momentum & 2nd-order Variance (FP32) 8 22.4 TB
    Total (excluding activations) 16 44.8 TB

    FSDP2’s MixedPrecisionPolicy dictates the precision used during computation and communication. Sharded parameters are stored in FP32 by default, temporarily all-gathering BF16 copies only during the forward and backward passes. Therefore, the static total is 16 bytes per parameter, identical to a layout of “BF16 weights + BF16 gradients + FP32 master weights and optimizer states,” but partitioned differently.

    After fully sharding these states, the lower bound for the number of GPUs can be calculated as:

    GPU Count ≥ Total Static VRAM ÷ Usable VRAM per GPU

    Assuming a nominal 80GB per GPU (80×10^9 bytes), dividing 44.8TB by 80GB yields 560 GPUs. This number holds true only if states are perfectly evenly sharded, ignoring activations, all-gather temporary buffers, VRAM fragmentation, and communication buffers. Actual usable VRAM is only a fraction of the nominal value, and activations also consume VRAM on each GPU. If the actual allocatable VRAM per GPU is about 70GB and 10GB must be reserved for activations and temporary buffers, the lower bound becomes 44.8×10^12 ÷ 60×10^9 ≈ 747 GPUs. These are theoretical lower bounds; the actual GPU count should be extrapolated from peak VRAM usage measured in small-scale tests.

    2. FSDP2 vs. FSDP1: Differences and Version Boundaries

    FSDP2 is PyTorch’s second-generation fully sharded data parallel implementation, accessed via the fully_shard entry point. The main differences between the two generations are as follows:

    Dimension FSDP1 (FullyShardedDataParallel) FSDP2 (fully_shard)
    Wrapping Method Nested wrapper classes, altering module structure In-place sharding, module structure remains unchanged
    Parameter Representation Multiple params concatenated into FlatParameter Each param independently represented as DTensor, sharded along dim 0
    Mixed Precision Config MixedPrecision MixedPrecisionPolicy
    Checkpoint Saving Requires a dedicated state dict interface Integrates more directly with torch.distributed.checkpoint (DCP)

    Version requirements are as follows: In PyTorch 2.6 and above, fully_shard and MixedPrecisionPolicy are located in torch.distributed.fsdp, which is the path used in this article’s code. In PyTorch 2.4 to 2.5, the same interfaces are located in the private path torch.distributed._composable.fsdp, which is subject to change and not recommended for production training. When using DCP’s get_model_state_dict and set_model_state_dict, version 2.6 or higher is recommended.

    FSDP2 is a general-purpose parameter sharding and scheduling capability, not a multimodal-specific feature. Multimodal models typically contain vision encoders, text encoders, and fusion layers, whose computational load and VRAM footprint vary significantly. When using FSDP2, you can call fully_shard on individual sub-network blocks and select different wrapping granularities.

    3. Four Stages of the Training Pipeline

    1. Model Loading. Construct the model on the meta device, which only records tensor shapes and types without allocating physical VRAM. Once sharding is complete, materialize the model on the GPU using to_empty. to_empty only allocates memory without filling valid values, so you must subsequently perform parameter initialization or load weights from a checkpoint.

    Whether buffers need to be re-initialized depends on whether they enter the state_dict. Persistent buffers (register_buffer default parameters) enter the state_dict and are handled during DCP save and load operations. Non-persistent buffers (persistent=False) do not enter the state_dict and will not be auto-filled during checkpoint recovery. The sinusoidal positional encoding in this article’s example is a non-persistent buffer, so it is explicitly recalculated in init_weights.

    2. Sharding and Forward Pass. For each module wrapped by fully_shard, the required parameters are collected via all-gather before forward computation and released after computation if they do not belong to the local shard. reshard_after_forward controls this release behavior, with a default value of True. Setting it to True saves VRAM but requires gathering parameters again before the backward pass, increasing communication overhead. Setting it to False reduces communication but increases VRAM usage. The sharding granularity is determined by the wrapped module, so peak VRAM primarily depends on the largest wrapped module.

    3. Gradient Synchronization. During backward propagation, gradients are reduced via reduce-scatter, so each rank only retains the gradient segment it is responsible for. Unlike DDP’s all-reduce, each GPU does not need to hold the full gradient. The optimizer subsequently executes step only on the local shard, ensuring optimizer states are also stored in a sharded manner.

    4. Communication and Compute Overlap. FSDP2 executes all-gather asynchronously on independent CUDA streams, allowing it to prefetch parameters for subsequent blocks while computing the current block. If communication time for a step exceeds compute time, the GPU will idle. In this case, you can use a profiler to check the communication ratio.

    1. import torch
    2. from torch.profiler import profile, ProfilerActivity
    3. with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
    4. for _ in range(3):
    5. train_one_step() # Replace with your actual single-step training function
    6. prof.export_chrome_trace("trace_rank0.json")
    7. print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=20))

    In the output table, kernels with names containing nccl belong to communication, while the rest are computation. If the CUDA time for communication kernels accounts for a high proportion of the total and GPU utilization is low, you can try refining the wrapping granularity or adjusting prefetch settings. The above ratio is an empirical judgment and should be evaluated based on the specific model and network conditions.

    4. Environment Setup

    The recommended environment is as follows:

    • Python 3.10 or higher
    • PyTorch 2.6 or higher, using the official build that matches your CUDA version
    • NVIDIA driver version that meets the requirements of your chosen CUDA version
    • NCCL can use the version bundled with PyTorch; no separate installation is needed

    Example installation command (using CUDA 12.4):

    1. pip install torch --index-url https://download.pytorch.org/whl/cu124

    5. Complete Training Code

    The code below is a minimal runnable example. The model size is very small and uses randomly synthesized data to facilitate process validation. To replace it with a real model and data, simply modify MultimodalModel and SyntheticPairs.

    It is recommended to test it on 2 GPUs first before scaling to more.

    1. # train_fsdp2.py
    2. import argparse
    3. import math
    4. import os
    5. import torch
    6. import torch.distributed as dist
    7. import torch.distributed.checkpoint as dcp
    8. import torch.nn as nn
    9. import torch.nn.functional as F
    10. from torch.distributed.checkpoint.state_dict import (
    11. get_model_state_dict,
    12. set_model_state_dict,
    13. )
    14. from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
    15. from torch.utils.data import DataLoader, Dataset
    16. from torch.utils.data.distributed import DistributedSampler
    17. class Block(nn.Module):
    18. def __init__(self, dim):
    19. super().__init__()
    20. self.norm = nn.LayerNorm(dim)
    21. self.ff = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))
    22. def forward(self, x):
    23. return x + self.ff(self.norm(x))
    24. def sinusoid_table(max_len, dim):
    25. pos = torch.arange(max_len, dtype=torch.float32).unsqueeze(1)
    26. div = torch.exp(torch.arange(0, dim, 2, dtype=torch.float32) * (-math.log(10000.0) / dim))
    27. pe = torch.zeros(max_len, dim, dtype=torch.float32)
    28. pe[:, 0::2] = torch.sin(pos * div)
    29. pe[:, 1::2] = torch.cos(pos * div)
    30. return pe
    31. class MultimodalModel(nn.Module):
    32. def __init__(self, vocab=32000, dim=512, max_text=256, patch=16, depth=4):
    33. super().__init__()
    34. self.dim = dim
    35. self.max_text = max_text
    36. self.patch_embed = nn.Conv2d(3, dim, kernel_size=patch, stride=patch)
    37. self.vision = nn.ModuleList([Block(dim) for _ in range(depth)])
    38. self.embed = nn.Embedding(vocab, dim)
    39. self.text = nn.ModuleList([Block(dim) for _ in range(depth)])
    40. self.fusion = nn.ModuleList([Block(dim) for _ in range(depth)])
    41. self.norm = nn.LayerNorm(dim)
    42. self.head = nn.Linear(dim, vocab, bias=False)
    43. # Non-persistent buffer, does not enter state_dict, not saved by DCP
    44. self.register_buffer("pe", torch.zeros(max_text, dim), persistent=False)
    45. def init_weights(self):
    46. for m in self.modules():
    47. if hasattr(m, "reset_parameters"):
    48. m.reset_parameters()
    49. self.pe.copy_(sinusoid_table(self.max_text, self.dim).to(self.pe.device))
    50. def forward(self, images, tokens):
    51. v = self.patch_embed(images).flatten(2).transpose(1, 2)
    52. for blk in self.vision:
    53. v = blk(v)
    54. t = self.embed(tokens)
    55. t = t + self.pe[: tokens.size(1)].to(t.dtype)
    56. for blk in self.text:
    57. t = blk(t)
    58. x = torch.cat([v, t], dim=1)
    59. for blk in self.fusion:
    60. x = blk(x)
    61. x = self.norm(x[:, v.size(1):])
    62. return self.head(x)
    63. class SyntheticPairs(Dataset):
    64. """Replace with a real dataset. Returns (image, token sequence)."""
    65. def __init__(self, n, vocab, seq_len, img_size):
    66. self.n = n
    67. self.vocab = vocab
    68. self.seq_len = seq_len
    69. self.img_size = img_size
    70. def __len__(self):
    71. return self.n
    72. def __getitem__(self, idx):
    73. g = torch.Generator().manual_seed(idx)
    74. img = torch.randn(3, self.img_size, self.img_size, generator=g)
    75. tokens = torch.randint(0, self.vocab, (self.seq_len + 1,), generator=g)
    76. return img, tokens
    77. def save_model(model, path):
    78. dcp.save({"model": get_model_state_dict(model)}, checkpoint_id=path)
    79. def load_model(model, path):
    80. state = {"model": get_model_state_dict(model)}
    81. dcp.load(state, checkpoint_id=path)
    82. set_model_state_dict(model, model_state_dict=state["model"])
    83. def parse_args():
    84. p = argparse.ArgumentParser()
    85. p.add_argument("--steps", type=int, default=100)
    86. p.add_argument("--batch", type=int, default=2)
    87. p.add_argument("--lr", type=float, default=3e-4)
    88. p.add_argument("--ckpt", type=str, default="./ckpt")
    89. p.add_argument("--save_every", type=int, default=50)
    90. p.add_argument("--init_from", type=str, default="")
    91. return p.parse_args()
    92. def main():
    93. args = parse_args()
    94. dist.init_process_group("nccl")
    95. local_rank = int(os.environ["LOCAL_RANK"])
    96. torch.cuda.set_device(local_rank)
    97. device = torch.device("cuda", local_rank)
    98. rank = dist.get_rank()
    99. # 1. Construct model on meta device, no VRAM allocated
    100. with torch.device("meta"):
    101. model = MultimodalModel()
    102. # 2. Shard sub-blocks first, then shard the root module
    103. mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
    104. for blk in list(model.vision) + list(model.text) + list(model.fusion):
    105. fully_shard(blk, mp_policy=mp)
    106. fully_shard(model, mp_policy=mp)
    107. # 3. Materialize, initialize, and load checkpoint if needed
    108. model.to_empty(device=device)
    109. model.init_weights()
    110. if args.init_from:
    111. load_model(model, args.init_from)
    112. # Optimizer must be created after parameters are materialized
    113. optimizer = torch.optim.AdamW(
    114. model.parameters(), lr=args.lr, betas=(0.9, 0.95), weight_decay=0.1
    115. )
    116. ds = SyntheticPairs(n=10000, vocab=32000, seq_len=128, img_size=64)
    117. sampler = DistributedSampler(ds, shuffle=True)
    118. loader = DataLoader(ds, batch_size=args.batch, sampler=sampler,
    119. num_workers=2, drop_last=True)
    120. model.train()
    121. step = 0
    122. epoch = 0
    123. while step < args.steps:
    124. sampler.set_epoch(epoch)
    125. for images, tokens in loader:
    126. if step >= args.steps:
    127. break
    128. images = images.to(device, non_blocking=True)
    129. tokens = tokens.to(device, non_blocking=True)
    130. inputs, labels = tokens[:, :-1], tokens[:, 1:]
    131. logits = model(images, inputs)
    132. loss = F.cross_entropy(
    133. logits.float().reshape(-1, logits.size(-1)), labels.reshape(-1)
    134. )
    135. loss.backward()
    136. torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    137. optimizer.step()
    138. optimizer.zero_grad(set_to_none=True)
    139. step += 1
    140. if rank == 0 and step % 10 == 0:
    141. print(f"step {step} loss {loss.item():.4f}", flush=True)
    142. if step % args.save_every == 0:
    143. save_model(model, f"{args.ckpt}/step_{step}")
    144. epoch += 1
    145. save_model(model, f"{args.ckpt}/final")
    146. dist.destroy_process_group()
    147. if __name__ == "__main__":
    148. main()

    The example above only restores the model weights. For continued training where you also need to restore optimizer states, you can use DCP’s optimizer state dict interfaces.