FSDP2 Multimodal Training: Sharding, Communication, and Checkpointing

    This article covers the memory budget for mixed-precision AdamW training, compares FSDP1 and FSDP2 sharding, walks through the all-gather and reduce-scatter order in a Transformer block, and provides a torchrun-compatible FSDP2 skeleton for a toy multimodal model.

    1. Working Out the Memory Budget

    Take mixed-precision AdamW as a common example. Each parameter needs several kinds of storage: 2 bytes for the bf16 weight, 2 bytes for the bf16 gradient, 4 bytes for the fp32 master weight, and 4 bytes each for the fp32 momentum and variance. The total is about 16 bytes per parameter. This figure applies to AdamW with mixed precision, an fp32 master weight, and fp32 optimizer states. It excludes activations and temporary buffers.

    A model with one trillion parameters needs about 16 TB for its model states. If those states are evenly sharded across 1,024 GPUs, each GPU needs about 16 GB for model states. Activations must still be calculated separately. They grow with sequence length, batch size, and layer count, and they often take up more memory than the model states.

    Sharding adds communication. Before each computation, parameters must be gathered temporarily. The trade-off between memory and communication is the starting point for adaptation. All numbers in this article are estimates. They help set a configuration direction and do not represent measured results on any specific hardware.

    2. Confirming the Hardware and Software Stack

    Before you start, check the following items.

    Check item Why it matters Recommended practice
    PyTorch version The location and parameters of the FSDP2 APIs changed across versions Use PyTorch 2.6 or later, and follow the official documentation for your version
    Communication backend version all-gather, reduce-scatter, and all-to-all require backend support Record the NCCL or vendor backend version and match it to your image
    DeviceMesh The shard group size is determined by the mesh Confirm that the world size matches the mesh shape before launch
    Per-GPU memory and bandwidth Determines shard granularity and recomputation strategy Measure peak memory once with a small model
    Interconnect topology Determines whether communication crosses nodes Run nvidia-smi topo -m to view the connections between GPUs

    Many adaptation problems come from version mismatches. The command below quickly checks the versions and whether the NCCL backend is available.

    1. python -c "import torch, torch.distributed as dist; \
    2. print('torch', torch.__version__); \
    3. print('cuda', torch.version.cuda); \
    4. print('nccl available', dist.is_nccl_available()); \
    5. print('nccl version', torch.cuda.nccl.version())"

    3. FSDP2 Sharding and Execution Order

    FSDP2 is built on DTensor and shards each parameter independently. FSDP1 instead concatenates multiple parameters into one flat parameter and then splits that. The differences are summarized below.

    Dimension FSDP1 FSDP2
    Parameter representation Multiple parameters concatenated into a FlatParameter Each parameter represented independently as a DTensor
    Sharding method Splits the flattened one-dimensional parameter Splits along the dimension specified by the device mesh and placement, dimension 0 by default
    Multi-dimensional parallelism Limited combination options Can be combined with other parallelism types on a multi-dimensional device mesh
    Mixed precision and offloading Configured through wrapped parameters Configured through MixedPrecisionPolicy and CPUOffloadPolicy

    The shard layout is set explicitly by the device mesh and placement. The framework does not decide the layout automatically from the computation graph.

    When training a Transformer block, the execution order is roughly as follows:

    1. Before the forward pass, all-gather the full parameters of the block.
    2. After the forward pass, release the full parameters and keep only the local shard. reshard_after_forward controls this step.
    3. Before the backward pass, all-gather the block’s parameters again.
    4. After the backward pass produces local gradients, reduce-scatter them and return them to each GPU’s shard.

    With a ring algorithm, each GPU sends about (p−1)/p × S data in each collective call. Here p is the shard group size, and S is the number of parameter bytes in the unit. This formula assumes fixed parameter bytes, no link congestion, and an ideal ring algorithm. It compares the communication volume of a single call and does not directly indicate end-to-end speed. Whether communication overlaps with computation is the main factor that affects speed.

    Below is a skeleton that can be launched with torchrun. The model is a toy multimodal network used to verify the wrapping flow.

    1. import os
    2. import torch
    3. import torch.distributed as dist
    4. import torch.nn as nn
    5. from torch.distributed.device_mesh import init_device_mesh
    6. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    7. class ToyMultimodal(nn.Module):
    8. def __init__(self, dim=1024, layers=4):
    9. super().__init__()
    10. self.vision_blocks = nn.ModuleList([nn.Linear(dim, dim) for _ in range(layers)])
    11. self.text_blocks = nn.ModuleList([nn.Linear(dim, dim) for _ in range(layers)])
    12. self.fuse = nn.Linear(2 * dim, dim)
    13. def forward(self, img_feat, txt_feat):
    14. v = img_feat
    15. for blk in self.vision_blocks:
    16. v = torch.relu(blk(v))
    17. t = txt_feat
    18. for blk in self.text_blocks:
    19. t = torch.relu(blk(t))
    20. return self.fuse(torch.cat([v, t], dim=-1))
    21. def setup():
    22. dist.init_process_group(backend="nccl")
    23. local_rank = int(os.environ["LOCAL_RANK"])
    24. torch.cuda.set_device(local_rank)
    25. return init_device_mesh("cuda", (dist.get_world_size(),))
    26. def wrap(model, mesh):
    27. mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
    28. for blk in model.vision_blocks:
    29. fully_shard(blk, mesh=mesh, mp_policy=mp)
    30. for blk in model.text_blocks:
    31. fully_shard(blk, mesh=mesh, mp_policy=mp)
    32. fully_shard(model, mesh=mesh, mp_policy=mp) # Wrap the remaining parameters, such as the fuse layer
    33. return model
    34. def main():
    35. mesh = setup()
    36. model = wrap(ToyMultimodal().cuda(), mesh)
    37. # The optimizer must be created after fully_shard so that its states are sharded as DTensors
    38. optim = torch.optim.AdamW(model.parameters(), lr=1e-4)
    39. img = torch.randn(8, 1024, device="cuda")
    40. txt = torch.randn(8, 1024, device="cuda")
    41. loss = model(img, txt).pow(2).mean()
    42. loss.backward()
    43. optim.step()
    44. optim.zero_grad(set_to_none=True)
    45. dist.destroy_process_group()
    46. if __name__ == "__main__":
    47. main()

    Launch the script with torchrun --nproc_per_node=2 train_fsdp2_smoke.py.

    4. Communication Order Risks in Multimodal Training