Sharding Scheduling and Gradient Synchronization in Multimodal Large Model Training
Training trillion-parameter multimodal models requires balancing memory, communication, and computation. This article explores how Fully Sharded Data Parallel (FSDP) addresses these challenges by partitioning model states across multiple compute cards. It breaks down the training pipeline into five key stages—model loading, sharding scheduling, multimodal input handling, gradient synchronization, and checkpointing—and provides practical troubleshooting and engineering best practices for building stable, large-scale distributed training systems.
Introduction
When model parameter scales reach the trillion level, a single compute card can no longer hold the entire model. Multimodal models must simultaneously process heterogeneous inputs such as images, videos, and text, leading to significant differences in compute density and memory footprint across different modules. The training system must strike a balance between memory, communication, and computation; otherwise, training efficiency and stability will be noticeably impacted.
The open-source community has already seen several large models successfully adapt to multimodal training. A common thread in these practices is splitting the model state across multiple cards, aggregating parameters on demand, and ensuring numerical consistency in gradient synchronization and optimizer updates. This article will use this approach as the main thread to discuss the design choices at each stage of the training pipeline.
1. Main Challenges in Large-Scale Multimodal Training
1. High Memory Pressure. Taking the commonly used mixed-precision Adam optimizer as an example, each parameter requires half-precision parameters, half-precision gradients, single-precision master parameters, and the optimizer’s first and second moments. This totals about 16 bytes per parameter. At a trillion-parameter scale, the model state alone requires about 16 TB of memory, far exceeding single-card capacity.
2. Heterogeneous Module Structures. Multimodal models typically consist of a vision encoder, a projection layer, and a language decoder. The layer structure of the vision encoder differs from that of the decoder, and the sequence lengths during forward computation also vary. Using a uniform sharding granularity for all modules can easily lead to excessive communication overhead or long idle times on certain cards.
3. Rising Communication Overhead. After parameter sharding, both forward and backward computations require additional collective communication. If communication cannot be overlapped with computation, training throughput will drop significantly.
4. High Checkpointing and Fault Tolerance Requirements. Node failures are inevitable during long training runs. Checkpoints must be saved and restored by shard, ensuring that the training state remains consistent with its pre-failure state.
2. Basic Principles of Fully Sharded Data Parallel
Fully Sharded Data Parallel (FSDP, referred to as sharded parallelism below) is a common solution to address memory pressure. It splits the parameters, gradients, and optimizer states on each card into several parts, with each card holding only its responsible portion.
The workflow can be summarized in three steps:
- Forward Phase: Before computing a specific module, an all-gather operation is used to temporarily fetch the complete parameters of that module. Once computation is done, non-local shards are immediately released to control peak memory.
- Backward Phase: Parameters are similarly gathered on demand to compute gradients. A reduce-scatter operation then sums the gradients across cards and scatters them back to local shards.
- Optimizer Phase: Each card only updates the shards it holds. Optimizer states are also sharded, eliminating redundancy.
Compared to traditional data parallelism, the memory footprint of sharded parallelism decreases linearly as the number of cards increases. The trade-off is an increase in communication volume, meaning sharding granularity and communication scheduling directly dictate performance.
3. Five Key Stages in the Training Pipeline
3.1 Model Loading: Avoiding Loading the Entire Model on a Single Card
Large model initialization should first build the structure on a “meta device” without allocating actual storage, only recording tensor shapes. Subsequently, weights are loaded shard by shard and immediately split across the corresponding cards.
This approach prevents single-card out-of-memory (OOM) errors during the startup phase. Weight loading should use streaming reads, processing only one shard unit at a time and releasing the temporary buffer once read.
3.2 Sharding Scheduling: Rationally Dividing Shard Units
The granularity of the shard unit is a critical parameter. If too fine, communication frequency increases, driving up startup overhead and latency. If too coarse, the memory peak from a single aggregation becomes too high.
In practice, a Transformer layer block is typically used as the base unit, merging adjacent small modules. Additionally, parameter prefetching should be enabled: while computing layer N, asynchronously pull the parameters for layer N+1 to overlap communication with computation.
3.3 Multimodal Input Paths: Defining Sharding Strategies by Module
The vision encoder and language decoder should be managed in separate groups. Both parts can use different sharding granularities, or the vision encoder can use a lower degree of sharding to reduce small-scale internal communication.
Preprocessing of multimodal inputs must also coordinate with the training pipeline. Because image and text sample lengths vary greatly, data should be bucketed by length to avoid wasting compute power on excessive padding within the same batch. The output dimension of the projection layer must strictly align with the decoder’s hidden dimension, otherwise, it will cause direct errors during the forward phase.
3.4 Gradient Synchronization and Optimizer Update
After backpropagation, gradients are distributed across cards. The reduce-scatter operation completes the summation and splitting, allowing each card to obtain the global gradient for its own shard.
Special attention must be paid to gradient clipping. Clipping relies on the global gradient norm, but each card only holds a portion of the gradient. The correct approach is to first compute the sum of squares locally, then obtain the total norm via a global reduce operation, and finally scale uniformly. If each card computes its own norm, the clipping results will be inconsistent, leading to training divergence.
In mixed-precision training, gradients may overflow or underflow. This should be handled with dynamic loss scaling, checking for infinity or NaN values in the gradients before each update.
3.5 Checkpoint Saving and Recovery
Checkpoints in sharded training should be saved by shard, rather than first being aggregated to a single card and written to disk. Each card writes its own shard file and records the shard mapping. This ensures fast saving speeds and avoids single-point memory pressure.
During recovery, it is necessary to verify whether the number of cards, sharding strategy, and data parallel groups match those at the time of saving. If the card count has changed, shard remapping must be performed first. After recovery, the loss values of the initial steps should be compared to ensure continuity with the pre-failure curve.
4. Pseudocode Example
The following code illustrates the structure of the training pipeline. The function names are generic abstractions and do not correspond to any specific framework’s API; actual implementation should be adjusted based on the training system used.
# Illustrative: Main pipeline of sharded training# 1. Build the model structure on a meta device, consuming no actual memorymodel = build_model(device="meta")# 2. Divide shard units by layer block, managing vision and language parts in separate groupsshard_units = group_by_block(model,blocks=["vision_encoder", "decoder_layer"],)# 3. Load weights unit by unit and shard them across cardsfor unit in shard_units:materialize_and_shard(unit, world_size, rank)# 4. Training loopfor batch in length_bucketed_loader(dataset):# Forward: gather parameters of the current module on demandloss = forward_with_gather(model, batch)# Backward: compute gradients and reduce-scatter to cardsscaled_loss = scaler.scale(loss)scaled_loss.backward()# Calculate global gradient norm across shards and clip uniformlyglobal_norm = sharded_grad_norm(model)clip_grads(model, global_norm, max_norm)# Optimizer only updates local shardsscaler.step(optimizer)scaler.update()optimizer.zero_grad()
5. Common Issues and Troubleshooting Strategies
Memory peak exceeds expectations. This is usually caused by sharding units being too large or prefetch depth being too high. You can reduce the unit granularity or decrease the prefetch amount from multiple units to a single unit, then observe peak changes.
Communication ratio is too high. First, use profiling tools to confirm the overlap between communication and computation. If overlap is insufficient, adjust the sharding granularity or merge small modules to reduce the number of communications.
Loss does not converge or suddenly diverges. Prioritize checking whether the global norm for gradient clipping is correct, and then check if mixed-precision loss scaling is in effect. Errors in either will lead to training instability.
Loss jumps after recovery. A common cause is that the data reading position, random seeds, or learning rate scheduler state were not restored together. After recovery, compare the values of the previous few hundred steps and verify them item by item.
6. Engineering Best Practices
- Validate at a small scale first. Run the complete pipeline on a few cards to ensure forward pass, backward pass, gradient clipping, and checkpoint recovery are correct before scaling up to full capacity.
- Establish monitoring metrics. Track at least per-card memory usage, step time, communication time, throughput, and loss curves. When metrics are abnormal, you can quickly locate which stage has the issue.
- Fix reproducible configurations. Sharding strategies, data parallel groups, random seeds, and mixed-precision parameters should all be written into config files and placed under version control to facilitate reproduction and rollback.
- Prepare for failures. Save sharded checkpoints at fixed step intervals and regularly rehearse the recovery process to ensure training can be restored within an acceptable timeframe during node failures.
Conclusion
Adapting training for multimodal large models is essentially a trade-off between memory, communication, and computation. Sharded parallelism provides the foundational framework, but sharding granularity, communication scheduling, gradient synchronization, and checkpoint design determine the final outcome. Checking the stages outlined in this article item by item allows for quick problem localization and keeps the training system stable as the scale expands.
