Building a Distributed Training Pipeline for Large Models on Domestic AI Accelerators: A Practical Guide
This article presents a practical guide to setting up a stable distributed training pipeline for large models on domestic AI accelerators. It covers acceptance criteria for a two-node, sixteen-device validation run, the six core layers of a maintainable training pipeline, data sharding validation, parallel strategy selection, version locking, operator and collective communication troubleshooting, memory and communication optimization, stability monitoring, checkpointing, and checklists for scaling up and pre-release validation.
1. Acceptance Criteria: From Startup to Verification
When migrating large-model training workloads to domestic AI accelerators, the key thing to prove is not peak single-device compute, but whether the entire distributed training pipeline remains stable in a real multi-node, multi-device environment. “Working” does not mean only that the training script starts without errors; it means that data loading, model construction, optimizer initialization, parallel partitioning, cross-device communication, forward and backward propagation, parameter updates, and checkpoint saving all form a complete closed loop.
It is recommended to use “hundreds of continuous training steps on two nodes with sixteen devices” as the minimum acceptance standard. During acceptance testing, focus on four indicators:
- Steps: complete 300-500 continuous training steps without abnormal exits.
- Loss: training loss generally decreases, with no sustained NaN, Inf, or abnormal spikes.
- Throughput: compute utilization and throughput per device remain relatively stable, and communication waits should not dominate for long periods.
- Recovery: training can resume from a checkpoint while keeping the model, optimizer state, data progress, and random state consistent.
Only when all of these conditions are met can we say that basic adaptation among hardware, drivers, the collective communication library, and the training framework has been achieved.
2. Components of a Complete Training Pipeline
A maintainable distributed training pipeline usually consists of six layers:
- Data layer: responsible for sample reading, tokenization, batching, shuffling, and distributed sharding. It must ensure that samples do not overlap or go missing across data-parallel ranks.
- Model layer: responsible for network structure, weight initialization, precision configuration, and parameter partitioning.
- Parallelism layer: determines how data parallelism, tensor parallelism, pipeline parallelism, and optimizer state sharding are combined.
- Communication layer: responsible for gradient synchronization, parameter broadcast, and activation transfer, relying on the collective communication library.
- Optimization layer: manages optimizer state, gradient accumulation, learning-rate scheduling, mixed precision, and loss scaling.
- Fault tolerance layer: responsible for checkpoint saving, resuming from breakpoints, exception recovery, and failure diagnosis.
The data layer especially needs pre-validation. It is recommended to confirm correct data sharding with “global seed + shard index + sample count consistency check”:
# Pseudocode: verify that samples do not overlap or go missing across data parallel ranksglobal_seed = 2025rank = get_rank()world_size = get_world_size()# 1. Build a global sample indexindices = list(range(total_samples))random.Random(global_seed).shuffle(indices)# 2. Shard the index by rankmy_indices = indices[rank::world_size]# 3. Verify the expected sample countexpected_count = len(indices) // world_sizeif rank < len(indices) % world_size:expected_count += 1assert len(my_indices) == expected_count# 4. Optionally sample sample IDs and compare them across ranks to confirm there is no overlap# For example, all_gather the first and last sample IDs of each rank and check for duplicates.
If the data loader does not support deterministic sharding, use the distributed sampler provided by the accelerator vendor or the framework, and save data loading progress to avoid re-consuming samples after resuming training.
3. How to Choose Parallelism Strategies: Principles, Constraints, and Launch Prerequisites
When a single device cannot hold the full model, gradients, and optimizer states, parallel strategies are needed. Common options are:
| Strategy | Communication pattern | Memory benefit | Scope | Common failures |
|---|---|---|---|---|
| Data parallelism | All-reduce gradients during backpropagation | Lower; mainly expands throughput | The model fits on a single device, and scaling nodes improves throughput | Communication timeouts, synchronization failures |
| Tensor parallelism | High-frequency intra-layer communication | High; can partition parameters within a single layer | Usually limited to high-speed intra-node interconnects | Insufficient communication bandwidth, operator mismatch |
| Pipeline parallelism | Transfer activations between adjacent stages | Medium-high; can partition by layers | Many layers and relatively large models | Excessive pipeline bubbles, imbalanced partitioning |
| Optimizer state sharding | Partition and gather gradients/state | High; significantly reduces optimizer memory | Used within data-parallel groups | Inconsistent parameter updates, abnormal memory peaks |
For a two-node, sixteen-device setup, a common combination is “data parallelism 8 x tensor parallelism 2 x pipeline parallelism 1”. The core constraint is:
data_parallel × tensor_parallel × pipeline_parallel = world_size
There is no single correct choice of parallelism degrees. In general, communication-intensive and latency-sensitive dimensions should stay within the high-bandwidth intra-node interconnect range, while dimensions with more controllable communication can be expanded across nodes. After changing parallelism, memory usage, throughput, and numerical consistency must be revalidated.
To ensure reproducibility, lock versions before launch and maintain a matching table:
| Component | Locking requirement | Verification method |
|---|---|---|
| Training framework | Match the accelerator plugin version; record the commit or wheel version | Version check command, image digest |
| Driver/firmware | Use the vendor-recommended version and avoid mixing versions | Vendor tools to query device and driver information |
| Collective communication library | Match the driver, NIC, and topology | Small-scale all-reduce bandwidth test |
| NIC/RDMA | Consistent MTU, GID, routing, and port status | Network status check commands |
| Launch script | Consistent node count, process count, and environment variables | Launch logs and rank binding checks |
The minimum launch command for two nodes and sixteen devices can be adjusted according to the actual framework. Using a common distributed launcher as an example:
torchrun \--nnodes=2 \--nproc_per_node=8 \--node_rank=0 \--master_addr=$MASTER_ADDR \--master_port=29500 \train.py \--data-parallel 8 \--tensor-parallel 2 \--pipeline-parallel 1 \--global-seed 2025 \--output-dir ./checkpoints
On the second machine, change --node_rank to 1. If a launcher provided by the domestic accelerator vendor is used, replace the command with the vendor command, but keep the node count, process count, master address, port, and parallel configuration consistent.
4. Operator and Communication Library Adaptation: Troubleshooting Methods and Thresholds
After moving to domestic AI accelerators, common problems are concentrated in operator fallback, communication timeouts, incorrect topology selection, and precision underflow. When troubleshooting, follow the principle of “start small, scale up, and verify layer by layer”: first run a single-device forward pass, then multi-device gradient synchronization, and then add mixed precision and checkpointing.
1. Single-Layer Numerical Alignment
It is recommended to start with single-layer numerical alignment tests. Use the same weights and the same input batch, run forward and backward passes in a reference environment or a known-good environment, and then compare the outputs with the target accelerator.
Key script points include:
- Fix the random seed to ensure consistent weight initialization.
- Use the same input shape, dtype, and stride.
- Compare forward outputs, input gradients, and parameter gradients.
- Output maximum absolute error, maximum relative error, and gradient norm.
- Record the operator, layer name, rank, dtype, shape, and device ID for each check.
Example log fields:
step=0 layer=block_0 op=attention dtype=bf16 shape=[8,1024,4096] rank=0device=0 max_abs_err=0.0031 max_rel_err=0.0007 grad_norm=12.34comm_op=all_reduce elapsed_ms=8.7 loss_scale=65536
Error thresholds should be adjusted according to the model, operator, and precision mode. The following examples can be used as references:
| Precision mode | Suggested forward error | Suggested backward error |
|---|---|---|
| FP32 | Maximum relative error ≤ 1e-5 | Gradient relative error ≤ 1e-4 |
| BF16 | Maximum relative error ≤ 5e-3 | Gradient relative error ≤ 1e-2 |
| FP16 | Forward relative error ≤ 5e-3 | Gradients must be finite and loss scaling must remain stable |
If one layer’s error clearly exceeds that of other operators in the same layer, or if an operator cannot match the reference result on the target hardware, first inspect the operator implementation, data type conversion, and fused operator fallback paths.
2. Communication Adaptation and Common Errors
The collective communication library needs to match the framework, driver, NIC, and topology. Common problems include:
- all-reduce timeouts: check NIC status, port connectivity, NCCL-like communication library logs, MTU, and routing.
- Low bandwidth utilization: check topology selection, ring/tree configuration, and whether cross-node communication paths are suboptimal.
- Communication group initialization failures: check whether rank, world_size, node_rank, and master_addr are consistent.
- Performance drops caused by operator fallback: check logs for fallback, unsupported, or generic implementation messages.
- Precision underflow: check whether loss scaling is effective and whether gradients are continuously zero or Inf.
For communication troubleshooting, first run small-scale communication benchmarks, scaling gradually from 2 devices to 8 devices and then 16 devices. Observe bandwidth, latency, and error rates before entering real training.
5. Memory and Communication Optimization: Formulas, Configurations, and Corrections
The goal of memory and communication optimization is to improve throughput and reduce per-device memory pressure while maintaining numerical stability. Common methods include:
- Activation recomputation: discard intermediate forward results and recompute them during backpropagation, significantly reducing activation memory.
- Gradient accumulation: use smaller micro-batches to accumulate and simulate a larger global batch, relieving memory pressure.
- Mixed precision: compute in lower precision while maintaining master weights and optimizer states in higher precision.
- Communication and computation overlap: overlap gradient synchronization with backward computation to reduce waiting.
- Joint tuning of batch size and parallelism: avoid mismatches between the number of micro-batches and pipeline scheduling.
The global batch size can be estimated as:
global_batch = micro_batch_size × gradient_accumulation × data_parallel
A common misconception needs correction here: it is not that “micro-batch size must be divisible by the pipeline parallel degree”; rather, “the number of micro-batches or the global batch schedule must be divisible by the pipeline parallel degree”. In pipeline parallelism, if each global batch produces too few micro-batches, or even fewer than the number of pipeline stages, some stages cannot remain busy continuously and must wait for other stages to fill the pipeline, creating bubbles. Bubble ratio can increase significantly, causing accelerators to remain idle. In general, it is recommended that the number of micro-batches be greater than the pipeline parallel degree and, preferably, divisible by it for more balanced scheduling.
An illustrative configuration:
train_cfg = {"micro_batch_size": 1,"gradient_accumulation": 16,"data_parallel": 8,"pipeline_parallel": 1,"tensor_parallel": 2,"precision": "bf16","activation_checkpoint": True,"loss_scale": "dynamic",}# global_batch = 1 * 16 * 8 = 128# If pipeline_parallel = 4, ensure the micro-batch count or scheduling can be divided by 4.
Mixed-precision training also needs exception handling. If Inf, NaN, or continuously decreasing loss scaling appears in multiple consecutive training steps, the system should automatically skip the current update, fall back to a higher precision mode, or reduce the learning rate and log a warning. It should not silently continue training.
6. Training Stability: Metrics, Monitoring Frequency, and Anomaly Criteria
“Being able to run” is only the passing line; “running correctly” is the real goal. It is recommended to establish a continuous monitoring loop covering at least loss, gradient norm, throughput, communication ratio, and utilization.
| Metric | Suggested frequency | Healthy reference | Anomaly action |
|---|---|---|---|
| Loss | Record every step | Smooth decline | Stop immediately on NaN/Inf; if loss does not decline for 20 consecutive steps or increases significantly, check learning rate, data, and mixed precision |
| Gradient norm | Every step or every 10 steps | Fluctuate near the baseline | If it exceeds 10 times the baseline or shows spikes, check gradient clipping, learning rate, and abnormal samples |
| Communication ratio | Every 50-100 steps | Long-term below 30% | If it remains above 30% for a long time, check parallelism strategy, communication library, topology, and data loading |
| Compute utilization | Sample every 500 ms or aggregate from logs | Above 70% most of the time | If it remains below 70% for a long time, check the data pipeline, pipeline bubbles, and communication blocking |
| Peak memory | Every 100 steps or at key phases | Close to but below the limit | If OOM occurs frequently, enable activation recomputation, optimizer state sharding, or reduce the micro-batch |
These thresholds are engineering examples and should be adjusted according to model size, hardware generation, cluster topology, and task goals. More importantly, establish a baseline: record metrics from the first stable run under the same model, data, and parallel configuration, and compare later training runs against this baseline.
Long-running training must save complete checkpoints. A checkpoint should include model weights, optimizer state, learning-rate scheduler state, random seeds, data loading progress, and the global step count. For machine scaling, migration, or large-scale training, back up critical checkpoints in advance and prepare rollback plans to avoid wasting days of compute due to a single exception.
7. Scaling Up from Hundreds of Steps: Pre-Scaling Checklist
After completing several hundred steps of validation on two nodes with sixteen devices, run the following checks before scaling up:
- Confirm that the current configuration has already run stably for hundreds of consecutive steps and that baselines exist for loss and throughput.
- Confirm that checkpoints can be fully restored, including the model, optimizer, random seeds, and data progress.
- Confirm that data sharding remains non-overlapping and complete under the new world_size.
- Confirm that the learning-rate schedule has been recalibrated after the global batch size changes with data parallelism.
- Confirm that driver, firmware, communication library, and framework versions on new nodes match those on existing nodes.
- Confirm that the collective communication library has passed bandwidth and latency tests under the new topology.
- Confirm that monitoring, alerting, log collection, and automatic restart policies cover the new scale.
- After scaling up, first run a small-scale validation for dozens of steps, then resume long-running training.
8. Pre-Release Best Practices Checklist
- The parallel configuration satisfies: data parallelism × tensor parallelism × pipeline parallelism = total number of processes.
- Framework, driver, collective communication library, and NIC firmware versions are locked and verified.
- The data layer supports a global seed, shard indexes, and sample count consistency checks.
- Operator adaptation includes single-layer forward and backward numerical alignment, with error logs recorded.
- Communication adaptation includes small-scale all-reduce benchmarks with no timeouts or abnormal bandwidth.
- Mixed-precision configuration includes loss scaling and exception handling thresholds.
- Under pipeline parallelism, the micro-batch count or scheduling can be divided by the pipeline parallel degree, avoiding excessive bubbles.
- Checkpoints cover the model, optimizer, random seeds, data progress, and global step count.
- Monitoring metrics include loss, gradient norm, throughput, communication ratio, and utilization.
- Critical checkpoints are backed up before scaling or restarting, and a rollback path is prepared.
In the end, getting a large-model distributed training pipeline working on domestic AI accelerators is not about peak performance at a single point. It tests the stable, system-level coordination of hardware, drivers, communication libraries, and training frameworks. Making the pipeline runnable, correct, and stable, and turning it into a reusable, monitorable, and rollback-capable engineering process, is the reliable starting point for scalable autonomous training.
