Practices for Sharded Training Pipelines of Ultra-Large Multimodal Models

    As multimodal models scale to trillions of parameters, infrastructure challenges—such as memory constraints, cross-node communication overhead, and training recovery costs—become the primary bottleneck. This article details the engineering practices for training ultra-large models, focusing on model loading, shard scheduling, and gradient synchronization. It provides pseudocode examples and explores specific considerations for multimodal training, hardware adaptation, and a validation checklist for stable deployment.

    Introduction: Infrastructure Challenges Brought by Parameter Scaling

    Recently, the industry open-sourced a flagship multimodal model with 2.8 trillion parameters. As model sizes expand, training challenges have shifted from algorithm design to infrastructure. The memory of a single accelerator cannot hold the complete model, cross-node communication overhead rises rapidly with cluster size, and recovery costs after interruptions increase significantly. Ensuring that ultra-large models run stably and efficiently on computing clusters is the primary concern for training engineering teams.

    Using a typical training adaptation process as a guide, this article explains the design principles of the ultra-large model training pipeline, focusing on model loading, shard scheduling, and gradient synchronization. The code snippets are illustrative pseudocode for explaining the process and do not correspond to any specific framework or API.

    1. Core Constraints in Ultra-Large Model Training

    When training ultra-large models, engineering teams typically face three types of constraints simultaneously.

    1. Memory Constraints

    Model parameters, gradients, and optimizer states all consume memory. Taking half-precision storage as an example, each parameter occupies 2 bytes. The weights of a 2.8 trillion parameter model alone require about 5.6 TB of memory, far exceeding the capacity of a single accelerator. Optimizer states (such as first-order and second-order momentums) further increase the total consumption, usually several times the parameters themselves.

    2. Communication Constraints

    Data parallelism, tensor parallelism, and pipeline parallelism all require data exchange between devices. The communication volume is directly related to the number of devices, model structure, and sharding method. If communication cannot overlap with computation, devices will spend a lot of time waiting for data, reducing actual utilization.

    3. Stability Constraints

    Ultra-large training tasks run for long periods, and any single point of failure can interrupt the entire task. Numerical overflow, individual device slowdowns, or checkpoint corruption can all cause wasted computing power. Therefore, the training pipeline needs observability, recoverability, and reproducibility.

    These three constraints affect each other. Increasing communication to save memory may slow down training speed. Enlarging batch size to improve throughput may exacerbate memory pressure. A good solution requires a balance among the three.

    2. Basic Principles of Fully Sharded Data Parallelism

    Fully Sharded Data Parallelism (FSDP) is a common approach to address memory constraints. Its core idea: each device only holds a fraction of the model states—1/N of parameters, gradients, and optimizer states, where N is the number of participating devices. During computation, the required parts are temporarily gathered on demand.

    2.1 Forward and Backward Processes

    Phase Operation Purpose
    Forward computation All-gather current layer parameters Each device obtains complete weights for the current layer
    Forward computation Release non-local shards after computation Control peak memory
    Backward computation All-gather parameters, compute local gradients Obtain gradients for the current layer
    Backward computation Reduce-scatter gradients Each device keeps only its responsible gradient shard
    Optimizer update Update parameters and states on local shards No need to save complete optimizer states

    With this approach, the model state memory on each device is roughly reduced to 1/N of the complete model, at the cost of increased communication for parameter gathering and gradient reduction.

    2.2 Choice of Communication Primitives

    To understand the training pipeline, it is necessary to clarify the semantics of three collective communication operations:

    • All-gather: Each device sends its shard to others, eventually obtaining the complete tensor.
    • Reduce-scatter: First sum the same tensor across all devices, then split the result, allowing each device to receive its portion.
    • All-reduce: All devices receive the same sum result, commonly used for synchronizing scalar metrics (e.g., gradient norm).

    3. Training Pipeline Breakdown

    3.1 Model Loading: Avoiding OOM at Initialization

    Ultra-large models cannot be fully built on a single device before sharding, or an OOM error will occur during the loading phase. A common approach involves two steps.

    The first step is lazy initialization. The model structure is first built on a “meta device,” recording only tensor shapes and types without allocating actual storage.

    The second step is streaming loading. Checkpoints are saved per shard; each device reads only its responsible part and writes directly to the corresponding memory location.

    1. # Pseudocode: Lazy construction and shard-based loading
    2. def build_sharded_model(config, world_size, rank, ckpt_dir):
    3. with meta_device(): # Build structure only, no memory allocation
    4. model = build_model_structure(config)
    5. shard_plan = plan_shards(model, world_size) # Determine which device is responsible for each parameter
    6. for name, tensor_meta in shard_plan.local_tensors(rank):
    7. shard = read_checkpoint_slice(ckpt_dir, name, rank, world_size)
    8. materialize(model, name, shard) # Allocate actual storage only on this device
    9. return model

    Checkpoints must also support resharding. When the number of devices changes, the system must be able to reorganize old shards into a new sharding plan. If the checkpoint format is bound to the device count, scaling becomes difficult.

    3.2 Shard Scheduling: Granularity and Overlap

    Shard scheduling determines when parameters are gathered, directly affecting peak memory and communication efficiency.

    Wrapping Granularity

    The sharding unit is typically a model block, such as an attention layer plus a feed-forward layer. If the granularity is too fine, there will be too many communication calls, and the fixed overhead of small messages will dominate. If too coarse, a single gather of too many parameters will increase peak memory. In practice, a trade-off must be made based on available memory and network bandwidth.

    Communication and Computation Overlap

    While computing the previous model block, the parameter gather for the next module can be initiated in advance. This prefetching operation hides communication behind computation.

    1. # Pseudocode: Prefetch next layer parameters, overlapping with current layer computation
    2. def forward_with_prefetch(blocks, x):
    3. handle = async_all_gather(blocks[0].shard)
    4. for i, block in enumerate(blocks):
    5. full_params = wait(handle)
    6. if i + 1 < len(blocks):
    7. handle = async_all_gather(blocks[i + 1].shard) # Initiate in advance
    8. x = block.compute(x, full_params)
    9. release(full_params) # Release non-local shards
    10. return x

    Load Balancing

    The parameter volume of different blocks can vary greatly. If the sharding plan only allocates by layer count, some devices may bear more communication and storage. Allocation should comprehensively consider both parameter volume and computation volume.

    3.3 Gradient Synchronization and Numerical Stability

    Gradient synchronization is the most problematic phase in the training pipeline.

    Gradient Bucketing

    Backpropagation generates many small gradients. Initiating a reduction for each small gradient individually is highly inefficient. Training systems usually merge multiple gradients into a bucket and perform a unified reduction when a threshold is reached. The bucket size should be determined empirically.

    Mixed Precision

    Forward and backward passes can use low-precision computation while retaining a high-precision master copy of parameters for optimizer updates. Using half-precision (fp16) requires loss scaling to prevent gradient underflow. Using bf16 generally does not require loss scaling because its exponent bits match single precision.

    Global Gradient Clipping

    Gradient clipping requires the global gradient norm. Since gradients are sharded, each device can only compute the local sum of squares first, then aggregate it into a scalar via all-reduce.

    1. # Pseudocode: Global gradient norm clipping in a sharded environment
    2. def clip_grad_norm_sharded(shards, max_norm):
    3. local_sq = sum(float(g.square().sum()) for g in shards)
    4. total_sq = all_reduce_scalar(local_sq) # All-reduce to get global sum of squares
    5. total_norm = total_sq ** 0.5
    6. if total_norm > max_norm:
    7. scale = max_norm / (total_norm + 1e-6)
    8. for g in shards:
    9. g.mul_(scale)
    10. return total_norm

    If the global aggregation is omitted, each device will clip based on the local norm, causing inconsistent scaling ratios across shards and deviating training results from expectations.

    4. Additional Issues in Multimodal Training

    Multimodal models typically consist of a vision encoder, a feature projection module, and a language backbone. These modules differ significantly in structure and computation characteristics, requiring tailored training pipeline designs.

    1. Module-specific Sharding Strategies

    The layer structure of the vision encoder differs from the language backbone, and their parameter volumes and activation sizes vary. A unified wrapping strategy may result in overly fine sharding for some modules and overly coarse for others. A safer approach is to set the sharding granularity separately for each module.

    2. Variable Input Lengths

    The number of visual tokens generated by encoding images and videos is variable. Padding to the longest sample wastes significant computation. If not padded, the computation volume across devices will be inconsistent. Common practices include bucketing by length or using sample packing, while considering the actual computation volume of each device during scheduling.

    3. Handling Frozen Modules

    In certain training phases, some modules may be frozen. Frozen modules do not need to store gradients and optimizer states; the sharding plan should exclude these to avoid wasting memory and increasing invalid communication.

    4. Adequate Data Supply

    The decoding and preprocessing overhead of multimodal data is significant. If the data loading speed cannot keep up with the computation speed, devices will idle. The training pipeline needs to configure sufficient parallelism and prefetch buffers for data loading.

    5. Focus Areas for Hardware Adaptation

    Migrating the training pipeline to new accelerator hardware usually requires attention to the following aspects:

    • Operator Coverage: High-frequency operators like attention computation, normalization, and activation functions need efficient implementations. For unsupported operators, a fallback path must be defined, and the performance loss evaluated.
    • Collective Communication Correctness and Bandwidth: It is necessary to verify whether intra-node and cross-node communication bandwidth meets expectations and to check if reduction results are consistent across different topologies.
    • Memory Management: During long training runs, memory fragmentation accumulates. Activation recomputation can trade extra computation for memory; whether to enable it depends on the actual bottleneck.
    • Numerical Consistency: First align forward outputs on a small-scale model, then align the loss curve over several steps, and scale up only after confirming there are no errors.

    6. Validation and Troubleshooting Checklist

    Before bringing the training pipeline online, it is recommended to verify the following items in order:

    1. Forward Consistency: Fix the random seed and compare the output difference between the sharded model and the unsharded reference model.
    2. Loss Curve Alignment: Compare the loss changes over the first few hundred steps under the same data and seed.
    3. Checkpoint Round-trip Test: Save a checkpoint and immediately restore it to ensure parameters and optimizer states are consistent; then change the number of devices to verify resharding correctness.
    4. Performance Profiling: Record the computation time, communication time, and memory peak per step to identify which phase is the bottleneck.
    5. Fault Drill: Artificially introduce a single slow node or a single interruption to check if the task can detect it and recover from the latest checkpoint.