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:

    1. Insufficient memory: add TP or PP first.
    2. Keep TP within a node whenever possible.
    3. PP suits layer splitting and needs enough micro-batches.
    4. DP/FSDP handles data-dimension scaling and memory sharing.
    5. MoE scenarios additionally introduce EP, with expert communication kept within nodes first.
    6. 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:

    1. export WORLD_SIZE=8
    2. export RANK=0
    3. export MASTER_ADDR=127.0.0.1
    4. export MASTER_PORT=29500
    5. # Default NCCL; for domestic cards, replace with the vendor backend name, e.g., hccl, cann, xccl
    6. export TORCH_DIST_BACKEND=nccl
    7. # If the vendor stack provides a visible-device variable, set it accordingly
    8. # export ASCEND_RT_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
    9. # Enable communication debugging
    10. export NCCL_DEBUG=WARN

    Launch command example:

    1. 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.

    1. import os
    2. import torch
    3. import torch.distributed as dist
    4. from torch import nn
    5. from torch.distributed.device_mesh import init_device_mesh
    6. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    7. class Block(nn.Module):
    8. def __init__(self, dim=512, hidden=2048):
    9. super().__init__()
    10. self.norm = nn.LayerNorm(dim)
    11. self.fc1 = nn.Linear(dim, hidden)
    12. self.act = nn.GELU()
    13. self.fc2 = nn.Linear(hidden, dim)
    14. def forward(self, x):
    15. return x + self.fc2(self.act(self.fc1(self.norm(x))))
    16. class TinyLM(nn.Module):
    17. def __init__(self, vocab=4096, dim=512, n_layer=4):
    18. super().__init__()
    19. self.embed = nn.Embedding(vocab, dim)
    20. self.blocks = nn.ModuleList([Block(dim) for _ in range(n_layer)])
    21. self.norm = nn.LayerNorm(dim)
    22. self.head = nn.Linear(dim, vocab, bias=False)
    23. def forward(self, input_ids):
    24. x = self.embed(input_ids)
    25. for block in self.blocks:
    26. x = block(x)
    27. return self.head(self.norm(x))
    28. def build_model():
    29. return TinyLM()
    30. def main():
    31. dist.init_process_group(
    32. backend=os.getenv("TORCH_DIST_BACKEND", "nccl"),
    33. init_method="env://",
    34. )
    35. rank = dist.get_rank()
    36. world = dist.get_world_size()
    37. device_type = "cuda"
    38. device = torch.device(device_type, rank % torch.cuda.device_count())
    39. torch.cuda.set_device(device)
    40. mesh = init_device_mesh(device_type, (world,))
    41. model = build_model().to(device)
    42. fsdp_kwargs = dict(
    43. mesh=mesh,
    44. mp_policy=MixedPrecisionPolicy(
    45. param_dtype=torch.bfloat16,
    46. reduce_dtype=torch.float32,
    47. ),
    48. )
    49. for block in model.blocks:
    50. fully_shard(block, **fsdp_kwargs)
    51. fully_shard(model.embed, **fsdp_kwargs)
    52. fully_shard(model.head, **fsdp_kwargs)
    53. fully_shard(model.norm, **fsdp_kwargs)
    54. fully_shard(model, **fsdp_kwargs)
    55. opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
    56. torch.manual_seed(20250308 + rank)
    57. input_ids = torch.randint(0, 4096, (8, 128), device=device)
    58. loss = model(input_ids).sum()
    59. loss.backward()
    60. opt.step()
    61. opt.zero_grad()
    62. if rank == 0:
    63. print("loss:", loss.item())
    64. print("max_memory_GB:", torch.cuda.max_memory_allocated() / 1e9)
    65. dist.destroy_process_group()
    66. if __name__ == "__main__":
    67. 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:

    1. Count the total checkpoint bytes:
    1. BYTES=$(du -sb /data/ckpt | awk '{print $1}')
    1. Run the load validation with the same nodes, device count, and storage path as training, and record the elapsed time (T_{load}).
    2. Compute throughput:

    [
    Throughput = \frac{Bytes}{T_{load} \times 10^9}
    ]

    1. Repeat 5 times and report P50 and P95.
    2. 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:

    1. torchrun --nproc_per_node=8 minimal_fsdp2.py | tee shard_log.txt
    2. python -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:

    1. export TORCH_NCCL_BLOCKING_WAIT=1
    2. export 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:

    1. 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.
    2. Verify operator by operator: run unit-test comparisons for attention, normalization, and MoE routing operators, and record relative errors.
    3. 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:

    1. import torch
    2. with torch.profiler.profile(
    3. activities=[
    4. torch.profiler.ProfilerActivity.CPU,
    5. torch.profiler.ProfilerActivity.CUDA,
    6. ],
    7. record_shapes=True,
    8. ) as prof:
    9. loss = model(input_ids).sum()
    10. loss.backward()
    11. print(prof.key_averages().table(sort_by="cuda_time_total"))

    Operator unit-test suggestions:

    1. python test_ops.py --op rmsnorm --tol 1e-3
    2. python test_ops.py --op attention --tol 1e-3
    3. python 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:

    1. Compare loss against a single-card or small-cluster pure-DP baseline.
    2. Fix the random seed, data, global batch, initialization, and precision policy.
    3. Keep key operator unit-test errors within the threshold.
    4. Scale up to multi-node, multi-card step by step.
    5. 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.