Adapting Multimodal LLM Training with Fully Sharded Parallelism: An End-to-End Practice

    This article explains how to adapt trillion-parameter-scale multimodal models for training on new accelerator hardware and software stacks. It covers the core memory and communication challenges, how fully sharded data parallelism works, and the key steps across model loading, shard scheduling, multimodal-specific handling, and gradient synchronization. It also lists common failure modes with troubleshooting methods and a staged validation approach.

    1. Background and Problem Definition

    Recently, several open-source multimodal models with parameter counts on the order of a trillion have been adapted for training on China-developed accelerator hardware. The main difficulties in this work fall into three areas: memory capacity, communication overhead, and compute throughput. A single accelerator card cannot hold the full parameters, gradients, and optimizer states, which is the most direct limit. When a vision encoder is added, the input expands from pure text to mixed forms such as interleaved image-text sequences and video frames. The computational characteristics of different modules differ noticeably, and scheduling complexity rises accordingly.

    Migrating a training script that runs in one software and hardware environment to new accelerator hardware and a new software stack usually involves more than replacing operators. The training framework, communication library, memory management strategy, and numerical precision scheme must be adapted together, and each step needs verifiable results.

    2. Fundamentals of Fully Sharded Data Parallelism

    The core idea of fully sharded data parallelism is that each device keeps only its assigned portion of the parameters, gradients, and optimizer states over the long term. Assume there are N devices. The static memory footprint can then drop to roughly 1/N of the full footprint on a single card, plus temporary buffers for the unit currently being computed. This is an approximation. Actual usage also depends on activations, communication buffers, and memory fragmentation.

    Execution happens in two steps. During the forward pass of a unit, the system uses an all-gather operation to temporarily assemble the complete parameters of that unit. Once the computation finishes, the parameters are released immediately and do not stay in memory. During backpropagation, gradients are distributed to each device through a reduce-scatter operation, and each device keeps only the gradients of its own shard.

    This approach trades more communication for lower memory usage. To keep communication from slowing down training, engineers typically prefetch parameters. While unit i is computing, the parameters needed for unit i+1 are gathered in advance, so communication and computation overlap as much as possible.

    3. Four Stages of the Training Pipeline

    (1) Model Loading and Initialization

    Loading has three key points. First, deferred construction: the model structure is first built on a meta device, which allocates no real memory, and parameters are materialized unit by unit afterward. This prevents each process from reserving memory for the full model during initialization. Second, sharded loading: when reading weights from a checkpoint, each process reads only the tensor slices it is responsible for. If every process reads the full weights, memory pressure during startup becomes the main bottleneck. Third, initialization consistency: random seeds must match the sharding rules so that initial values on each device can be aligned item by item with the reference implementation.

    (2) Shard Scheduling

    How shard units are divided directly affects peak memory and the number of communication calls. Transformer layers or vision encoder blocks are common choices for units. If a unit is too large, the parameters gathered temporarily during computation consume more memory, and peak memory rises. If a unit is too small, the number of communication calls grows, and the fixed overhead of each launch accumulates.

    In a multimodal model, the vision and language parts differ in structure and computational density, so each can have its own wrapping granularity. The prefetch depth should also match bandwidth and the computation time of each unit. Prefetching too deep occupies extra buffers, while prefetching too shallow fails to hide communication latency.

    (3) Special Handling for Multimodal Structures

    First, frozen modules. If the vision encoder stays frozen during a training stage, its parameters need no gradients or optimizer states. Exclude it from the sharding plan or handle it separately. Otherwise, it wastes memory and communication bandwidth.

    Second, precision policy. Normalization layers and some projection layers are sensitive to numerical error, so they can keep higher precision, while the other modules use low-precision computation. The precision assignment should be written into the configuration file and checked separately during validation.

    Third, variable-length inputs. The number of image tokens and the text length are often not fixed. At the batch level, padding or packing is required, and the compute load across devices should stay roughly balanced. If one card processes noticeably longer sequences, the other devices wait at the reduction points, and overall throughput is limited by the slowest device.

    (4) Gradient Synchronization and Optimization

    During backpropagation, gradients should be reduce-scattered unit by unit instead of synchronized all at once after the backward pass finishes. This lets communication overlap with the backward computation of later layers.

    Gradient clipping is an error-prone step. The global gradient norm must be aggregated across shards. Each device first computes the sum of squares of its local gradients, then a single global reduction yields the total norm, and finally all gradients are scaled by the same factor. If clipping happens only locally, each device applies a different scaling ratio, parameter updates drift from the single-card results, and the deviation is hard to detect from the loss curve alone.

    Gradient accumulation can enlarge the effective batch size without increasing memory usage. During accumulation, gradient communication usually happens only at the final step, unless the application has special requirements. Optimizer states should also be saved by shard, and checkpoint saving and restoring must be done per shard as well.

    4. Illustrative Code

    The following pseudocode shows the main workflow. The function names are generic descriptions and do not correspond to any specific API.

    1. def build_sharded_model(config, world_size, rank):
    2. with init_on_meta_device(): # Build the model structure only, without allocating device memory
    3. model = build_model(config)
    4. shard_plan = plan_shards(model, world_size) # Assign parameter ownership by compute unit
    5. model = materialize_and_shard(model, shard_plan, rank) # Load unit by unit and keep only the local shard
    6. return model
    7. def train_step(model, batch, optimizer):
    8. for unit in model.units:
    9. full_params = all_gather(unit.local_shard) # Temporarily gather full parameters before the forward pass
    10. hidden = unit.forward(full_params, hidden)
    11. release(full_params) # Release immediately after computation finishes
    12. loss = compute_loss(hidden, batch.labels)
    13. loss.backward() # Reduce-scatter gradients unit by unit during backward
    14. clip_grad_norm_sharded(model, max_norm=1.0) # Aggregate the global norm first, then scale uniformly
    15. optimizer.step() # Each device updates only its local shard

    5. Common Issues and Troubleshooting

    1. Memory usage exceeds expectations. A common cause is that shard units are too large, or activation recomputation is not enabled. To troubleshoot, record the peak memory of each unit, then turn on activation recomputation and compare the results.
    2. Abnormal loss after loading. A common cause is an incorrect weight name mapping, or information loss during precision conversion. To troubleshoot, capture the inputs and outputs of individual layers and compare them item by item with the reference implementation.
    3. Multi-card results differ from single-card results. A common cause is an incorrect gradient clipping scope, or random number generators that are not synchronized. To troubleshoot, fix the seeds and compare gradient norms step by step.
    4. Throughput below expectations. A common cause is that communication does not overlap with computation, or data loading becomes the bottleneck. To troubleshoot, use a performance profiling tool to inspect the timeline and identify idle intervals.
    5. Loss jumps after checkpoint recovery. A common cause is that optimizer states were not restored correctly per shard. To troubleshoot, load a checkpoint immediately after saving it and verify each tensor.

    6. Validation Methods

    Validation should start small and gradually expand in scope.

    Step 1, small-scale alignment. Use a few layers and a small batch size. Compare forward outputs and losses between single-card and multi-card runs to confirm that the sharding logic itself does not introduce deviations.

    Step 2, set numerical tolerances. Errors are unavoidable under mixed-precision computation, so results should not be required to match bit for bit. Set acceptable error ranges based on the precision configuration, and record the locations where errors exceed those ranges.

    Step 3, long-running stability observation. Track loss curves and gradient norms over thousands of steps to confirm there is no unexpected divergence or sudden change.

    Step 4, checkpoint round-trip testing. Run save, load, and continue training in sequence. Confirm that model parameters, optimizer states, and random number generator states are fully restored.

    7. Practical Recommendations

    1. Validate individual modules before running full-pipeline integration. This makes it easier to locate the source of a problem.
    2. Record the sharding strategy, precision policy, and unit partitioning in configuration files so experiments can be reproduced.
    3. Keep baseline results for every change and compare before and after. This prevents multiple modifications from stacking up in a way that makes the cause of a problem impossible to identify.
    4. When memory is insufficient, first adjust the shard unit size or enable activation recomputation. Consider adding more devices after that.