Trillion-Parameter LLM Training on Domestic AI Accelerators: A Full-Stack Adaptation Guide
Trillion-parameter-class large language models are pushing training systems to their limits. This article explains why adapting such models to domestic AI accelerators is difficult, covering memory pressure, communication bottlenecks, and software-stack gaps. It reviews a native fully sharded data-parallel approach and breaks down three critical engineering stages: model loading, shard scheduling, and gradient synchronization. It also discusses multimodal training, numerical stability, operations, and troubleshooting, giving engineering teams a practical methodology for training frontier models on new hardware and software stacks.
Recently, an important signal emerged from China’s large-model ecosystem: flagship models at the trillion-parameter scale began to be released in open source. As parameter counts grow, open source matters not only because it lets more teams use the models, but also because it becomes a test of whether domestic compute can support frontier-model training. At the same time, domestic AI accelerators completed training adaptation for this class of models. By using a native fully sharded data-parallel path, they connected the full training pipeline from model loading and shard scheduling to gradient synchronization.
Considered together, these developments mark a turning point: frontier-model training is no longer limited to accelerators from a single established ecosystem. For engineering teams, this creates a new question: how can a trillion-parameter-class model be trained stably, efficiently, and sustainably on an unfamiliar hardware and software stack?
This article does not target a specific product. Instead, it abstracts this type of adaptation work into a general methodology. It examines the memory and communication bottlenecks of trillion-parameter training, analyzes three key stages on the native sharded data-parallel path, and offers practical advice on multimodal training, stability, and operations.
1. Why trillion-parameter training adaptation is a hard threshold
1.1 Parameter scale brings memory and bandwidth pressure, not just compute pressure
A rough estimate: a trillion parameters occupy about 2TB for weights alone in BF16; gradients require another 2TB. If FP32 master weights and Adam-like first- and second-moment states are also maintained, another 12TB is needed. The three together total about 16TB, equivalent to filling the memory of over a hundred 80GB accelerators, before activation values are even considered.
Compute demand also grows roughly linearly with parameter count. The computation for training one token can be approximated as 6 × parameter count floating-point operations, about 2 for the forward pass and 4 for the backward pass. A trillion-parameter model processing 1 trillion tokens therefore requires 6 × 10^24 floating-point operations. This means:
- Parameter count: sets the lower bound on memory;
- Sequence length: determines activation and attention costs;
- Total token count: determines overall training time.
Together, these three factors determine the parallel strategy, communication topology, and fault-tolerance design. The essence of adaptation is to find a balance across these three dimensions.
1.2 Open-source flagship models require hardware neutrality
Open-source models are valuable because they are reproducible and transferable, enabling different teams to continue pretraining or fine-tuning on their own compute. However, the more advanced the model architecture, the deeper its dependencies on the underlying stack. Common obstacles include:
- New or custom operators that are missing or underperforming on the target platform;
- Subtle differences in mixed-precision rules and initialization across backends;
- Inconsistent semantics and topology awareness of distributed communication primitives.
Simply reusing existing code often leads to systems that run, but run slowly, fail to converge properly, or become unstable.
1.3 Common challenges in domestic software and hardware stacks
Compared with mature ecosystems, the software stacks of domestic AI accelerators are still evolving quickly. Engineering teams often encounter the following issues:
- Operator coverage: specialized model structures may lack high-performance implementations, requiring fallback to general implementations, manual composition, or custom operator development;
- Communication libraries: collective communication interfaces and topology awareness must be verified one by one, especially for high-frequency operations such as gradient reduction and parameter aggregation;
- Compilation and graph optimization: the compiler’s support for dynamic shapes and sparse structures directly affects the performance ceiling;
- Observability: the maturity of profiling and debugging tools determines how quickly issues can be isolated.
These problems share a common theme: they sit at the seam between model code and hardware capabilities, which is exactly where adaptation work creates value.
2. Before adaptation: understand what you are working with
A mature adaptation workflow usually does not start by changing code. It begins with a round of due diligence that answers at least three questions.
First: What does the model compute?
- Does the backbone use a dense architecture or a sparse mixture-of-experts (MoE) architecture?
- Does it include multimodal branches such as vision or audio encoders?
- What is the maximum sequence length, and does it include long-context tasks?
Second: What can the hardware provide?
- Per-card compute capacity across precisions, memory capacity, and memory bandwidth;
- Intra-node and inter-node interconnect bandwidth;
- Cross-node network bandwidth and topology, such as rail-optimized networks or multi-level switching structures;
- Mixed-precision formats and collective communication primitives supported by the target platform.
Third: How complete is operator and framework support?
Check every type of operator used by the model: whether it has a native implementation, whether it must be composed from smaller operators, whether performance is acceptable, and whether numerical behavior is consistent.
For example, the dispatch and combine operators that route tokens to different experts in an MoE model often become performance bottlenecks. Convolution or window attention operators in a vision encoder may also lack optimized implementations on some platforms.
3. Core solution: design points for a native sharded data-parallel path
3.1 Why choose a native sharded path
An earlier industry practice was to hand-code tensor parallelism, pipeline parallelism, and related logic in model code. This approach is tightly coupled to a particular implementation. When the model structure changes, the parallel code often must be rewritten.
A sharded data-parallel path pushes parallel logic down into the training framework. Users mainly need to tell the framework how to wrap the model, after which the framework handles parameter sharding, communication scheduling, and memory management. This is the meaning of “native.”
For trillion-parameter models, this approach offers four main advantages:
- Lower development cost: model code largely remains single-device in perspective, and forward and backward logic does not need to be rewritten;
- Controllable memory: parameters, gradients, and optimizer states are sharded by layer, with temporary aggregation released after use, making peak memory easier to estimate;
- Ecosystem compatibility: mainstream training-framework features, such as activation recomputation and checkpointing, can be reused directly;
- Better portability: moving from single-node multi-card to multi-node multi-card training mainly requires adjusting parallel configurations.
3.2 How sharded parallelism works
The core idea of the sharded data-parallel path can be summarized as “aggregate when needed, release after use”:
- Model initialization: wrap the model layer by layer so that each card holds only a shard of the parameters;
- Forward pass: when computation reaches a layer, temporarily reconstruct the full parameters for that layer using collective communication, then release them immediately after the layer completes while retaining only necessary information for backward;
- Backward pass: aggregate the layer’s parameters again to compute gradients, then use reduce-scatter communication to accumulate gradients onto the corresponding shards on each card;
- Optimizer update: each card updates only the shard it owns.
This is an approach that trades communication for compute capacity. A model that does not fit in a single card’s memory can be trained by splitting storage and using communication. Whether communication can be sufficiently hidden behind computation directly determines actual efficiency.
Note: Sharding along the sequence dimension is another concept that is easy to confuse. The sharding described above applies to parameters, gradients, and optimizer states, and addresses the problem that the model does not fit. Sequence sharding applies to activations and addresses the problem that long contexts cannot be computed or stored efficiently. It usually requires sequence parallelism or context parallelism. The two operate on different dimensions and often need to be combined.
3.3 Combining parallel strategies
Sharded data parallelism is the foundation, but a single strategy rarely covers all scenarios. In practice, multiple parallel modes are usually combined following the principle of “high-bandwidth intra-node interconnect first, then inter-node network.”
| Parallel dimension | What is split | Suitable scenarios | Main cost |
|---|---|---|---|
| Sharded data parallelism | Parameters, gradients, optimizer states | General foundation, especially when memory is limited | Frequent communication |
| Tensor parallelism | Single-layer weight matrices | Layers are too large or compute-constrained | Communication-heavy; requires high-bandwidth interconnect |
| Pipeline parallelism | Layers, divided into stages | Many layers and tight memory | Pipeline bubbles |
| Sequence/context parallelism | Sequence dimension | Long-context training | Complex attention communication |
| Expert parallelism | MoE experts | Sparse models | Load imbalance and high dispatch overhead |
A common rule of thumb is to use tensor parallelism or expert parallelism within a node to take advantage of high intra-node bandwidth, and use data parallelism across nodes, optionally combined with pipeline parallelism, to reduce pressure on inter-node networks. If cross-node bandwidth is limited, a hybrid sharding approach can be used: full sharding within a group and replicas across groups, trading a small amount of memory redundancy for lower communication volume.
3.4 Do a memory budget first, then decide the parallel configuration
The first step in adaptation is to calculate the memory budget, estimating model states and activations separately.
Model states: for clarity, this article discusses model states from the perspective of a single card after sharding. If a model-state object is shared by N cards, with each card holding 1/N, it can be expressed as:
Per-card memory for model states ≈ (parameter count × bytes per parameter × (1 + K)) / NWhere:Bytes per parameter: 2 for BF16 weights and gradients, 4 for FP32 master weightsK: the number of extra optimizer-state copies per parameter(With FP32 first and second moments, K ≈ 4; total overhead is about 14 bytes per parameter)
For a trillion-parameter model, 1,024 cards, and about 14 bytes per parameter, model-state memory is about 14 × 10^12 ÷ 1,024 ≈ 13.7GB per card, already close to one-sixth of 80GB memory.
Activations: proportional to the number of layers, hidden dimension, sequence length, and micro-batch size. If full activation recomputation is enabled, only the input activation for each layer needs to be stored, greatly reducing memory usage at the cost of about one additional forward pass.
The conclusion is clear: model states determine how many cards are minimally required, while activations determine micro-batch size and the recomputation strategy. Both are essential.
4. Complete the full pipeline: engineering notes for three key stages
The complete training pipeline can be divided into three stages: model loading → shard scheduling → gradient synchronization. Each stage has its own pitfalls.
4.1 Model loading: make TB-scale weights shavable and fast to read
Main challenges
- Weight files can reach TB scale; loading them with a single process can prolong startup and exhaust memory;
- Sharded parallelism requires each card to load only its responsible portion, but checkpoint files are usually organized by complete layers;
- During multi-node startup, all processes accessing shared storage simultaneously can create I/O hotspots.
Practical points
- Deferred initialization: first construct the model structure on a meta device, recording only parameter shapes and dtypes without allocating actual memory;
- Shard-aware loading: based on each card’s shard mapping, read only the corresponding slices from the files;
- Post-load validation: compare key statistics such as parameter norms and means layer by layer to prevent silent errors caused by incorrect sharding;
- Sharing within data-parallel groups: one or more processes in a group can load the data and then broadcast it to other processes in the same group, reducing repeated I/O.
Example pseudocode (for illustration only)
# Stage 1: Build the structure only, without allocating memorymodel = build_model(config, device="meta")# Stage 2: Wrap each layer for sharding and create parameter-to-shard mappingsfor layer in model.layers:shard_layer(layer, mesh=training_mesh)# Stage 3: Each rank loads only the shard it is responsible forfor name, shard in model.named_parameter_shards():local_slice = load_slice_from_checkpoint(ckpt_dir, name, shard)shard.copy_(local_slice, non_blocking=True)assert_allclose_stats(shard, local_slice) # Validate key statistics# Stage 4: Synchronize all ranks and wait for loading to complete before trainingbarrier()
Additional considerations for multimodal models: vision and audio encoders are often stored separately from the language backbone, and their loading order and freezing strategy need to be configured separately. For example, when training only the language backbone, the modality encoders can remain frozen, reducing the number of parameters that need to be sharded.
4.2 Shard scheduling: the control point for peak memory and communication efficiency
Shard scheduling must answer three questions: at what granularity to shard, when to aggregate, and when to release.
(1) Shard granularity: wrap by layer, not the whole model
Layer-wise wrapping, usually with Transformer decoder layers as the unit, is the standard practice for sharded data parallelism:
- Parameters are aggregated only for the layer being computed, so temporary memory usage scales with the size of a single layer;
- Coarse granularity, such as wrapping the entire model once, means aggregating all parameters at once and makes peak memory impossible to control;
- Extremely fine granularity, such as sharding individual matrices, sharply increases communication frequency and scheduling overhead.
(2) Aggregation timing: whether to re-shard after the forward pass
Whether parameters should be re-sharded immediately after the forward pass is a classic trade-off between memory and communication:
- Re-shard after forward: fewer parameters remain in memory during forward, lowering peak memory, but the backward pass requires another aggregation, roughly doubling communication volume;
- Keep full parameters: avoids backward aggregation but increases memory usage.
When memory is tight, prefer re-sharding; when memory has headroom and communication is the bottleneck, keeping full parameters may be acceptable.
(3) Wrapping order: determine whether communication can be overlapped
The order in which layers are wrapped for sharding is usually the reverse of the computation order: layers that reach gradient reduction first during backward are wrapped first. This allows gradient reduction to start while backward computation is still ongoing, creating opportunities for communication-computation overlap.
(4) Memory allocation: reduce fragmentation and peak overlap
- Plan aggregation buffer sizes in advance to avoid repeated allocation and deallocation at runtime;
- Stagger one layer’s parameter aggregation with the previous layer’s gradient reduction as much as possible, avoiding large simultaneous memory usage from both.
Example pseudocode (for illustration only)
# Wrap layer by layer; deeper layers (reached first in backward) are wrapped firstfor layer in reversed(model.layers):shard_layer(layer,mesh=training_mesh,dtype="bf16",reduce_dtype="fp32", # Use higher precision for reductions to improve numerical stabilityreshard_after_forward=use_memory_efficient_mode, # Re-shard when memory is tight)# Wrap the output layer separately: the vocabulary dimension is very large and aggregation causes a clear memory peakshard_layer(model.output_head, mesh=training_mesh, dtype="bf16")
A detail that is easy to overlook: the vocabulary projection layer
In trillion-parameter models, the input word embedding and output vocabulary projection layers can also contain substantial parameters, vocabulary size times hidden dimension. The output layer requires the full vocabulary weights for matrix operations. If the entire layer is aggregated at once, the memory peak can be significant. In practice, the output layer is usually handled separately, or cross-entropy loss is computed in chunks to keep the peak down.
4.3 Gradient synchronization: ensure every card computes correct gradients
Main challenges
- With trillion parameters, gradient reduction communication volume is huge;
- Improper reduction precision can introduce numerical errors;
- Running the optimizer update before synchronization completes can corrupt parameter updates.
(1) Reduction method: reduce-scatter instead of all-reduce
Traditional data parallelism performs an all-reduce after each gradient bucket is ready, so every card ends up with the full gradient. The sharded path uses reduce-scatter instead: each card keeps only the gradient for its shard, roughly halving communication volume. Since each card updates only its own parameter shard, this is mathematically equivalent.
(2) Precision strategy: separate accumulation from update
A common combination is BF16 for computation and FP32 for gradient accumulation and parameter updates. BF16 has a wide dynamic range and is less prone to overflow, but limited mantissa precision. If gradients are accumulated entirely in low precision throughout, small gradients can be lost during repeated additions. A safer approach is to accumulate into FP32 buffers during reduction, then update from FP32 master weights in the optimizer.
(3) Synchronization timing: triggering, ordering, and overlap
- Triggering: set thresholds per bucket and start communication once all gradients in a bucket are ready;
- Ordering: prioritize communication for layers computed first in backward to overlap with computation as much as possible;
- Waiting: before the optimizer update, ensure all reductions have completed.
Gradient accumulation requires more care. If reduction is triggered for every micro-batch, communication volume multiplies. If reduction waits until all accumulation is complete, communication cannot overlap with computation. A common compromise is to use a no-sync mode during accumulation: each card accumulates local gradients independently, then performs one reduction after the final micro-batch and divides by the number of accumulation steps. This requires consistent data partitioning across cards and fully symmetric forward computation.
(4) Gradient clipping: a global operation, not a local one
Gradient clipping first requires computing the global gradient norm across all parameter shards, then scaling gradients proportionally. Since each card sees only its own shard, the norm calculation must go through cross-card reduction. Using local norms instead would produce inconsistent scaling factors and accelerate divergence.
Example pseudocode (for illustration only)
for step in range(total_steps):optimizer.zero_grad(set_to_none=True)# Gradient accumulation: do not trigger gradient synchronization for the first few micro-batchesfor i, micro_batch in enumerate(get_micro_batches(step)):ctx = no_grad_sync(model) if i < accum_steps - 1 else null_context()with ctx, autocast(dtype="bf16"):loss = model(micro_batch)(loss / accum_steps).backward()finalize_grad_sync(model) # Wait for all shard gradient reductions to completeglobal_norm = compute_global_grad_norm(model) # Compute gradient norm across cardsif global_norm > max_norm:scale_gradients(model, max_norm / global_norm)optimizer.step()
5. Additional challenges in multimodal scenarios
Trillion-parameter models are often not purely text models; they may combine text, images, audio, and other modalities. Multimodal training tends to amplify the challenges above.
1. Heterogeneous submodules have very different memory and compute demands
Vision encoders are compute-intensive, and activation memory grows quickly with image resolution. The language backbone usually accounts for most parameters. Modality fusion layers must process two streams of features simultaneously. Adaptation therefore requires separate sharding granularity and precision strategies for each submodule; a one-size-fits-all approach does not work.
2. Variable-length sequences and modality alignment
Images are split into large numbers of visual tokens. After concatenation with text tokens, sequence lengths can vary widely. Padding every sample to the longest sequence wastes a substantial amount of compute. Common approaches include:
- Length-based bucketing to reduce padding waste;
- Variable-length attention operators that skip invalid computation at padded positions;
- Enabling sequence or context parallelism for long samples.
3. Numerical alignment across modalities
Cross-modal attention requires consistent numerical behavior between the two feature streams. If the vision branch and text branch use different precisions or different operator implementations, subtle differences may appear and accumulate during training.
4. Data-loading pressure
Image decoding, audio resampling, and other preprocessing tasks are CPU-intensive and can easily become throughput bottlenecks. A practical approach is multi-process prefetching combined with offline preprocessing caches, moving decoding work ahead of training. This approach applies whether you use a self-built cluster or cloud resources from providers such as Baidu AI Cloud: keep raw data in object storage, cache preprocessing results as sharded files, and let training processes read through a high-speed file system.
6. Stability and operability: keep training running long enough
Training cycles for trillion-parameter models often last weeks or months. Stability can matter more than peak performance.
1. Before launch: layered validation
- Single-node smoke test: first run a few dozen steps on a single node with multiple cards to confirm the forward, backward, and update flows are correct;
- Small-scale benchmark: use a reduced model to measure throughput and identify the split between communication and computation;
- Scale-out validation: gradually increase the number of machines and observe whether throughput grows approximately linearly with card count. A clear drop in scaling efficiency usually indicates that inter-node communication has become a bottleneck.
2. During training: monitor key metrics
At a minimum, monitor:
- Hardware: utilization, memory usage, temperature, power, and card failures;
- Communication: inter-node network bandwidth and the proportion of time spent in collective communication;
- Training: step time, tokens processed per second, loss, and gradient norm.
3. Numerical stability
- Learning-rate warmup: avoid large gradient shocks in early training;
- Skip anomalous steps: when loss spikes or gradient norms behave abnormally, skip the update for that step to prevent parameters from being contaminated;
- Periodic validation: regularly compare loss curves across different parallel configurations to ensure the parallel strategy has not changed the mathematical semantics.
4. Checkpoints and resumable training
- Sharded saving: each card saves its own shard, avoiding a single process writing TB-scale files;
- Asynchronous saving: move disk writes to a background thread to reduce training stalls;
- Retention policy: keep several recent high-frequency checkpoints and a small number of lower-frequency long-term checkpoints, balancing storage cost against recovery granularity;
- Recovery validation: when resuming, verify that optimizer states, learning-rate schedules, and data-loader positions are all restored, avoiding a situation where the model is recovered but training progress is not.
5. Fault recovery
In large clusters, hardware failures are almost inevitable. A mature approach includes fast fault-node detection through heartbeat checks, isolating the faulty node, automatically resuming from the most recent checkpoint, and configuring elastic retry policies at the job-scheduling layer to reduce manual intervention.
7. Troubleshooting common issues
| Symptom | Possible cause | Investigation approach |
|---|---|---|
| Memory overflow during loading | No deferred initialization, or a single process loading all weights | Check whether loading is shard-aware and whether multiple processes load duplicate data |
| Excessive memory peak during forward | Shard granularity too coarse, or output layer aggregated as a whole | Reduce wrapping granularity; handle the output layer separately or compute loss in chunks |
| Second memory spike during backward | Parameter aggregation and gradient-reduction buffers occupy memory simultaneously | Enable re-sharding after forward and stagger communication |
| Poor scaling efficiency | Insufficient inter-node bandwidth or communication not overlapped | Check wrapping order and bucket thresholds; consider hybrid sharding or pipeline parallelism |
| Loss curve deviates from reference | Reduction precision, initialization, or data order differs | Align random seeds, precision strategy, and data partitioning step by step |
| Loss anomalies after gradient clipping | Norm not aggregated across cards | Confirm that global norm reduction was performed |
| Multimodal throughput drops sharply | Too much padding for variable-length sequences or CPU preprocessing bottleneck | Use length-based bucketing, enable variable-length attention, and increase prefetch processes |
8. Conclusion
The emergence of open-source trillion-parameter models turns “whether frontier models can be trained on domestic compute” from a hypothetical into an engineering problem. The fact that domestic AI accelerators have completed training adaptation for this class of models shows that this path is feasible.
From a technical perspective, adaptation can be summarized in three sentences:
- Account first: use a memory budget to determine the starting point for card count and parallel strategy;
- Layer second: use native sharded parallelism as the foundation, combining tensor parallelism, pipeline parallelism, and expert parallelism according to intra-node and inter-node bandwidth;
- Tune last: refine communication-computation overlap, mixed precision, memory peaks, and numerical stability.
Adaptation for trillion-parameter models has no endpoint. As model scale continues to grow, multimodality becomes standard, and scenarios such as sparse expert structures, ultra-long contexts, and heterogeneous compute deployment keep raising new requirements.
For engineering teams, a standardized workflow of due diligence → budgeting → layering → tuning → operations, combined with robust monitoring and checkpointing, is the most reliable preparation for the next leap in parameter scale. Whether your compute sits in a self-built cluster or on cloud resources from providers such as Baidu AI Cloud, the methodology remains the same: account first, layer second, tune last.
