Training Trillion-Parameter Models: Key Points from Weight Loading to Gradient Synchronization

    Training models at the trillion-parameter scale requires rethinking the entire pipeline—memory estimation, sharding, loading, and gradient synchronization. This article walks through each stage of an FSDP2-based training path using a 2.8-trillion-parameter dense model as an example, covering memory accounting, communication volume, overlap scheduling, checkpointing, and a practical launch checklist.

    Why Large-Scale Training Needs a Redesigned Pipeline

    When training a trillion-parameter model, the challenge is not just that the model does not fit in GPU memory. Memory, communication, and scheduling bottlenecks constrain each other. Finer sharding saves more memory per GPU but increases communication frequency. Denser communication makes compute-communication overlap more valuable, but overlap itself adds scheduling complexity. Adaptation work therefore needs to examine the entire chain—loading, sharding, and synchronization—step by step, rather than tuning a single parameter.

    This article uses a 2.8-trillion-parameter dense model as an example to explain each stage of the training path based on FSDP2 (Fully Sharded Data Parallelism, exposed in PyTorch as the fully_shard API). The code samples are illustrative; replace interfaces according to your actual framework version and hardware platform before use.

    First, Get the Memory Accounting Right

    The estimates below assume the following: weights and gradients use BF16 or FP16 at 2 bytes per parameter; Adam’s first and second moments (m and v) use FP32 at 4 bytes each per parameter; activations are not counted.

    • Weights: 2.8T × 2 bytes ≈ 5.6 TB
    • Gradients: 2.8T × 2 bytes ≈ 5.6 TB
    • Adam’s m and v: 2.8T × 8 bytes ≈ 22.4 TB
    • Total: about 33.6 TB

    If mixed-precision training also keeps FP32 master weights, add 2.8T × 4 bytes ≈ 11.2 TB, bringing the total to about 44.8 TB.

    At 80 GB per GPU, model states alone require at least roughly 420 GPUs (33.6 TB ÷ 80 GB), or about 560 GPUs with FP32 master weights. This figure excludes activations, communication buffers, and memory fragmentation, so the real requirement is higher.

    Note that optimizer state size depends on momentum precision. A rough rule of doubling the weight footprint underestimates it by about half in this example. Always state your precision assumptions explicitly when estimating.

    Communication Volume: How Sharding Compares to Standard Data Parallelism

    Standard data parallelism performs one gradient all-reduce per step. All-reduce can be decomposed into reduce-scatter and all-gather, giving a communication volume of about 2Ψ per parameter, where Ψ is the bytes per parameter.

    FSDP’s sharding scheme requires an all-gather of each layer’s weights during the forward pass, another all-gather during the backward pass, and a reduce-scatter of gradients—for a total of about 3Ψ, or 1.5× standard data parallelism. This matches the analysis in the ZeRO paper. The memory savings from sharding come at the cost of more communication.

    FSDP2 provides the reshard_after_forward option. Keeping the full weights after the forward pass skips the second all-gather in the backward pass but increases memory usage. The choice depends on your memory headroom and network bandwidth. When bandwidth is tight, retaining weights is usually the better trade; when memory is tight, release them.

    Model Loading: Read Metadata First, Then Stream Weights

    The primary goal of the loading phase is to avoid reading all weights into memory at once. A sensible workflow has two steps. First, parse the configuration file and generate a shard plan specifying which file each parameter comes from, along which dimension it is split, and which ranks are responsible for it. Second, read parameter by parameter according to the plan, moving only the slices owned by the current rank into GPU memory.

    The following code is illustrative and shards only along dimension 0; helper functions such as build_shard_plan need to be implemented yourself.

    1. import json
    2. import time
    3. from pathlib import Path
    4. from safetensors import safe_open
    5. def load_sharded_state(model_dir, rank, world_size, device, retries=3):
    6. cfg_path = Path(model_dir) / "config.json"
    7. if not cfg_path.is_file():
    8. raise FileNotFoundError(f"Missing config file: {cfg_path}")
    9. config = json.loads(cfg_path.read_text(encoding="utf-8"))
    10. # plan structure: {param name: {"file": filename, "shape": full shape}}
    11. plan = build_shard_plan(config, world_size)
    12. local_state = {}
    13. for name, spec in plan.items():
    14. local_state[name] = read_slice_with_retry(
    15. model_dir, name, spec, rank, world_size, device, retries
    16. )
    17. return local_state
    18. def read_slice_with_retry(model_dir, name, spec, rank, world_size, device, retries):
    19. last_err = None
    20. for attempt in range(retries):
    21. try:
    22. with safe_open(Path(model_dir) / spec["file"], framework="pt", device="cpu") as f:
    23. sl = f.get_slice(name)
    24. start, end = shard_range(spec["shape"][0], world_size, rank)
    25. tensor = sl[start:end]
    26. return tensor.to(device)
    27. except OSError as err: # retry only transient IO errors
    28. last_err = err
    29. time.sleep(2 ** attempt)
    30. # Never partially load. Missing any parameter makes training results untrustworthy—fail fast.
    31. raise RuntimeError(f"Failed to read parameter {name} after {retries} attempts, aborting load") from last_err

    Several points in this code deserve attention.

    First, load failures should raise errors rather than skip parameters. Skipping leaves weights uninitialized; training may continue to run, but the results are uninterpretable.

    Second, retries should apply only to IO errors. If a file is corrupted or checksums mismatch, retrying is pointless—fail immediately and preserve the state for debugging.

    Third, memory mapping (mmap) suits very large embedding tables because only accessed pages enter memory. However, on network file systems, random-access latency can be high. A more robust approach is to copy weights to local NVMe storage first, then read from local disk.

    Fourth, the device mesh must be established before loading. The mesh dimensions should match your parallelism strategy, such as the number of nodes and GPUs per node. If the mesh is wrong, shards land on the wrong communication domain—a symptom is usually anomalous loss or a sudden throughput drop rather than an explicit error.

    Sharding and Scheduling: Assign by Parameter Block and Topology

    FSDP2 evenly splits each parameter along one dimension across all ranks in the shard group. It does not assign tensors one by one based on memory capacity, so the main scheduling lever is deciding which modules are packaged together. FSDP2 does this by calling fully_shard on modules—each wrapped module becomes one communication unit.

    The granularity of communication units requires trade-offs. Units that are too small produce fragmented all-gather messages and poor bandwidth utilization. Units that are too large increase the number of full parameters resident at any moment, raising peak memory. A common practice is wrapping per Transformer layer, sized so each unit has enough parameters to saturate network bandwidth. The specific threshold depends on network bandwidth, operator granularity, and memory headroom, and should be determined with a profiler rather than copied from rules of thumb.

    Small parameters, such as LayerNorm weights and biases, gain little from separate communication. Bundle them into the same unit as neighboring large parameters to reduce the number of small messages.

    Memory balance can be checked after initialization. The parameter bytes assigned to each rank should be nearly equal; the acceptable deviation is a team-level decision based on memory headroom rather than a fixed number. Large deviations usually mean some modules were wrapped too large, or some ranks carry extra unsharded state.

    In multimodal settings, compute cost varies widely across encoders. A safer approach is to create a separate wrapping unit for each modality encoder and determine load weights from measured per-step timings offline. Dynamic resharding mid-training is expensive because parameters and optimizer states must be moved again. If dynamic adjustment is truly needed, do it at checkpoint boundaries and run a full memory and loss validation afterward.

    Gradient Synchronization: Overlapping Reduction with Compute

    Backward propagation computes gradients layer by layer, starting from the last layer. As soon as each layer’s gradient is ready, you can launch an asynchronous reduce-scatter and continue computing the next layer’s gradients, overlapping communication with computation.

    There is a common pitfall here. Calling handle.wait() at the end of every layer’s loop blocks until the current reduction completes, preventing overlap with the next layer’s computation. The correct approach is to put outstanding handles into a bounded queue and only wait on the oldest one when the queue is full. The queue length determines how many full gradient buffers stay resident, and thus the extra memory consumed.

    1. import torch
    2. import torch.distributed as dist
    3. MAX_INFLIGHT = 2 # max concurrent outstanding reductions; tune based on memory headroom
    4. def backward_with_overlap(layers, group, world_size):
    5. inflight = [] # elements: (work, full grad buffer, sharded output buffer, layer)
    6. for layer in reversed(layers):
    7. full_grad = layer.compute_full_grad() # illustrative API: full gradient of this layer, length N
    8. shard_out = torch.empty(
    9. full_grad.numel() // world_size,
    10. dtype=full_grad.dtype,
    11. device=full_grad.device,
    12. )
    13. work = dist.reduce_scatter_tensor(
    14. shard_out, full_grad, op=dist.ReduceOp.SUM, group=group, async_op=True
    15. )
    16. inflight.append((work, full_grad, shard_out, layer))
    17. if len(inflight) > MAX_INFLIGHT:
    18. finish_oldest(inflight, world_size)
    19. while inflight:
    20. finish_oldest(inflight, world_size)
    21. def finish_oldest(inflight, world_size):
    22. work, full_grad, shard_out, layer = inflight.pop(0)
    23. work.wait()
    24. shard_out.div_(world_size) # reduce-scatter sums; convert to average here
    25. layer.set_sharded_grad(shard_out) # illustrative API: write back the local sharded gradient
    26. del full_grad # release the full gradient buffer once reduction completes

    The compute_full_grad and set_sharded_grad functions are illustrative interfaces; actual implementations depend on how your modules are organized.

    In multimodal scenarios, backward pass durations differ across modalities. Merging small gradients with similar timings into a single communication buffer reduces the number of small messages; merge thresholds should be determined from measured results. For tail gradients that take unusually long, avoid letting them block the entire queue—place them in a separate, longer window instead.

    Memory Fragmentation: Tune with Monitoring Data

    Frequent weight gathering and release creates significant fragmentation. PyTorch’s CUDA allocator exposes several relevant parameters: expandable_segments reduces fragmentation, and max_split_size_mb limits the maximum size of memory blocks that can be split. If your platform offers similar parameters, follow that platform’s documentation.

    Set max_split_size_mb carefully. Too large a value is effectively no limit—large blocks get split into small pieces and fragmentation becomes hard to control. Too small a value prevents large blocks from being reused, forcing the allocator to frequently reclaim and retry, degrading throughput. While tuning, watch these metrics:

    • The gap between memory_reserved and memory_allocated. A steadily widening gap usually indicates growing fragmentation.
    • num_alloc_retries, the number of retry attempts after allocation failures. A rising value means memory is near its limit.
    • num_ooms, the count of actual out-of-memory events.

    The tuning order: first ensure num_ooms is zero, then reduce fragmentation. Change one parameter at a time and record throughput and peak memory before and after each change.

    Gradient Clipping and Numerical Precision

    One approach—clipping by global norm before reduce-scatter—is flawed. The global norm is the square root of the summed squares of all parameter gradients, but before reduce-scatter, each rank holds only its local portion and cannot compute the global norm.

    The correct approach: after reduce-scatter, each rank computes the squared sum of its own shards, an all-reduce yields the global squared sum, and scaling is applied uniformly.

    1. def clip_global_norm(sharded_grads, max_norm, group):
    2. local_sq = torch.zeros((), device=sharded_grads[0].device, dtype=torch.float32)
    3. for g in sharded_grads:
    4. local_sq += g.float().pow(2).sum()
    5. dist.all_reduce(local_sq, op=dist.ReduceOp.SUM, group=group)
    6. total_norm = local_sq.sqrt()
    7. if total_norm > max_norm:
    8. scale = max_norm / (total_norm + 1e-6)
    9. for g in sharded_grads:
    10. g.mul_(scale)
    11. return total_norm

    The clipping threshold depends on the task and loss scale; 1.0 is only a common starting point and should be validated against training curves.

    BF16 shares FP32’s exponent bits, giving it a wide dynamic range, so it typically does not need loss scaling the way FP16 does. However, it has fewer mantissa bits and accumulates more error, so gradient accumulation and reduction should still use FP32.

    Checkpoints and Resuming from Failures

    Training runs may last weeks, so your checkpointing strategy directly determines how much progress is lost on failure. Each rank should asynchronously save its own parameter and optimizer state shards, along with the current step, RNG states, and data sampler position.

    Save to a temporary directory first, then atomically rename it to the final directory after all files are written. This way, a failure mid-write never leaves behind a checkpoint that looks complete.

    Compute a hash for each shard file and write a manifest. On recovery, verify hashes first; failed shards must not be loaded. Roll back to the last complete checkpoint and preserve the corrupted directory for investigation—do not simply overwrite it.

    Keep the most recent K checkpoints, where K depends on storage capacity and failure frequency. Training progress between the last successful save and the failure is lost, so the save interval should match your acceptable loss.

    Multimodal Input Pipeline

    Tokenization, image resizing, and speech feature extraction should all happen during data loading or in separate worker processes, keeping this work off the training process’s compute time.

    Cross-process shared memory reduces copying but makes lifecycle management error-prone. The creator is responsible for unlinking shared memory objects after all consumers finish. If /dev/shm usage keeps growing during training, some objects are likely not being released.

    The sampling ratio of each modality within a batch shapes the model’s training direction. Initial ratios can follow each modality’s data volume or business goals. During training, monitor each modality’s loss and actual sample share. If one modality’s loss stalls while others keep dropping, check that modality’s data quality and sampling ratio rather than simply training longer.

    How to Interpret Reported Results

    Drafts of this material have cited performance numbers, including startup time compressed from hours to under ten minutes, memory utilization above 90%, cross-node bandwidth utilization above 75%, and a linear scaling ratio of 0.82 at ten-thousand-GPU scale, compared to 0.71 for a ZeRO-3 setup.

    These numbers cannot be independently reproduced. The hardware model, network topology, model configuration, batch size, baseline version, and measurement methodology are not specified, so treat them only as observations from the author’s controlled internal tests—not as benchmarks.

    The linear scaling ratio is defined as: throughput on N GPUs divided by (throughput on N/N₀ GPUs multiplied by N₀), where N₀ is the baseline scale. When comparing two schemes, ensure identical hardware, batch size, and model structure for the baseline.

    Launch Checklist

    Check item Method Pass criterion
    Memory estimation List weights, gradients, and optimizer states by precision Actual per-GPU usage after launch differs within an explainable range
    Device mesh Print each rank’s mesh coordinates and communication groups Ranks on the same node belong to the same communication domain
    Load integrity Count and hash-verify all parameters Parameter count matches config; hashes match the manifest
    Memory balance Compute parameter bytes per rank after initialization Deviation within the team’s accepted tolerance
    Communication overlap Inspect reduction and backward timelines with a profiler Reductions overlap with subsequent layers’ compute
    Gradient clipping Compare global norms between single-GPU and multi-GPU Values match
    Fragmentation and OOM Monitor reserved, allocated, and retry counts num_ooms is zero; fragmentation does not grow steadily
    Checkpoint recovery Run recovery drills periodically Loss curve is continuous across the interruption

    Conclusion

    Large-scale training adaptation can be understood as aligning three groups of objects: model-side parameters and optimizer states, communication-side meshes and communication domains, and hardware-side memory and bandwidth. Every change should map to one of these three groups and be validated against the checklist above.

    FSDP2’s sharding, layered loading, and asynchronous reduction spread memory pressure across many GPUs, but the cost is more communication. Every optimization must be confirmed by measurement—rules of thumb should not be applied blindly.