Training Multimodal Large Models: Sharding, Gradient Synchronization, and Checkpoint Recovery

    A practical guide to adapting multimodal large model training for multi-GPU clusters. This article covers FSDP-style sharding, memory estimation for optimizer states, model loading on meta devices, gradient synchronization with global norm computation, multimodal-specific challenges like mixed freezing and uneven sequence lengths, and how to validate correctness and recovery with checkpoints.

    Training Multimodal Large Models: Sharding, Gradient Synchronization, and Checkpoint Recovery

    1. Background: Training Challenges of Ultra-Large Multimodal Models

    Multimodal large models process text, images, and other input types simultaneously, with parameter counts often reaching hundreds of billions or even trillions. Since the memory of a single accelerator card is far smaller than the total training state required, training must rely on multi-card coordination.

    Take AdamW with mixed-precision training as an example. Assuming optimizer states and the high-precision master weights are stored in fp32, each parameter occupies roughly 16 bytes: 2 bytes each for the low-precision weights and gradients, plus 4 bytes each for the first moment, second moment, and fp32 master weights. This figure changes with SGD or other precision strategies and should be re-estimated based on the actual configuration. By this estimate, a 100-billion-parameter model carries about 1.6 TB of training state—far beyond the capacity of a single card.

    The first question in training adaptation is therefore how to shard this state across multiple cards while keeping results consistent with single-card training.

    2. Adaptation Goals and the End-to-End Pipeline

    The core goals of adaptation can be summarized in three points:

    1. Correctness: The loss curves and gradients from multi-card training should match a reference implementation within numerical tolerance.
    2. Scalability: As the number of cards increases, per-card memory usage should decrease, and training throughput should scale close to linearly.
    3. Recoverability: Training should resume from checkpoints after interruptions, with model parameters, optimizer states, and data progress kept consistent.

    The full pipeline can be broken into six stages: model loading and initialization, parameter sharding, parameter aggregation during forward passes, backward computation, gradient synchronization with optimizer updates, and checkpoint saving and recovery. Any of these stages can become a source of performance or correctness issues. The table below lists typical risks and verification methods for each stage.

    Stage Typical Risks Verification
    Model loading and initialization Sharding plan mismatched with weight files; wrong shapes or dtypes Compare shapes, dtypes, and value ranges layer by layer
    Parameter sharding Sharding plan inconsistent with checkpoint layout Compare aggregated parameters against the reference, item by item
    Forward parameter aggregation Peak memory exceeding expectations; prefetch failing to overlap with computation Log per-layer peak memory and communication wait time
    Backward computation Temporary full gradients not released in time Observe the memory curve during the backward phase
    Gradient synchronization and optimizer updates Incorrect process groups; gradients reduced twice or missed Fix data and random seeds, compare gradient norms
    Checkpoint saving and recovery Data progress or random states inconsistent after recovery Compare losses over subsequent steps after interruption and recovery

    3. How Fully Sharded Data Parallelism Works

    Traditional data parallelism keeps a full model replica on every card, resulting in low memory efficiency. Fully Sharded Data Parallelism (referred to below as the FSDP approach) shards parameters, gradients, and optimizer states across all cards in a shard group, with each card holding only one segment.

    When computing a given layer, each card temporarily retrieves the layer’s full parameters via all_gather. Once that layer’s computation finishes, non-local shards are released immediately, so peak memory only includes the current layer.

    During backpropagation, each card produces a temporary full gradient for the layer. reduce_scatter then sums gradients across cards and splits the result back into the shard each card owns. After reduce_scatter completes, temporary full gradients should be released immediately, leaving each card with only its local gradient shard.

    The following illustrative code shows the execution order and tensor shapes:

    1. # Illustrative pseudocode showing execution order and tensor shapes
    2. # shard_params[layer_idx]: local shard, shape [N/W, ...]
    3. # full_params: aggregated full parameters, shape [N, ...]
    4. # pg: process group for the shard group; W is the number of cards in the group
    5. def forward_layer(layer_idx, shard_params, x, pg):
    6. full_params = all_gather(shard_params[layer_idx], group=pg) # [N/W, ...] -> [N, ...]
    7. y = compute(full_params, x)
    8. del full_params # release non-local shards
    9. return y
    10. def backward_layer(layer_idx, grad_full, pg):
    11. # grad_full: temporary full gradient from backward, shape [N, ...]
    12. grad_shard = reduce_scatter(grad_full, group=pg) # [N, ...] -> [N/W, ...]
    13. del grad_full # release temporary full gradients immediately
    14. return grad_shard

    In real implementations, the next layer’s parameters also need to be prefetched. If parameter aggregation cannot overlap with the current layer’s computation, communication waits will directly drag down overall throughput.

    With a hybrid sharding strategy that replicates across nodes, an additional all_reduce across replica groups is required after reduce_scatter within the shard group. The division of process groups must be determined before startup; otherwise, the reduction scope will be wrong.

    4. What Makes Multimodal Training Different

    Multimodal models typically consist of a vision encoder, a modality projection module, and a language model backbone. These three module types differ in parameter scale, compute density, and freezing strategy, so configurations designed for text-only models often do not work as-is.

    • Sharding unit granularity: Sharding the entire model as one unit makes each aggregation too large and raises peak memory. A better approach is to define sharding units at Transformer layer or module boundaries.
    • Mixed freezing strategies: The vision encoder may be frozen in some training phases. Frozen parameters must satisfy three conditions: requires_grad set to False, excluded from optimizer parameter groups, and excluded from gradient reduction. Otherwise, you get wasted communication or unnecessary optimizer state memory.
    • Uneven input lengths: The number of image tokens varies with resolution, so sequence lengths differ significantly across samples. When per-card load is imbalanced, synchronization points wait for the slowest card. Length-based bucketing can mitigate this, but padding and loss normalization must be consistent across cards within the same batch. Dynamic batching requires the same constraints.
    • Data pipeline: Multimodal samples involve image-text decoding and alignment. If data loading becomes the bottleneck, accelerators sit idle waiting for data. Prefetching and multi-process decoding are common remedies, and you should continuously monitor GPU idle rate—the fraction of time between steps during which the GPU is idle.

    Before launch, verify the following checkpoints:

    • Frozen modules have requires_grad set to False and are not in optimizer parameter groups.
    • After bucketing, padding and loss normalization are consistent across cards for every batch.
    • GPU idle rate stays stable throughout the target training phase. If idle rate is clearly above baseline, investigate the data pipeline first.

    5. Model Loading and Initialization

    Ultra-large models cannot be fully instantiated in a single process. The common approach is to build the model structure on the meta device—allocating no real memory—then load weights layer by layer according to the sharding plan.

    Before loading, confirm the following prerequisites:

    • The sharding plan must match the checkpoint’s sharded state dict layout, including how optimizer states are sharded. A layout mismatch may throw shape errors—or, more insidiously, silently place weights in the wrong locations.
    • rank, world_size, and process groups should be injected by the launcher (e.g., torchrun or a cluster scheduler), not hardcoded.
    • When broadcasting weights from a single file, all processes must use a uniform dtype and the same random seed for initializing unloaded parameters.
    • New checkpoints should be written to a separate directory and must never overwrite old ones. If a write is interrupted, overwriting corrupts both the old and new data.

    The steps are as follows:

    1. Build an empty model shell and record each layer’s shape and dtype.
    2. Following the sharding plan, each process reads only the weight slices it owns.
    3. For parameters requiring random initialization, initialize them after sharding, keeping seed settings consistent with the reference implementation.
    4. After loading, run a forward pass to verify shapes, dtypes, and value ranges.

    Illustrative code:

    1. def load_sharded_model(config, ckpt_dir, rank, world_size):
    2. model = build_model_on_meta(config) # no real memory allocated
    3. plan = make_shard_plan(model, world_size) # generate the sharding plan; must match the checkpoint layout
    4. for name, spec in plan.items():
    5. if spec.owner != rank:
    6. continue
    7. tensor = read_slice(ckpt_dir, name, spec.slice)
    8. materialize(model, name, tensor.to(spec.dtype))
    9. return model

    Weight reading also needs planning. If all processes read the same large file simultaneously, storage bandwidth becomes the bottleneck. You can split weight files by shard, or have a few processes read and broadcast to the rest.

    6. Gradient Synchronization and Communication Optimization

    Gradient synchronization is the dominant communication overhead in multi-card training. The following optimizations are commonly used:

    • Communication-computation overlap: As soon as backward computation finishes for a layer, immediately start reducing that layer’s gradients so communication runs in parallel with computation for subsequent layers.
    • Communication bucketing: Combine multiple small tensors into larger communication buckets to reduce per-communication launch overhead. Bucket size requires trade-offs: small buckets have high launch overhead, while large buckets consume more temporary memory. Tune via benchmarks per layer or device rather than relying on defaults.

    Computing the Global Gradient Norm

    After sharding, each card holds only part of the gradients, so the norm cannot be computed from local gradients alone. The correct procedure is:

    1. Compute the sum of squares of the local shard in fp32 on each card.
    2. all_reduce (SUM) the sums of squares across all cards to get the global sum of squares.
    3. Take the square root of the global sum of squares to get the global gradient norm.
    4. Compute the clipping coefficient from the global norm and scale each card’s local gradients.

    Parameters replicated across all cards (such as some LayerNorm weights) must be counted only once; otherwise, the sum of squares is double-counted.

    Illustrative code:

    1. def global_grad_norm(grad_shards, replicated_flags, rank_in_group, pg):
    2. # grad_shards: local gradient shards, accumulated in fp32
    3. # replicated_flags: marks parameters replicated across all cards
    4. local_sq = torch.zeros((), dtype=torch.float32, device=grad_shards[0].device)
    5. for g, replicated in zip(grad_shards, replicated_flags):
    6. if replicated and rank_in_group != 0:
    7. continue # replicated parameters counted by one card only
    8. local_sq += g.float().pow(2).sum()
    9. all_reduce(local_sq, op=SUM, group=pg)
    10. return local_sq.sqrt()

    With mixed precision, overflow must also be handled. If any card’s gradient contains inf or nan, the update should be skipped globally and the loss scale adjusted in sync. Judging overflow on a single card only will cause the states of different cards to diverge.

    7. Common Issues and Verification Methods

    Troubleshooting Checklist

    The table below lists five common problem categories, what to check, and pass criteria.

    Problem Checks Pass Criteria
    OOM Does peak memory grow with layer count; are temporary full parameters or gradients left behind; is activation recomputation enabled Peak memory includes only the current layer’s full parameters and activations
    Loss diverges or mismatches the reference Compare early losses with fixed seeds; check the global gradient norm; confirm frozen parameters are not updated; confirm data order and loss normalization match With the same data, relative error of early losses versus the reference implementation falls within precision tolerance, with thresholds set per model and precision
    Communication hang Are world_size and process groups consistent across ranks; does any rank skip collectives because some parameters have no gradients; is the batch count the same on all ranks All ranks execute the same number of collective operations, with no timeouts
    Throughput drop Is communication overlapped with computation; is bucket size appropriate; is GPU idle rate rising; is synchronization waiting caused by uneven lengths Throughput scales near-linearly with card count; idle rate stays stable
    Data progress inconsistent after recovery Does the checkpoint include sampler state, RNG state, and optimizer state; does the first batch after recovery match the pre-interruption batch Post-recovery losses over several steps match the uninterrupted training curve

    Verifying Multi-Card Training Correctness

    Since the full model usually cannot fit on a single card, validation can use a smaller configuration with identical structure, keeping the sharding logic consistent with the production configuration. The steps are:

    1. Fix random seeds, disable stochastic operators like dropout, and use the same data order.
    2. Run the first N steps on the reference configuration, recording loss, global gradient norms, and checksums of selected parameters.
    3. Run the same configuration on multiple cards and compare these metrics step by step.
    4. After passing, save a checkpoint mid-training, interrupt and resume, and verify that post-recovery metrics match the uninterrupted run.

    8. FAQ

    What is the difference between FSDP and ZeRO-3?

    The two are conceptually similar: both shard parameters, gradients, and optimizer states across cards. The differences mainly lie in implementation and configuration. FSDP is built into PyTorch and wraps modules to control the sharding strategy. ZeRO-3 is provided by DeepSpeed and is configured primarily through config files that control sharding, prefetching, and communication bucket sizes. Specific parameter names and default behaviors change across versions, so consult the documentation for the version you use when making a choice.

    How do I verify the correctness of multi-card training?

    Follow the verification steps in Section 7. The key is to use the same data and random seeds, compare losses and gradient norms, and check whether the loss curve remains continuous after interruption and recovery.