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.
python -c "import torch, torch.distributed as dist; \print('torch', torch.__version__); \print('cuda', torch.version.cuda); \print('nccl available', dist.is_nccl_available()); \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:
- Before the forward pass, all-gather the full parameters of the block.
- After the forward pass, release the full parameters and keep only the local shard.
reshard_after_forwardcontrols this step. - Before the backward pass, all-gather the block’s parameters again.
- 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.
import osimport torchimport torch.distributed as distimport torch.nn as nnfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicyclass ToyMultimodal(nn.Module):def __init__(self, dim=1024, layers=4):super().__init__()self.vision_blocks = nn.ModuleList([nn.Linear(dim, dim) for _ in range(layers)])self.text_blocks = nn.ModuleList([nn.Linear(dim, dim) for _ in range(layers)])self.fuse = nn.Linear(2 * dim, dim)def forward(self, img_feat, txt_feat):v = img_featfor blk in self.vision_blocks:v = torch.relu(blk(v))t = txt_featfor blk in self.text_blocks:t = torch.relu(blk(t))return self.fuse(torch.cat([v, t], dim=-1))def setup():dist.init_process_group(backend="nccl")local_rank = int(os.environ["LOCAL_RANK"])torch.cuda.set_device(local_rank)return init_device_mesh("cuda", (dist.get_world_size(),))def wrap(model, mesh):mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)for blk in model.vision_blocks:fully_shard(blk, mesh=mesh, mp_policy=mp)for blk in model.text_blocks:fully_shard(blk, mesh=mesh, mp_policy=mp)fully_shard(model, mesh=mesh, mp_policy=mp) # Wrap the remaining parameters, such as the fuse layerreturn modeldef main():mesh = setup()model = wrap(ToyMultimodal().cuda(), mesh)# The optimizer must be created after fully_shard so that its states are sharded as DTensorsoptim = torch.optim.AdamW(model.parameters(), lr=1e-4)img = torch.randn(8, 1024, device="cuda")txt = torch.randn(8, 1024, device="cuda")loss = model(img, txt).pow(2).mean()loss.backward()optim.step()optim.zero_grad(set_to_none=True)dist.destroy_process_group()if __name__ == "__main__":main()
Launch the script with torchrun --nproc_per_node=2 train_fsdp2_smoke.py.
