FSDP2 Sharding and Communication Practices for Trillion-Parameter Training
Training models at the trillion-parameter scale requires carefully balancing memory, communication, and fault recovery. This article walks through practical FSDP2 techniques: estimating memory requirements, configuring sharding with fully_shard, understanding real communication overhead, combining FSDP2 with tensor and pipeline parallelism, gradient accumulation, distributed checkpointing, multimodal data loading, and how to validate your configuration against a baseline.
1. Calculate Memory Requirements First
Before training, estimate memory usage to determine the sharding scale. Take a hypothetical 2.8-trillion-parameter model as an example. Weights stored in FP32 require about 11.2 TB, and about 5.6 TB in BF16. These figures cover only the weights themselves.
With BF16 mixed precision and the Adam optimizer, each parameter typically occupies about 16 bytes: 2 bytes each for the BF16 weight and gradient, and 4 bytes each for the FP32 master weight, first-order momentum, and second-order momentum. At this rate, model states alone require roughly 44.8 TB. On 80 GB GPUs, the theoretical minimum is about 560 GPUs—and that excludes activations, communication buffers, and memory fragmentation.
These numbers make it clear that pure data parallelism is not viable. Each GPU can hold only a fraction of the model states, which is exactly why sharding exists.
2. How FSDP2 Shards Parameters
FSDP2 shards at the granularity of individual parameters. Each parameter is split along dimension 0, and each data-parallel rank holds one chunk. The framework represents sharded parameters as DTensors and describes their layout via Shard(0). Splitting parameters along rows or columns for matrix operations belongs to tensor parallelism, not FSDP2.
During the forward pass, the framework all-gathers the parameters of the layers being computed, temporarily reconstructing the full parameter, and releases it after computation. During the backward pass, it all-gathers again, computes gradients, and then runs reduce-scatter so each rank keeps only its own gradient shard. The reshard_after_forward flag controls whether the full parameter is released immediately after the forward pass. Enabling it lowers peak memory but requires another all-gather in the backward pass, increasing communication volume.
Here is a reference code snippet showing the typical call order of fully_shard in PyTorch. The import paths assume PyTorch 2.6 or later; for other versions, refer to the corresponding documentation.
import torchfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicymesh = init_device_mesh("cuda", (world_size,))mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16,reduce_dtype=torch.float32,)# Shard each Transformer layer first, then shard the root modulefor block in model.layers:fully_shard(block, mesh=mesh, mp_policy=mp_policy, reshard_after_forward=True)fully_shard(model, mesh=mesh, mp_policy=mp_policy)optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
model.layers is only illustrative; the actual attribute name depends on the model implementation. Replace world_size with the actual number of data-parallel GPUs.
The benefit of per-layer sharding is that each all-gather reconstructs only one layer’s parameters, so peak memory is bounded by the largest single layer rather than the whole model. If you shard only the root module, all parameters are reconstructed in a single all-gather, creating heavy memory pressure.
The optimizer must be created after fully_shard, so that it receives the sharded parameters.
3. What Actually Happens to Communication Volume
Some materials claim FSDP reduces communication to 1/N of DDP. This is inaccurate.
With a ring algorithm, DDP transfers about 2P bytes per GPU per step (P being the parameter size in bytes), corresponding to one all-reduce. FSDP performs two all-gathers and one reduce-scatter per step, totaling about 3P bytes per GPU. FSDP’s communication volume is slightly higher than DDP’s; what it buys is a dramatic reduction in memory usage.
Therefore, the optimization direction is to hide communication, not to reduce its volume. Common techniques include:
- Enable forward prefetching to pull the next layer’s parameters while computing the current layer.
- Tune the sharding group size so communication-heavy process groups sit within the same machine’s NVLink domain.
- Use a profiler to verify that communication overlaps with computation and to locate any serialized waits.
4. Combining the Three Parallelism Strategies
Very large-scale training typically combines multiple parallelism strategies. FSDP2 handles parameter sharding along the data-parallel dimension, tensor parallelism (TP) splits matrices within layers, and pipeline parallelism (PP) places different layers on different device groups.
A common rule of thumb: tensor parallelism has the most frequent communication, so it should stay within a single machine’s high-speed interconnect. FSDP2 can span machines because its communication can overlap with computation layer by layer. Introduce pipeline parallelism only when the model has so many layers that a single machine cannot hold them.
FSDP2 supports two-dimensional DeviceMesh, which allows combining FSDP with tensor parallelism. The mesh dimension split must match the hardware topology; a mismatched split will significantly increase cross-machine communication.
5. Writing Gradient Accumulation
When the global batch size is constrained, gradient accumulation is a common approach. With FSDP2, intermediate micro-steps do not need gradient synchronization—sync only once on the last micro-step.
num_micro = len(micro_batches)for i, micro_batch in enumerate(micro_batches):is_last = (i == num_micro - 1)model.set_requires_gradient_sync(is_last)loss = model(micro_batch).loss / num_microloss.backward()optimizer.step()optimizer.zero_grad()
During accumulation, gradients are stored in sharded form, so each GPU only needs to hold one extra sharded gradient rather than a full one.
6. Checkpoint Saving and Recovery
Checkpoints for 2.8 trillion parameters are enormous. Gathering the full model onto a single GPU before saving is both slow and prone to OOM. Use the distributed checkpoint API so each rank writes only its own shard.
torch.distributed.checkpoint supports this mode: each rank writes its own data files, while one rank writes the unified metadata.
Three practices make this reliable:
- Write to a temporary directory first and rename it to the final name only after all writes complete, avoiding incomplete checkpoints after interruptions.
- Update the pointer file to the latest checkpoint last, pointing only to directories that have passed validation.
- Keep several recent versions so you can roll back if recovery fails.
Example directory structure (file names are illustrative):
ckpt/step_000100.tmp/ # still being writtenstep_000100/ # renamed after writing completes.metadata__0_0.distcp__1_0.distcplatest.txt # updated only after validation passes
Asynchronous saving allows disk writes to run in parallel with training. During async saving, however, you must ensure snapshot consistency and limit the number of concurrent save tasks to avoid saturating storage bandwidth. After recovery, compare the loss over the next few steps to confirm it matches the pre-interruption trend.
7. Multimodal Data Loading Considerations
In multimodal training, each modality usually has its own loader. Text, image, and audio tokenization and batch construction differ substantially, so keep the following in mind when combining them.
First, all data-parallel ranks must have the same number of steps. If one rank runs out of data early, it will wait at the next collective communication and block all other ranks—the training appears to hang. Fix the number of steps per epoch, or pad/drop the tail of each dataset to avoid this.
Second, bucket by sequence length. When sequences within a batch have similar lengths, padding waste is reduced. Image resolutions should likewise be unified into a small set of tiers.
Third, call fully_shard separately on the vision encoder and the text decoder. Vision encoders have few layers but large per-layer parameters, so per-layer sharding offers limited benefit—sharding the whole submodule is fine. Text decoders have many layers and suit per-layer sharding. Choose the sharding granularity based on the actual parameter size of each layer.
8. Choosing the Sharding Granularity
Sharding granularity involves a trade-off. Finer granularity lowers peak memory but increases the number of all-gathers, so communication latency accumulates. Coarser granularity reduces communication count but raises peak memory.
In practice, the Transformer layer is a common unit. If a single layer’s parameters are already small, per-layer sharding generates many tiny communications and actually slows things down. If a single layer is very large, all-gathering the entire layer will exhaust memory, requiring further splitting. Base the decision on communication time and peak memory observed in the profiler.
9. Common FSDP2 Mistakes
- Sharding only some submodules while leaving the root module unsharded, so some parameters still keep full replicas.
- Creating the optimizer before sharding, so optimizer states no longer match the parameters.
- Inconsistent batch counts or sample distributions across ranks, causing collective communication to hang.
- Gathering the full state_dict onto rank 0 when saving checkpoints, exhausting memory.
- Watching only the loss curve without monitoring peak memory and communication share, so problems surface very late.
- Enabling CPU offload without evaluating its cost. CPU offload saves memory but introduces heavy PCIe transfers, which can noticeably reduce throughput.
10. Validating Your Configuration
After adjusting a configuration, run a controlled comparison against a baseline. Keep the model, data, and global batch identical, changing only the parameter under test.
Record three categories of metrics:
- Peak memory: read torch.cuda.max_memory_allocated, and also record max_memory_reserved to observe fragmentation.
- Throughput: measure tokens processed per second, averaged over multiple steps in the stable phase, skipping the warm-up steps.
- Communication share: use the profiler to time all-gather and reduce-scatter, and check how well they overlap with computation.
When reporting results, always note the hardware topology, GPU count, parallelism configuration, and number of measured steps. Numbers without these conditions are neither reproducible nor comparable.
Conclusion
The challenge of trillion-parameter training is that memory, communication, and fault recovery must all be satisfied simultaneously. FSDP2 primarily solves the memory problem, while communication overlap and checkpointing still require separate design. It is advisable to validate configurations on smaller models first, confirm that peak memory and throughput meet expectations, and then scale up gradually.
