Trillion-Parameter Model Training on Domestic AI Accelerators: A Practical Adaptation Guide
This practical guide explains how to adapt trillion-parameter MoE model training to domestic AI accelerators. It lays out a TP/PP/DP selection matrix keyed to concrete hardware signals, then walks through a reproducible minimal FSDP2 full-shard experiment with conditional acceptance criteria. A three-stage pipeline checklist covers model loading, shard scheduling, and gradient synchronization, while monitoring tables and a troubleshooting matrix help teams diagnose OOM, precision drift, communication timeouts, checkpoint corruption, and inconsistent resume. With fixed hardware, framework versions, and parallelism strategies, engineers can use these patterns to raise adaptation success rates and observability.
1. Background: Why Adaptation Is Needed Again in the Trillion-Parameter Era
As parameter counts scale from tens of billions toward trillions, the Mixture of Experts (MoE) architecture has become the mainstream choice for holding such massive parameter volumes. It distributes parameters across multiple expert sub-networks, expanding model capacity while keeping the compute per forward pass under control. But this jump in scale also brings triple pressure on memory, compute, and communication: the parameters plus optimizer states alone far exceed single-card memory, so distributed training with coordinated sharding is mandatory.
On domestic AI accelerators, the problem compounds further. Domestic accelerator cards differ from mainstream platforms in their instruction sets, operator implementations, communication libraries, runtimes, and ecosystem toolchains. A model already validated on GPUs usually needs more than a simple recompile to “run, run well, and run stably” on domestic cards. It typically requires compute adaptation, joint debugging of the domestic communication library, distributed training tuning, and checkpoint/resume verification.
This guide focuses on an actionable path: it first provides a TP/PP/DP selection matrix, then presents a reproducible minimal FSDP2 full-shard data-parallel experiment, acceptance conditions, a three-stage pipeline checklist, and a troubleshooting table. With clear hardware, framework versions, and parallelism strategies, engineering teams can use these to improve adaptation success rates and observability.
2. Core Challenges and the TP/PP/DP Selection Matrix
When adapting a trillion-parameter model, the first question is not “will the code compile” but “how do I choose TP/PP/DP.” The table below gives selection rules keyed to specific signals:
| Scenario Signal | Recommended Parallelism Strategy | Rationale and Adjustment Notes |
|---|---|---|
| Single-card memory headroom below 10% | Prefer TP or PP | Solve the “doesn’t fit” problem first. If intra-layer matrices are large and the model has fewer layers, prefer TP; if there are many layers with clear layer boundaries, prefer PP |
| High intra-node interconnect bandwidth, low inter-node bandwidth | Keep TP within the node; use PP or DP across nodes | TP communication is frequent, so keep it within a node as much as possible. Avoid high-frequency TP communication across nodes |
| Adequate but latency-unstable inter-node bandwidth | PP + DP/FSDP | PP splits layers across nodes, and DP raises throughput; watch for pipeline bubbles and gradient-sync timeouts |
| Many model layers, e.g., 60+ | Prefer PP | PP splits by layer, making memory balancing more intuitive. Ensure enough micro-batches to lower the bubble ratio |
| Clearly imbalanced MoE routing | Enable Expert Parallelism (EP) and constrain communication scope | Expert load skew amplifies communication and memory jitter. Enable a capacity factor and load-balancing loss, and place EP groups within a node first |
| Small batch size | Mainly TP/PP; use pure DP cautiously | Small batches struggle to hide communication overhead, so pure DP may push the communication ratio too high |
| Large batch size or sufficient gradient accumulation | DP/FSDP can improve throughput | Large batches can mask parameter all-gather and gradient-reduce overhead, making them suitable for FSDP2 full-shard or HSDP |
| Inter-node bandwidth constrained but intra-node bandwidth ample | Prefer HSDP | HSDP shards within the node and replicates across nodes, reducing inter-node collective communication pressure |
The recommended priority order for common combinations is:
- Insufficient memory: add TP or PP first.
- Keep TP within a node whenever possible.
- PP suits layer splitting and needs enough micro-batches.
- DP/FSDP handles data-dimension scaling and memory sharing.
- MoE scenarios additionally introduce EP, with expert communication kept within nodes first.
- When inter-node communication is congested, replace full-shard with HSDP.
3. FSDP2 Full-Shard Data Parallel: A Reproducible Minimal Experiment
The core idea of FSDP2 is to shard parameters, gradients, and optimizer states along the data-parallel dimension, all-gathering only when needed. Compared with earlier versions, FSDP2 manages parameters explicitly via DTensor, which makes the boundaries between forward all-gather and backward reduce-scatter clearer. This helps reduce the memory peak caused by repeatedly switching between aggregation and sharding, and makes it easier to orchestrate communication-computation overlap.
3.1 Dependencies and Runtime Environment
Example dependencies:
- Python 3.10+
- PyTorch 2.4+
- torchrun
- The domestic card vendor’s software stack has completed adaptation; for NPUs, a corresponding adaptation layer such as torch_npu is required
- Device type: use cuda for CUDA-like devices; replace with the actual device type for NPUs and others
- Communication backend: defaults to nccl; domestic cards can explicitly set the vendor backend parameter, e.g., hccl, cann, xccl, etc.
Environment variable example:
export WORLD_SIZE=8export RANK=0export MASTER_ADDR=127.0.0.1export MASTER_PORT=29500# Default NCCL; for domestic cards, replace with the vendor backend name, e.g., hccl, cann, xcclexport TORCH_DIST_BACKEND=nccl# If the vendor stack provides a visible-device variable, set it accordingly# export ASCEND_RT_VISIBLE_DEVICES=0,1,2,3,4,5,6,7# Enable communication debuggingexport NCCL_DEBUG=WARN
Launch command example:
torchrun --nproc_per_node=8 --master_port=29500 minimal_fsdp2.py
3.2 Minimal Model Definition
To make the example runnable, here is a minimal Toy Transformer. In real training you can swap it for your business model, but keep the same initialization, data, and optimizer settings.
import osimport torchimport torch.distributed as distfrom torch import nnfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicyclass Block(nn.Module):def __init__(self, dim=512, hidden=2048):super().__init__()self.norm = nn.LayerNorm(dim)self.fc1 = nn.Linear(dim, hidden)self.act = nn.GELU()self.fc2 = nn.Linear(hidden, dim)def forward(self, x):return x + self.fc2(self.act(self.fc1(self.norm(x))))class TinyLM(nn.Module):def __init__(self, vocab=4096, dim=512, n_layer=4):super().__init__()self.embed = nn.Embedding(vocab, dim)self.blocks = nn.ModuleList([Block(dim) for _ in range(n_layer)])self.norm = nn.LayerNorm(dim)self.head = nn.Linear(dim, vocab, bias=False)def forward(self, input_ids):x = self.embed(input_ids)for block in self.blocks:x = block(x)return self.head(self.norm(x))def build_model():return TinyLM()def main():dist.init_process_group(backend=os.getenv("TORCH_DIST_BACKEND", "nccl"),init_method="env://",)rank = dist.get_rank()world = dist.get_world_size()device_type = "cuda"device = torch.device(device_type, rank % torch.cuda.device_count())torch.cuda.set_device(device)mesh = init_device_mesh(device_type, (world,))model = build_model().to(device)fsdp_kwargs = dict(mesh=mesh,mp_policy=MixedPrecisionPolicy(param_dtype=torch.bfloat16,reduce_dtype=torch.float32,),)for block in model.blocks:fully_shard(block, **fsdp_kwargs)fully_shard(model.embed, **fsdp_kwargs)fully_shard(model.head, **fsdp_kwargs)fully_shard(model.norm, **fsdp_kwargs)fully_shard(model, **fsdp_kwargs)opt = torch.optim.AdamW(model.parameters(), lr=1e-3)torch.manual_seed(20250308 + rank)input_ids = torch.randint(0, 4096, (8, 128), device=device)loss = model(input_ids).sum()loss.backward()opt.step()opt.zero_grad()if rank == 0:print("loss:", loss.item())print("max_memory_GB:", torch.cuda.max_memory_allocated() / 1e9)dist.destroy_process_group()if __name__ == "__main__":main()
3.3 When to Choose Full-Shard vs. HSDP
- full-shard: All DP ranks jointly shard parameters, gradients, and optimizer states. Lowest memory, but heaviest communication.
- HSDP: Shards within the node and replicates across nodes. Suits clusters with high intra-node interconnect bandwidth but constrained or unstable inter-node bandwidth.
- Selection guidance:
- If single-card memory pressure is extreme and inter-node bandwidth is ample, use full-shard.
- If inter-node bandwidth is clearly lower than intra-node bandwidth, or the communication ratio stays higher than compute time, switch to HSDP.
- If the model has a clear hierarchical structure with distinct parameter layering, nested FSDP can shard again inside large modules to reduce single-layer aggregation pressure.
3.4 Conditional Acceptance Criteria
You cannot treat “relative error < 1e-3” as a universal standard. Validate under the following fixed conditions:
- Same random seed
- Same data input
- Same weight initialization
- Same global batch size
- Same communication backend
- Same mixed-precision policy
- Same optimizer type and learning rate
Let (L{ref}) be the reference implementation loss and (L{test}) the domestic-card adaptation loss, then:
[
E{loss} = \frac{|L{test} - L{ref}|}{\max(|L{ref}|, 10^{-8})}
]
Let (g{ref}) be the reference gradient and (g{test}) the adaptation gradient, then:
[
E{grad} = \frac{|g{test} - g{ref}|_2}{|g{ref}|_2 + 10^{-12}}
]
Recommended acceptance conditions:
- Under BF16 parameters and FP32 gradient reduction, the first 20 steps should satisfy (E{loss} < 10^{-3}) and (E{grad} < 10^{-3}).
- If NaN, Inf, or a persistent abnormal rise in loss appears, fail immediately.
- If using FP16 or vendor approximate operators, additionally report the deviation from the FP32 baseline and adjust the threshold to the calibrated baseline result.
4. Three-Stage Pipeline Checklist
4.1 Model Loading
- Input: trillion-scale checkpoints on object storage, a parallel file system, or a local distributed file system
- Output: a sharded layout adapted to the new hardware, plus metadata that passes validation
- Key parameters: shard read concurrency, weight format conversion, load throughput, shard checksums
- Failure symptoms: load hangs, memory peak exceeded, weight misalignment leading to NaN loss
How to measure loading throughput:
- Count the total checkpoint bytes:
BYTES=$(du -sb /data/ckpt | awk '{print $1}')
- Run the load validation with the same nodes, device count, and storage path as training, and record the elapsed time (T_{load}).
- Compute throughput:
[
Throughput = \frac{Bytes}{T_{load} \times 10^9}
]
- Repeat 5 times and report P50 and P95.
- Record the hardware and storage conditions: storage type, node count, card count, cold read or not, and whether local NVMe, a parallel file system, or object storage is used.
Acceptance suggestion: Do not use a fixed placeholder baseline. Establish a sequential-read baseline on the target cluster first—for example, measure bandwidth with fio or the vendor storage test tool; reaching 60% or more of that baseline can serve as an initial acceptance reference. If it is not met, investigate shard read concurrency, object-storage throttling, network bandwidth, or permission configuration.
Fallback plan: Compare checksums against the checkpoint before loading and keep a read-only backup; on anomaly, fall back to the last intact checkpoint.
4.2 Shard Scheduling
- Input: hardware topology, parallelism strategy, model layer structure
- Output: per-layer parameter sharding layout, memory-balance report
- Key parameters: TP/PP/DP combination, inter-node communication locality, shard balance ratio
- Failure symptoms: individual rank OOM, large inter-node traffic, excessively high communication ratio
Suggested checks:
torchrun --nproc_per_node=8 minimal_fsdp2.py | tee shard_log.txtpython -c "import torch; print(torch.cuda.max_memory_allocated() / 1e9, 'GB')"
If a few ranks show significantly higher memory, check the shard balance ratio first; if inter-node traffic is abnormal, check whether TP or EP crosses node boundaries.
4.3 Gradient Synchronization
- Input: backward gradients, parallel group partitioning
- Output: parameters after aggregated updates
- Key parameters: communication-backward overlap ratio, communication ratio, sync timeout threshold
- Failure symptoms: sync timeout, hang, communication backend errors
Suggested settings:
export TORCH_NCCL_BLOCKING_WAIT=1export NCCL_DEBUG=INFO
On sync timeouts, first shrink the parallel group, then check the inter-node network, switches, RDMA configuration, and communication backend version.
5. Software-Hardware Co-Design: Steps, Metrics, and Fault Recovery
The essence of adaptation is model-side modification on the domestic card vendor’s software stack, covering drivers, runtimes, communication libraries, operator libraries, and the framework adaptation layer. Proceed with these actions:
- Pin the environment: fix the driver, runtime, communication library, framework, and adaptation-layer versions, and record them in an inventory to avoid version drift that causes intermittent issues.
- Verify operator by operator: run unit-test comparisons for attention, normalization, and MoE routing operators, and record relative errors.
- Instrument training observability: hook up logging and monitoring to track memory, communication, compute utilization, loss curves, and node health.
| Monitoring Item | Example Alert Threshold | Suggested Command or Method |
|---|---|---|
| Memory usage | Approaching 90% of the single-card limit | torch.cuda.max_memory_allocated(), npu-smi info, vendor monitoring tools |
| Communication ratio | Continuously higher than compute time | torch.profiler, communication logs, NCCL_DEBUG=INFO |
| Compute utilization | Long below the target baseline | Vendor monitoring, profiler |
| Loss curve | NaN appears or abnormal rise | Log monitoring, gradient-norm recording |
| Node health | Lost heartbeat, ECC errors | Node health-check scripts, vendor diagnostic tools |
Communication profiling example:
import torchwith torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU,torch.profiler.ProfilerActivity.CUDA,],record_shapes=True,) as prof:loss = model(input_ids).sum()loss.backward()print(prof.key_averages().table(sort_by="cuda_time_total"))
Operator unit-test suggestions:
python test_ops.py --op rmsnorm --tol 1e-3python test_ops.py --op attention --tol 1e-3python test_ops.py --op moe_route --tol 1e-3
Fault recovery flow: monitoring alert → locate the rank/node → preserve on-site logs → resume training from the most recent intact checkpoint → isolate the faulty node.
When data supply is decoupled across containers, object storage, and message queues, the security boundaries must be clear:
- Run containers as non-root and avoid mounting sensitive credentials.
- Use least-privilege policies for object storage, isolating buckets/prefixes by tenant or job.
- Prefer read-only mounts for checkpoints and data.
- Back up critical configuration and checkpoint metadata before operations.
- Run a consistency check before resuming to avoid recovering from corrupted shards, which can make training diverge.
- Message queues should only carry tasks and metadata, not unencrypted sensitive data; access requires ACLs, TLS, and audit logs.
6. Practical Recommendations and Troubleshooting Table
Minimal verification checklist:
- Compare loss against a single-card or small-cluster pure-DP baseline.
- Fix the random seed, data, global batch, initialization, and precision policy.
- Keep key operator unit-test errors within the threshold.
- Scale up to multi-node, multi-card step by step.
- Use memory peak and throughput as dual metrics to tune the parallelism combination, activation recomputation, and communication overlap.
| Common Error | Possible Cause | Observable Metric or Command | Troubleshooting Direction |
|---|---|---|---|
| Memory overflow (OOM) | Insufficient sharding granularity, recomputation not enabled | torch.cuda.max_memory_allocated(), per-rank memory logs |
Increase sharding granularity, enable activation recomputation, switch to HSDP |
| Precision drift or NaN | Mixed-precision reduction differences, operator deviation | loss, grad norm, NaN checks | Use FP32 for reduction, layer-by-layer comparison, fix the random seed |
| Communication timeout | Parallel group too large, insufficient overlap, network anomaly | NCCL_DEBUG=INFO, communication ratio |
Shrink the parallel group, raise the timeout threshold and alert, check the inter-node network |
| Checkpoint corruption | Interrupted writes, permission issues, storage anomalies | sha256sum, metadata validation |
Checksum comparison, read-only backup, re-export the checkpoint |
| Inconsistent resume | Mismatched shard layout, version drift | Checkpoint metadata, rank count, TP/PP config | Validate metadata before loading, pin framework and parallelism-strategy versions |
7. Conclusion
Adapting large-scale model training on domestic AI compute is a systems-engineering effort that spans model architecture, parallelism strategy, communication optimization, and the hardware ecosystem. Given clear hardware, framework versions, and parallelism strategies, centering on FSDP2 full-shard data parallel to connect the three-stage pipeline—model loading, shard scheduling, and gradient synchronization—and pairing it with conditional acceptance, monitoring, and troubleshooting mechanisms can improve adaptation success rates and observability on domestic AI compute, accumulating reproducible engineering experience for an autonomous, controllable compute ecosystem.
