Engineering Practices for Trillion-Parameter Multimodal Model Training Adaptation on AI Accelerators
This article explains how to adapt a trillion-parameter multimodal model for training on domestic AI accelerators. It covers memory budgeting, operator coverage and fallback strategies, mixed-precision stability, native full-shard data parallelism, hybrid parallel orchestration, and long-running training operations. The goal is to show how model profiling, software-stack adaptation, and cluster-level engineering can turn a one-off training adaptation into reusable infrastructure.
1. Why Trillion-Parameter Multimodal Models Are Hard to Adapt
Recently, a domestic AI team open-sourced a multimodal flagship model with about 2.8 trillion parameters. A domestic AI accelerator vendor completed training adaptation for this model using its flagship training-and-inference integrated AI compute card and a proprietary software stack. The work established a native full-shard data-parallel multimodal training path, covering the complete chain from model loading and shard scheduling to gradient synchronization.
In announcement terms, “adaptation completed” and “the pipeline is connected” are only a conclusion. In engineering terms, it means at least four major thresholds have been crossed one by one:
- Memory threshold: Even when weights are stored in BF16, a trillion-parameter model requires nearly 5.6 TB for weights alone. Once gradients, optimizer states, and activations are added, neither a single server nor, in many cases, a single node can accommodate the full model.
- Operator threshold: A multimodal model includes an image encoder, a text backbone, cross-modal fusion modules, and generation heads. Mixture-of-Experts (MoE) layers also introduce non-standard operators such as routing, dispatch, and aggregation. The operator library of domestic hardware may not cover all of them.
- Parallelism threshold: Data parallelism, tensor parallelism, pipeline parallelism, and expert parallelism must work together. The number of possible combinations of communication primitives grows exponentially as parallelism dimensions increase.
- Stability threshold: Trillion-parameter training often lasts for tens of days. A single accelerator failure or a brief network fluctuation can interrupt training and force a costly restart.
Therefore, “training adaptation” is essentially the process of aligning the model, parallel strategy, hardware and software stack, and cluster operations into a sustainable system.
2. The First Step: Profile the Model and Account for Memory
Adaptation should begin with model structure analysis and resource accounting, rather than directly writing training scripts.
2.1 Analyze the Parameter Composition
It is necessary to distinguish three types of parameters: dense-layer parameters, expert-layer parameters, and modality-encoder parameters.
In an MoE structure, expert layers often account for a much larger share of parameters than dense layers, but only a small number of experts are activated for each token. Therefore, two metrics should be tracked separately:
- Total parameter count: determines memory and storage scale.
- Activated parameter count per token: determines compute demand.
2.2 Build a Memory Budget Model
For mixed-precision training, per-accelerator memory demand can be roughly estimated as follows:
Per-accelerator memory ≈ (parameter count × bytes per parameter) / number of shards+ activation memory+ communication buffers+ framework and memory-pool overheadwhere bytes per parameter ≈ BF16 weights (2)+ BF16 gradients (2)+ FP32 master weights (4)+ first-order momentum (4)+ second-order momentum (4)= 16
For a 2.8-trillion-parameter model trained with BF16 mixed precision, parameters, gradients, and optimizer states alone require about 44.8 TB of memory.
If the total memory capacity of the cluster is several times this number, additional headroom must be reserved for activations, communication buffers, and memory fragmentation. Only after this accounting can the required parallelism scale be derived.
2.3 Clarify Adaptation Priorities
The recommended order is:
- First ensure that the model can be loaded correctly and that a single forward and backward step can run.
- Then enable parallel strategies step by step.
- Finally, perform performance tuning.
Investing too early in performance optimization often leads to repeated rework when structural problems remain unsolved.
3. Software Stack Adaptation: Make Operators Run First, Then Make Them Fast
Domestic AI accelerator vendors usually provide a proprietary software stack that includes drivers, runtimes, communication libraries, and operator libraries. The core of adaptation is to complete missing operators and enable distributed training to start normally.
3.1 Operator Coverage Audit and Fallback Plans
The first step is to compare the operators in the model computation graph with those in the hardware operator library and produce a coverage list.
For operators that are not covered, fallback options can be selected from low cost to high cost:
| Option | Approach | Applicable scenarios |
|---|---|---|
| Graph rewriting | Replace the operator with an equivalent combination of supported operators | Simple substitutions that are mathematically equivalent |
| Composite implementation | Use basic operators to compose a complex operation | Fused operators and reduction operators |
| Custom operator | Write and register a high-performance kernel for the hardware | High-frequency, memory-intensive core operators |
| Host fallback | Offload part of the computation to the CPU | Very low-frequency, non-critical-path operators |
In MoE, routing and dispatch usually impose high demands on memory-access efficiency. Custom operators or communication-computation fusion should be prioritized.
For multimodal structures, steps such as image preprocessing and positional encoding generation can be moved to the host side or completed in advance during the loading stage.
3.2 Operator Correctness Verification
Custom operators must pass layer-by-layer alignment validation:
- Run the same weights and inputs through the reference implementation and the hardware implementation.
- Compare forward outputs and backward gradients layer by layer.
It is recommended to build an automated comparison test suite covering multiple shapes and data types. This helps prevent rare cases from surfacing only in the middle or late stages of training.
3.3 Mixed Precision and Numerical Stability
The gradient distribution of a trillion-parameter model has a wide dynamic range. Pure BF16 training can easily cause gradient underflow or activation overflow.
Common practices include:
- Use BF16 for forward and backward computation.
- Use FP32 for master weights, gradient accumulation, and optimizer states.
- Raise loss computation and some reduction operations to FP32.
- Perform the norm calculation for gradient clipping in FP32 to avoid overflow that could make clipping ineffective.
4. Native Full-Shard Parallelism: One Path from Loading to Scheduling and Gradient Synchronization
4.1 From Manual ZeRO-Style Sharding to Native Full Sharding
Early implementations of full-shard data parallelism often required developers to manually manage the timing of parameter sharding, gradient reduction, and parameter aggregation. This approach was highly invasive and error-prone.
A second-generation native full-shard parallelism approach changes the situation:
- Shard by parameter: Each parameter tensor of the model is directly sharded, so developers no longer need to maintain manual sharding views.
- Unified forward and backward interface: Model code remains almost identical to single-card training code, while parallel logic is handled by the wrapper layer.
- Native compatibility with distributed checkpoints: Checkpoints can be saved and loaded by shard, laying the foundation for fault tolerance and elastic scaling.
Example code:
import torch# 1. Initialize the process grouptorch.distributed.init_process_group(backend="nccl")rank = torch.distributed.get_rank()world_size = torch.distributed.get_world_size()# 2. Build the model: create the model structure without occupying memory, then shard weightswith torch.device("meta"):model = build_model(config) # Only build the computation graph; do not allocate real device memoryshard_weights(model, config.shard) # Each rank loads only the shard it owns# 3. Wrap the model with the full-shard policyfor module in model.shard_units: # Wrap by Transformer block or modality encoderfully_shard(module, config.fsdp)fully_shard(model, config.fsdp)# 4. Standard training loop: parallelism details are transparent to training codeoptimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)for step, batch in enumerate(dataloader):outputs = model(batch)loss = outputs.lossloss.backward() # Trigger gradient sharding and reduction during backwardoptimizer.step()optimizer.zero_grad()
4.2 Model Loading: From Full Loading to On-Demand Shard Loading
A trillion-parameter model cannot be loaded in the traditional way, that is, by first loading the complete weights and then starting training. A feasible path is:
- Structure instantiation: Build the model skeleton on the meta device. Only the operator graph is created, without allocating real device memory.
- Weight shard conversion: Convert full weights in single-file or traditional formats into a distributed checkpoint format sharded by parameter. Each shard contains metadata such as parameters, optimizer states, and training step.
- On-demand loading per accelerator: Each card reads only its own shard and fills it into the pre-built model. This reduces peak loading memory from the full model size to the single-card shard size.
- Shard scheduling and prefetching: Weight loading is often limited by storage bandwidth. Reads can be scheduled according to the order in which shards are needed, and shards not on the current path can be prefetched into memory or host RAM to reduce compute waiting time.
For multimodal models, it is recommended to package each modality encoder and the backbone as independent distributed checkpoints. This makes it easier to iterate on the weights of a specific modality.
4.3 Gradient Synchronization: Overlapped with Backward Computation
Native full sharding triggers gradient reduction layer by layer from back to front during backward propagation. Three key optimization points are:
- Overlap reduction with backward computation: Parameter shard reduction and gradient computation for subsequent layers run concurrently, hiding communication time under computation.
- Control prefetch depth: Prefetching too many shards can occupy memory and cause traffic bursts. Prefetching too few shards may not provide enough overlap. The prefetch depth needs to be tuned experimentally on the target hardware.
- Select appropriate communication primitives: In the data dimension, full sharding uses reduce-scatter to aggregate gradients and all-gather to gather parameters, rather than the traditional all-reduce. In multimodal scenarios, the data volume of each modality can differ significantly. It is advisable to set different batch sizes or sampling ratios per modality to avoid a small modality becoming the bottleneck.
5. Hybrid Parallelism Orchestration: Let Four Types of Parallelism Work Together
Full sharding alone cannot support trillion-parameter training. It is usually necessary to combine several strategies:
| Parallel dimension | What is sharded | Main role | Design considerations |
|---|---|---|---|
| Full-shard data parallelism | Parameters, gradients, optimizer states | Amortize memory usage and scale data size | Tune shard group size and sharding granularity |
| Tensor parallelism | Within a single operator | Reduce per-card compute and memory pressure for layers | High communication volume; keep it within high-speed node interconnect where possible |
| Pipeline parallelism | Model layers by depth | Scale model size across nodes | Split stages reasonably and design scheduling to reduce pipeline bubbles |
| Expert parallelism | Experts within expert layers | Carry the scale of MoE experts | Coordinate with capacity factor and load balancing; control dispatch communication overhead |
The basic principle is: parallelism with heavy communication should run on high-bandwidth links, while parallelism with light communication can run on lower-bandwidth links.
For example:
- Tensor parallelism is usually limited to a single node.
- Pipeline parallelism and expert parallelism can span nodes.
- Full-shard parallelism can cover all training accelerators.
MoE expert load balancing is also critical. If a few “hot experts” handle most tokens, the devices holding those experts become bottlenecks that slow down the entire step.
Common techniques include:
- Auxiliary load-balancing loss
- Routing noise
- Capacity factor to limit the load carried by a single expert
6. Long-Running Stable Training: From “It Runs” to “It Runs for Days”
Trillion-parameter training is measured in weeks or even months. Engineering support is therefore as important as the algorithm itself.
Asynchronous and distributed checkpoints
Save distributed checkpoints at fixed step intervals and move the write process to background threads so that it does not block the main training loop. When conditions permit, keep copies of the most recent checkpoints in memory to enable faster recovery after failures.Fault tolerance and elastic recovery
Use a job orchestration platform to monitor process heartbeats. When a node fails, automatically start a standby node and restore from the most recent checkpoint. During recovery, verify shard integrity to ensure that model parameters and optimizer states are strictly aligned.Slow-node and failure root-cause analysis
Periodically collect per-card step time, communication time, and device temperature to identify “slow cards” that consistently deviate from the average. Centralize logs from all ranks through a logging service, align timelines by training step, and quickly determine whether the issue is an operator anomaly, communication timeout, or data-loading stall.Observability
Training metrics should be connected to a unified monitoring and alerting system. Key metrics include:
| Metric | Meaning | Abnormal signal |
|---|---|---|
| Model FLOPs Utilization (MFU) | Ratio of effective computation to hardware peak compute | Low values indicate that communication or memory access is a bottleneck |
| Single-step time distribution | Mean and variance of per-rank step time | Continuously increasing variance indicates slow nodes or load imbalance |
| Communication time ratio | Ratio of collective communication time to total step time | A high ratio requires adjusting the parallel layout or overlap strategy |
| GPU memory usage curve | Peak usage and fragmentation level | When memory usage approaches the limit, fragmentation can easily interrupt training |
| Gradient norm | L2 norm of the global gradient | Sudden spikes or drops may indicate numerical anomalies |
7. From One-Off Adaptation to Reusable Capability
The value of adapting a trillion-parameter multimodal model on domestic AI accelerators is not limited to running one model successfully. More importantly, it produces a transferable methodology.
For teams training large models on domestic compute, useful practices include:
- Profile first, then adapt: Use a memory budget model to determine the parallelism plan instead of blindly tuning parameters.
- Complete operators layer by layer: Follow the order of graph rewriting, composite implementation, and custom kernels. Use layer-by-layer alignment tests to protect correctness.
- Use native full sharding as the main path: Reduce manual parallelism code and lower maintenance costs, while gaining fault-tolerance capabilities compatible with distributed checkpoints.
- Treat stability as the first requirement: Asynchronous checkpoints, slow-node detection, and monitoring/alerting should be built alongside the training scripts, not added after problems occur.
At the same time, training adaptation is a systems-engineering effort. It requires coordination among compute resources, software stacks, model structure, and cluster operations.
For example, Baidu AI Cloud’s Qianfan platform provides a model development and training toolchain, while the Baige platform provides AI compute, storage, and networking capabilities that provide underlying support for ultra-large-scale training. Combined with PaddlePaddle, Baidu’s deep learning framework, developers can complete the full process from model development and training to deployment on domestic compute.
Regardless of the compute or platform used, the underlying principles of parallel design, operator adaptation, and stability assurance are broadly shared. That is the core value this article aims to convey.
