Training Trillion-Parameter LLMs on Domestic AI Chips: A Practical Adaptation Guide
As large language and multimodal models scale from tens of billions toward trillions of parameters, training stops being a per-GPU speed problem and becomes a memory-capacity problem. This guide lays out a practical engineering path for adapting trillion-parameter model training to domestic high-performance AI chips. It covers the core challenges (the memory wall, operator and software-stack compatibility, and collective communication bottlenecks), a pre-adaptation checklist spanning drivers, communication libraries, operator coverage, mixed precision, and checkpoint formats, and a minimal runnable FSDP2 sharded training example. It then walks through the full pipeline from checkpoint conversion and model loading to sharding scheduling and gradient synchronization, along with mixed-precision and memory optimizations, action-oriented performance tuning, and reproducible experiment steps readers can apply directly.
1. Background: Training Challenges from Parameter Growth
In recent years, the parameter scale of large language and multimodal models has grown rapidly, moving from the tens-of-billions range toward trillions. Once a model enters the trillion-parameter range, the training system faces a different question: it is no longer about “whether a single card is fast enough,” but “whether a single card can even hold the model.”
Memory requirements for the parameters alone differ significantly across precision formats. Taking a one-trillion-parameter model as an example:
- BF16 parameters need about 2 TB of memory;
- FP8 parameters need about 1 TB;
- FP4 parameters need about 0.5 TB.
This is only the static footprint of the model weights themselves. In actual training, you also add gradients, optimizer states, forward activations, communication buffers, and temporary aggregation buffers. With an AdamW-style optimizer, the first-moment and second-moment estimates, plus any FP32 master weights, substantially increase memory usage. As a result, trillion-parameter models typically require a multi-card, multi-node distributed training architecture, combined with techniques such as parameter sharding, gradient sharding, optimizer-state sharding, and activation recomputation.
Domestic high-performance AI training-and-inference chips provide a self-controlled, supply-stable hardware foundation for large-model training, but running frontier models stably still requires a complete training adaptation: the model structure, parallel strategy, communication primitives, operator libraries, mixed-precision strategy, and checkpoint system must all be aligned. This article addresses common questions such as “how to do training adaptation on domestic AI chips,” “what to do when memory is insufficient,” and “how to troubleshoot slow communication,” and lays out a practical, actionable engineering path.
2. Core Challenges of Training Adaptation
In trillion-parameter model training adaptation, common problems usually fall into three areas.
1. The memory wall: the model does not fit
When the sum of parameters, gradients, optimizer states, and activations exceeds the capacity of a single card, you must reduce per-card residency through sharding. Strategies such as FSDP, ZeRO, tensor parallelism, and pipeline parallelism all serve this goal.
2. Software stack and operator adaptation: can the model’s operators run
Domestic AI chips typically have their own runtime, communication library, operator library, and supported mixed-precision range. Custom operators, attention implementations, normalization layers, positional encodings, and communication primitives in the model must all be revalidated on the target hardware. If operator coverage is insufficient, common symptoms include the model failing to compile, incorrect forward results, errors during backpropagation, or performance well below expectations.
3. Communication efficiency: collective communication becomes the bottleneck
Distributed training involves a large amount of collective communication such as all-reduce, all-gather, and reduce-scatter. If communication is not overlapped with computation, or if the inter-machine links become a bottleneck, training throughput drops noticeably. When adapting domestic chips, it is especially important to confirm whether the vendor’s communication library, the PyTorch adaptation plugin, and multi-node topology awareness are mature.
3. Before Adapting Domestic AI Chips: Do a Checklist First
Before writing training code, it is recommended to complete a domestic-chip adaptation checklist. Many training failures are not model-logic problems but are caused by inconsistent environments, drivers, communication libraries, operators, or checkpoint formats.
| Check item | Recommendation | Pass criterion |
|---|---|---|
| Chip and driver version | Record chip model, firmware, driver, and runtime toolchain versions | Multiple cards visible, version info consistent |
| Communication library version | Check the vendor communication library, PyTorch communication backend, and adaptation plugin | Small-scale all-reduce, all-gather, reduce-scatter pass |
| Operator coverage | Check LayerNorm, Attention, Rotary, custom operators, and BF16/FP16 support | Forward and backward numerical errors within acceptable range |
| Mixed-precision support | Confirm BF16, FP16, and FP32 reduction are available | If FP32 reduction is unavailable, a fallback plan is required |
| Checkpoint format | Confirm full single-machine weights can be converted to sharded checkpoints | Parameter count, shape, dtype, and sharding mapping consistent |
| Metadata validation | Validate config, parallel topology, parameter names, and shard indices | No shape mismatch or missing keys on load |
You can use the following script entry points as a starting point for adaptation:
python tools/check_env.py --check-driver --check-comm --check-oppython tools/convert_ckpt.py --src /ckpt/full.pt --dst /ckpt/sharded --world-size 64 --precision bf16python tools/validate_ckpt.py --ckpt /ckpt/sharded --config config.json --check-meta
These steps may seem basic, but they significantly reduce the cost of later troubleshooting.
4. FSDP2: The Core Sharded Parallel Training Solution
Traditional data parallelism stores a full copy of the model parameters on every card, which is inefficient in memory use. The core idea of FSDP is to shard parameters, gradients, and optimizer states along the distributed dimension, aggregate parameter shards on demand during forward and backward computation, and release them after computation, thereby reducing per-card memory usage.
FSDP2 further introduces the DTensor abstraction, treating “sharding” as a first-class property of tensors. This makes model state clearer and easier to combine with strategies such as quantization, tensor parallelism, and expert parallelism.
The applicability boundaries of FSDP2 and common parallelism methods can be summarized as follows:
| Parallel method | Main goal | Advantages | Limitations |
|---|---|---|---|
| FSDP2 | Reduce memory for parameters, gradients, and optimizer states | Relatively simple to implement, suitable for large-scale data parallelism | Frequent communication, depends on sharding scheduling quality |
| Tensor parallelism | Split single-layer computation | Reduces single-layer memory, improves computation parallelism | Requires model restructuring, communication-sensitive |
| Pipeline parallelism | Split the model by layers | Suitable for ultra-deep models | Complex bubbles, high scheduling difficulty |
| ZeRO | Shard optimizer states and gradients | Compatible with data parallelism | Still needs to combine memory optimization strategies |
Below is a minimal runnable FSDP2 framework. Before the code, you need to complete distributed environment initialization and use a launch command to bring up multiple processes.
# Single-node multi-card launch exampletorchrun --nnodes=1 --nproc_per_node=8 train_fsdp2.py# For domestic chip environments, replace backend and device with the vendor's communication backend and device interface
import osimport torchimport torch.distributed as distfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy# Launch command example:# torchrun --nnodes=1 --nproc_per_node=8 train_fsdp2.py# For domestic AI chips, replace backend and device with the vendor's communication backend and device interface.def build_model():# This is only a sketch of a Transformer structure; replace it with the full model definition in practiceclass TransformerModel(torch.nn.Module):def __init__(self):super().__init__()self.layers = torch.nn.ModuleList([torch.nn.Linear(4096, 4096) for _ in range(2)])def forward(self, x):for layer in self.layers:x = layer(x)return xreturn TransformerModel()def main():rank = int(os.environ.get("RANK", "0"))local_rank = int(os.environ.get("LOCAL_RANK", "0"))world_size = int(os.environ.get("WORLD_SIZE", "1"))# For domestic chips, you can replace nccl with the vendor's communication backendbackend = os.environ.get("DIST_BACKEND", "nccl")dist.init_process_group(backend=backend,rank=rank,world_size=world_size)if backend == "nccl":device = torch.device("cuda", local_rank)torch.cuda.set_device(device)else:# For domestic chips, set the device per the vendor documentation, e.g. npu, mlu, or another accelerator devicedevice_name = os.environ.get("AI_DEVICE", "cpu")device = torch.device(device_name)# Some domestic runtimes also require explicitly setting the local device index# Build a 1-D data-parallel mesh; in practice it can be extended to a multi-dimensional mesh combined with tensor parallelismmesh = init_device_mesh(device.type,(world_size,),mesh_dim_names=("dp",))# BF16 compute + FP32 reduction is a common configuration, but whether FP32 reduction is available depends on hardware and software stackmp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16,reduce_dtype=torch.float32,)model = build_model().to(device)# Shard each sub-layer at fine granularityfor layer in model.layers:fully_shard(layer,mesh=mesh,mp_policy=mp_policy)# Shard the root module again to form a hierarchical sharding groupfully_shard(model,mesh=mesh,mp_policy=mp_policy)# Continue writing the training loop hereprint(f"rank={rank}, world_size={world_size}, "f"device={device}, mesh={mesh}")dist.destroy_process_group()if __name__ == "__main__":main()
In this code, fully_shard aggregates the required parameters before a module call and releases the shards after the call. For developers, the value of FSDP2 is that it encapsulates complex sharding state into modules and DTensors, making the model code closer to single-card training code.
5. The Complete Training Pipeline: From Model Loading to Gradient Synchronization
1. Model loading
A trillion-parameter model usually cannot be loaded directly into a multi-card environment from a single full checkpoint. In engineering practice, you need to convert the full checkpoint into a sharded format according to the parallel topology, then distribute it to each node.
Key steps include:
- Re-shard the full weights saved on a single machine according to the DP, TP, PP, and other topologies;
- Preserve metadata such as config, parameter names, shapes, dtypes, and sharding mappings;
- Avoid all nodes loading the full weights simultaneously, which creates a centralized memory peak;
- After loading, validate parameter count, shapes, key names, and dtypes.
In domestic chip environments, special attention is needed to whether the checkpoint conversion and operator loading pipelines are consistent. If the checkpoint is generated by another framework or another parallel strategy, you need to confirm that the naming rules, parameter layout, and current FSDP2 sharding rules match.
2. Sharding scheduling
Sharding scheduling determines when parameters are aggregated, when they are released, and how aggregation overlaps with computation. Reasonable scheduling usually needs to:
- Overlap parameter aggregation with computation to hide communication latency;
- Control the number of parameter shards resident at the same time to avoid excessive instantaneous memory peaks;
- Use hierarchical sharding groups so that each Transformer sub-layer aggregates and releases independently;
- Adjust aggregation granularity and prefetch strategy according to inter-machine bandwidth.
The following metrics are recommended to observe closely:
| Metric | Description | Anomaly signal |
|---|---|---|
| all_gather_duration | Time spent aggregating parameters | Communication share too high |
| comm_overlap_ratio | Ratio of communication overlapped with computation | Insufficient overlap, obvious waiting |
| peak_memory | Per-card peak memory | Too few shards or too many resident |
| tokens_per_second | Training throughput | No improvement after tuning indicates another bottleneck |
| cross_machine_comm_ratio | Share of inter-machine communication | Too much inter-machine traffic, unreasonable topology |
Common troubleshooting log keywords include: timeout, collective, reduce-scatter, all-gather failed, memory allocation failed, checkpoint metadata mismatch. If intra-machine communication is normal but inter-machine throughput is significantly low, focus on checking inter-node bandwidth, switching equipment, NIC queues, link load, and whether the communication topology spans too many nodes.
3. Gradient synchronization
After backpropagation, each node holds the gradients of its own parameter shards. The gradient synchronization phase usually uses collective communication primitives such as reduce-scatter to reduce the distributed gradients to the corresponding nodes for the optimizer to update.
Tuning focus includes:
- Choose the appropriate communication backend and topology-aware strategy;
- Pipeline gradient reduction with forward and backward computation;
- Merge small messages to reduce the scheduling overhead of frequent communication;
- Adjust communication bucket size according to hardware bandwidth.
Bucket parameter names differ across frameworks; common directions include:
bucket_size_mbgrad_bucket_sizereduce_buffer_size_mbmax_split_size_mb
The tuning approach is usually: buckets that are too small increase the number of communications and small-message overhead; buckets that are too large increase memory usage and may reduce overlap granularity. It is recommended to test tiers such as 25 MB, 64 MB, and 128 MB on the target hardware, observing throughput, memory, and communication wait time.
6. Mixed Precision and Memory Optimization
When training trillion-parameter models on domestic chips, mixed precision is usually a must. The common approach is BF16 or FP16 for computation, and FP32 for some gradient reductions or numerically sensitive steps. But note that whether FP32 gradient reduction is available, and whether it provides performance benefits, depends on chip compute capability, communication library, and software stack support.
To further compress memory, you can combine the following methods:
- Activation recomputation: trade extra computation for lower activation memory;
- Optimizer state offloading: temporarily store infrequently used optimizer states to main memory or other media;
- Hierarchical sharding: control parameter aggregation granularity by sub-layer or module group;
- Temporary buffer reuse: reduce repeated allocation of communication buffers.
These optimizations are not better the more you add. Activation recomputation may increase compute time and even change some numerical behavior; optimizer offloading may introduce I/O bottlenecks and increase the risk of failed checkpoint resume; overly aggressive mixed precision may cause loss fluctuations, gradient underflow, or precision drift.
A gradual (canary) strategy is recommended:
- First enable a stable configuration, e.g. BF16 compute + FP32 gradient reduction;
- Validate the loss curve, gradient norms, and checkpoint recovery capability on a small-scale model;
- Then gradually enable activation recomputation, prioritizing layers with low computational redundancy;
- Before enabling optimizer offloading, keep a rollback checkpoint;
- If performance regresses or checkpoint resume behaves abnormally, immediately roll back to the last stable configuration.
Observable metrics include: grad_norm, loss, nan_count, inf_count, optimizer_io_wait, checkpoint_save_duration, restore_success_rate. These metrics help the team judge whether an optimization truly brings benefits rather than introducing new instability.
7. Performance Tuning and Best Practices
After completing the basic pipeline, you can advance performance optimization in an action-oriented way.
| Tuning item | Action | Observation tool or metric | Pass criterion |
|---|---|---|---|
| Communication bottleneck | Analyze all-gather and reduce-scatter time share | Profiling tool, communication metrics | Controllable communication share, no obvious waiting |
| Sharding granularity | Adjust sub-layer sharding groups and aggregation granularity | Peak memory, throughput | Throughput improves and memory does not overflow |
| Topology awareness | Place the same sharding group in a high-bandwidth domain | Intra-/inter-machine communication ratio | Inter-machine communication drops significantly |
| Stable reproducibility | Fix random seeds, data order, and checkpoint format | Logs, checkpoint hash | Multiple runs produce consistent results |
| Small-scale validation | First validate numerical correctness on a small model | loss, grad_norm | Then scale up to the target size |
Recommended minimal reproducible experiment steps:
- Use a small-scale Transformer with a fixed random seed;
- Fix the data loading order and turn off unnecessary randomness;
- Save the initial checkpoint and the post-training checkpoint;
- Record the baseline throughput, memory, loss, and grad_norm;
- Change only one variable at a time, e.g. sharding granularity, communication bucket size, or recomputation strategy;
- Compare the new configuration against the baseline to confirm benefits and risks.
8. Summary
Trillion-parameter model training is essentially a systematic coordination problem among memory, compute, and communication. For domestic AI chips to carry such tasks, it is not enough to focus only on single-card peak compute; you must also start from engineering details such as drivers, communication libraries, operator coverage, mixed precision, checkpoint formats, and monitoring and troubleshooting.
Fully-sharded data parallelism, represented by FSDP2, allows ultra-large models to run across multiple cards and machines through parameter sharding, on-demand aggregation, and hierarchical scheduling. But what truly determines the success of training adaptation is whether the complete pipeline of model loading, sharding scheduling, and gradient synchronization can be connected. Starting from checklists, observable metrics, risk rollback, and small-step validation is the reliable path to building an efficient, stable, and scalable domestic large-model training capability.
