Trillion-Parameter Model Training: FSDP2 Sharding and Gradient Synchronization

    Training models at the trillion-parameter scale introduces immense engineering challenges across memory, communication, scheduling, and ecosystem compatibility. This article explores the practical bottlenecks of training a 2.8 trillion-parameter multimodal model and provides actionable solutions. It delves into the mechanics of PyTorch's FSDP2 for per-parameter sharding, offers a runnable code example for loading and sharding, estimates gradient synchronization communication overhead, and outlines data packing strategies for multimodal workloads. Finally, it provides a five-step validation checklist for adapting these training pipelines to localized or non-mainstream hardware accelerators.

    1. Background and Metric Standards

    Recently, a flagship multimodal model with a parameter scale of 2.8 trillion was made public. This article does not name the model nor make performance claims about its training results. The figures below are calculated using standard metrics, allowing readers to apply the same methods to their own models.

    • Weights: Stored in BF16, 2 bytes per parameter. A 2.8 trillion parameter model requires about 5.6TB.
    • Full model state in mixed precision training: 2 bytes for BF16 parameters, 2 bytes for BF16 gradients, 4 bytes for FP32 master weights, and 4 bytes each for AdamW first-order and second-order momentums. This totals 16 bytes per parameter, or about 44.8TB.
    • The above figures do not include activations, communication buffers, or VRAM fragmentation.

    For every order of magnitude increase in parameter scale, the engineering complexity grows primarily in four areas: memory, communication, scheduling, and fault tolerance—rather than just a simple linear scaling.

    2. Four Bottlenecks and Mitigation Strategies

    Bottleneck Typical Symptoms Common Mitigations Suggested Validation Thresholds
    Memory Wall Single GPU cannot fit weights and optimizer states Full sharding, activation recomputation, optimizer state sharding Peak VRAM per GPU below ~85% of total capacity
    Communication Wall Gradient synchronization takes too high a percentage of a single step Compute-communication overlap, rational parallel group division, HSDP Communication exposure time below ~15% of step time
    Scheduling Wall Large variance in sample lengths causes some GPUs to wait Sequence packing, length-based bucketing, dynamic batching Step time variance across GPUs below ~10%
    Ecosystem Wall Missing operators, incorrect or slow collective communication Operator replacement, custom operators, communication library tuning Single operator results match reference implementation within tolerance

    The above thresholds are common starting points; actual projects need recalibration based on model structure and hardware.

    3. Hardware Requirements for Integrated Training and Inference Chips

    On the training side, three main factors are evaluated: single-GPU VRAM capacity and bandwidth, intra-node high-speed interconnect (e.g., NVLink or vendor-proprietary interconnects), and cross-node network bandwidth. PCIe networking can increase GPU count, but its bandwidth is far lower than intra-node high-speed interconnects, making it unsuitable as a unified large VRAM pool. Cross-node bandwidth must be verified separately using collective communication benchmarks.

    The inference side focuses on low latency and VRAM footprint. “Integrated training and inference” means that the same runtime and memory management serve both training and inference, thereby reducing the workload of checkpoint conversion and deployment migration. This benefit assumes that training and inference use the same version of the framework plugin; otherwise, migration costs remain.

    The software stack determines adaptation costs. The versions of the CUDA-like unified compute architecture (e.g., abstraction layers like MUSA), operator libraries, communication libraries, and PyTorch device adaptation layers must be cross-checked in a matrix before training begins.

    4. FSDP2: Per-Parameter Sharding

    Fully Sharded Data Parallel (FSDP) shards parameters, gradients, and optimizer states across devices. During forward and backward passes, it aggregates (all-gather) the parameters needed for the current module on demand and releases them immediately after use.

    PyTorch’s FSDP2 uses fully_shard as its entry point, sharding each module’s parameters based on DTensor. Compared to the first-generation implementation based on FlatParameter, there are three practical differences:

    1. Sharding granularity can reach the sub-module level. The vision encoder and the language model backbone can choose different wrapping granularities.
    2. Parameters retain their original shapes, making low-precision training and quantization-related processing more straightforward.
    3. Parameters exist as DTensors, allowing distributed checkpoint interfaces to be used directly for saving and loading.

    Versioning requires attention. fully_shard under torch.distributed.fsdp is available in PyTorch 2.6 and later; in versions 2.4 to 2.5, it is located under torch.distributed._composable.fsdp. For localized accelerators, the PyTorch version is determined by the vendor’s plugin, and the vendor’s release notes should prevail.

    The memory benefits of FSDP2 come with a cost. Each all-gather consumes temporary VRAM, so static estimation must be done before training, and the actual peak should be monitored during training. For low-precision training, loss and gradient norms must also be monitored; numerical stability should be checked especially when mixing BF16 and FP8.

    5. Runnable Loading and Sharding Example

    The following example requires PyTorch 2.6 or higher and the vendor’s PyTorch plugin installed. device_type depends on the device name registered by the vendor; it is "cuda" for NVIDIA environments, and other environments should refer to vendor documentation. Verify the interface signatures according to your version before running.

    1. import os
    2. import torch
    3. import torch.distributed as dist
    4. import torch.distributed.checkpoint as dcp
    5. from torch.distributed.device_mesh import init_device_mesh
    6. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    7. def build_model(config):
    8. # User's own model building function; the returned module must contain vision_encoder.blocks and language_model.layers
    9. ...
    10. def main():
    11. device_type = os.environ.get("DEVICE_TYPE", "cuda")
    12. dist.init_process_group(backend=os.environ.get("DIST_BACKEND", "nccl"))
    13. local_rank = int(os.environ["LOCAL_RANK"])
    14. device = torch.device(device_type, local_rank)
    15. world_size = dist.get_world_size()
    16. # Use a 1D mesh for single-node multi-GPU; for multi-node HSDP, change to a 2D mesh like (n_nodes, gpus_per_node)
    17. mesh = init_device_mesh(device_type, (world_size,), mesh_dim_names=("shard",))
    18. # 1. Build model on meta device, does not occupy real VRAM
    19. with torch.device("meta"):
    20. config = None # Fill in configuration per project
    21. model = build_model(config)
    22. # 2. Shard sub-modules first, then wrap the root module, so each block's parameters are gathered independently
    23. mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
    24. for block in model.vision_encoder.blocks:
    25. fully_shard(block, mesh=mesh, mp_policy=mp)
    26. for layer in model.language_model.layers:
    27. fully_shard(layer, mesh=mesh, mp_policy=mp)
    28. fully_shard(model, mesh=mesh, mp_policy=mp)
    29. # 3. Allocate real VRAM for the sharded parameters, contents are uninitialized at this point
    30. model.to_empty(device=device)
    31. # Non-persistent buffers (e.g., rotary position encoding frequency table) need manual re-initialization after to_empty
    32. # 4. Read directly from the distributed checkpoint by shard, without loading the full model onto a single GPU
    33. state = {"model": model.state_dict()}
    34. dcp.load(state, checkpoint_id=os.environ["CKPT_DIR"])
    35. optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0.1)
    36. model.train()
    37. for step, batch in enumerate(loader): # loader provided by user's data pipeline
    38. batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}
    39. loss = model(**batch).loss
    40. loss.backward() # Reverse pass automatically does gradient reduce-scatter
    41. torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
    42. optimizer.step() # Each rank only updates its local parameter shard
    43. optimizer.zero_grad(set_to_none=True)
    44. if dist.get_rank() == 0 and step % 100 == 0:
    45. print(f"step={step} loss={loss.item():.4f}")
    46. dist.destroy_process_group()
    47. if __name__ == "__main__":
    48. main()

    Example launch command:

    1. DEVICE_TYPE=cuda CKPT_DIR=/path/to/ckpt \
    2. torchrun --nnodes=4 --nproc-per-node=8 train.py

    The build_model and loader in the example need to be replaced with your project’s own implementations. model.state_dict() returns the sharded DTensors, and dcp.load writes in-place to the respective shards on each GPU, so there is no need to call load_state_dict again after loading.

    6. Gradient Synchronization Communication Volume Estimation

    After the backward pass, FSDP2 uses reduce-scatter to aggregate gradients and shard them across GPUs, with each GPU keeping only the gradient portion it is responsible for. Subsequently, each GPU only updates its local parameter shard and does not need to broadcast the full parameters.

    Estimating the send volume for a single rank using the ring algorithm: assuming a shard group size of N and a data volume of D per collective communication, the data sent by a single rank is approximately (N−1)/N × D. Under the assumption of one forward pass, one backward re-aggregation (when reshard_after_forward is enabled), and one gradient reduce-scatter, the total volume per step is approximately:

    • Forward all-gather: BF16 parameters, ~2P bytes;
    • Backward all-gather: BF16 parameters, ~2P bytes;
    • Gradient reduce-scatter: FP32 reduction, ~4P bytes.

    The total is approximately 8P bytes multiplied by (N−1)/N, where P is the number of parameters. This volume is directly proportional to P. As N increases, (N−1)/N approaches 1, and the send volume per GPU approaches a constant, avoiding quadratic growth with the number of GPUs. This estimation ignores activation communication, overlapping effects, and protocol overhead; actual values must be measured using communication profiling tools.

    7. Multimodal Data Packing and Load Balancing

    After passing through the vision encoder, image and video sequences are much longer than standard text and are unevenly distributed. If padded to the longest sequence within a batch, substantial compute is wasted on padding.

    For example, a batch contains four samples with lengths of 512, 1024, 3072, and 768, totaling 5376 valid tokens. If padded to 3072, the batch size is 4, totaling 16384 positions, with an effective utilization rate of 32.8%. By switching to packing with a length of 4096, the 3072 and 1024 sequences are combined into one 4096 sequence, and the 512 and 768 are combined and padded to 4096. This totals 8192 positions, increasing utilization to 65.6%. Packing must be paired with block-diagonal attention masks to prevent cross-attention between different samples.

    Load balancing is equally important. The computational overhead for vision tokens differs from text tokens, so shard scheduling should allocate tasks based on per-step execution time rather than token count. It is recommended to record the execution time per GPU every few steps and adjust bucketing rules when they exceed a threshold.

    8. Five-Step Validation Checklist for Localized Hardware Adaptation

    Step Validation Criteria Common Checks Common Failures & Troubleshooting
    1. Operator Coverage Single-GPU forward and backward pass successful; output error vs. reference implementation within tolerance Compare outputs layer by layer; record missing operator list Missing operators: replace with equivalent combinations or write custom operators; Large error: check precision conversion points
    2. Communication Integration all-reduce, all-gather, reduce-scatter results correct; bandwidth close to a certain proportion of theoretical value Use vendor-provided collective communication benchmark tools; record intra-node and cross-node results Incorrect results: check NIC and comm library versions; Low bandwidth: check topology and binding config
    3. Parallel Strategy Small-scale trial run throughput stable; peak VRAM within budget Record per-step time, peak VRAM, communication exposure time OOM: increase sharding granularity or enable activation recomputation; High comm exposure: adjust prefetch and grouping
    4. Full-link Stress Test Long-term training loss curve stable; checkpoint save and restore consistent Periodically save checkpoints and restore on another set of GPUs; compare subsequent loss Loss jump after restore: check if optimizer states and random seeds are saved alongside
    5. Performance Tuning MFU gradually improves without affecting numerical results Compare before and after operator fusion; record MFU changes Numerical drift: roll back corresponding optimization and verify item by item

    Calculating MFU (Model FLOPs Utilization) requires a clear denominator, i.e., whether peak compute is calculated based on which precision, and recording the batch size and sequence length during statistics. MFU across different projects can only be compared under identical metrics.

    9. Conclusion and Risk Warnings

    The successful training of a model exceeding 2.8 trillion parameters on a localized software stack demonstrates the feasibility of this engineering path. However, the information this article is based on is limited; figures regarding throughput, MFU, and stability must be re-measured under specific hardware, interconnects, and framework versions.

    The sharding and gradient synchronization mechanisms of FSDP2 already have mature open-source implementations. The primary work in adaptation focuses on operator coverage, communication libraries, and device plugins. The maturity of these components varies by vendor and version, so selection should be based on real test data rather than directly applying others’ conclusions. For developers, understanding the underlying mechanisms of sharding, gathering, and reduction holds more long-term value than memorizing a specific interface.