Getting a MoE LLM Training Pipeline Running on Two Nodes with 16 GPUs
A recent demonstration on a domestic accelerator platform validated the training of a trillion-parameter-scale MoE (Mixture-of-Experts) model on 16 GPUs across two nodes, completing 400 steps without interruption. Using this event as a starting point, this article takes a neutral look at the key steps and common pitfalls of bringing up large-model training pipelines on non-mainstream hardware, and lays out a practical, layered approach: first get the pipeline running, then running correctly, then running stably, and finally make it fast. It covers environment and communication baselines, parallel strategies and memory budgeting, MoE-specific challenges such as expert parallelism and routing, operator adaptation and numerical alignment, performance profiling, and fault tolerance, and finally how to scale from a 16-GPU validation up to larger clusters.
Recently, a domestic accelerator card platform announced that it had completed a training validation of a trillion-parameter-scale MoE (Mixture-of-Experts) large model in a two-node, 16-GPU environment. The run trained stably for 400 steps on 16 GPUs with no interruptions. The point of interest here is not the parameter scale itself, but that it serves as a check on the maturity of the end-to-end training pipeline on non-mainstream hardware.
For engineering teams, the most valuable takeaway is not the conclusion but the general methodology it implies: first get the pipeline running, then get it running correctly, then get it running stably, and finally make it fast. Using this event as a starting point, this article takes a neutral look at the key steps and common pitfalls of bringing up large-model training pipelines on domestic compute, and offers a practical implementation path.
1. Why Run 400 Steps on 16 GPUs First
A large-model training pipeline is a chain of stages: data loading, forward computation, backward propagation, gradient synchronization, parameter updates, and state saving. A defect in any one stage gets amplified many times over at large scale. Common failures include:
- Multi-node communication timeouts that hang the job;
- Numerical anomalies that cause loss divergence;
- Single-card failures that force a global restart.
These failures are cheapest to expose at small scale; at large scale, the cost is hours or even days of GPU time. So before committing to a larger allocation, completing one full validation round on two nodes with 16 GPUs is a pragmatic choice. This scale usually corresponds to the classic “8 GPUs per node × 2 nodes” configuration, and is enough to cover the vast majority of engineering issues:
- It runs: the full chain of data loading, forward, backward, optimizer update, and weight saving/loading works without errors.
- It runs correctly: the loss curve matches expectations, with no NaNs, gradient explosion, or persistent oscillation.
- It runs stably: hundreds of consecutive steps with no crashes, no memory leaks, and no communication hangs.
- It runs cleanly: per-step time can be broken down and bottlenecks located, establishing a baseline for scaling up later.
400 steps may seem small, but it is enough to cover key paths such as learning-rate warmup, the first activation of gradient clipping, log aggregation windows, and multiple weight saves—a cost-controlled “smoke test.” It should be clear that this is engineering validation, not convergence validation. Whether the model converges ultimately depends on longer training runs.
2. The Four Layers of the Pipeline and the Order to Bring Them Up
Domestic training adaptation can be broken into four layers. Bringing them up bottom-up, layer by layer, is safer than chasing end-to-end acceleration from the start:
| Layer | Core task | Common failures | Key output |
|---|---|---|---|
| Hardware and driver layer | Card health, topology, consistent driver and firmware versions | Cards dropping, ECC errors, version mismatches | Health baseline, network topology map |
| Framework and operator layer | Framework adaptation, operator coverage, precision alignment | Missing operators, result drift, overflow | Operator support matrix, precision report |
| Parallelism and algorithm layer | Parallel strategy, memory budget, communication optimization | Memory overflow, communication bottleneck, load imbalance | Optimal parallel plan, per-step baseline |
| Cluster and operations layer | Data pipeline, checkpoints, fault tolerance, monitoring | Data starvation, inability to resume after failure | A recoverable training flow |
The bring-up order follows the principle of “bottom-up, layer-by-layer validation”:
- First get single-card training running on one card;
- Then scale to 8 cards on a single node, validating intra-node communication;
- Finally scale to 16 cards across two nodes, validating inter-node communication and distributed checkpoints.
Each layer should leave a quantifiable baseline—for example, per-card memory usage, per-step time, and measured bandwidth. When an upper layer has a problem, you can compare directly against the baseline to determine whether the issue lies in this layer or the one below.
3. Step 1: Environment and Communication Baseline Self-Check
Many “model won’t run” problems do not originate in the model but in the environment. Before training, it is a good idea to run a self-check script covering:
- Driver and firmware versions consistent across all nodes;
- Accelerators visible and healthy, with no ECC errors or temperature alarms;
- High-speed network connectivity, with inter-node bandwidth in a reasonable range of the nominal level.
The schematic code below shows the idea; replace the specific commands with the ops tooling for your target platform:
#!/usr/bin/env bash# Pre-training environment self-check (schematic): command names and arguments# must be adjusted to the target platform's ops tooling.set -euo pipefailNODES=(node-a node-b) # list of the two nodesfor node in "${NODES[@]}"; doecho "===== ${node} ====="ssh "${node}" "<device-mgmt-tool> --query=driver_version,firmware_version,ecc_errors,temperature" # versions and card healthssh "${node}" "<device-mgmt-tool> -- topo -m" # intra-node interconnect and affinity topologydone# Collective communication baselines: AllReduce for data parallelism, All2All for expert parallelism<node_label> <AllReduce_benchmark> -b 8M -e 4G -f 2 -g 8<node_label> <All2All_benchmark> -b 8M -e 4G -f 2 -g 8
When testing communication, measure intra-node interconnect bandwidth on a single node and inter-node bandwidth across two nodes. When results differ significantly from nominal values, prioritize investigating the driver, NIC configuration, and network links, rather than tuning the parallel strategy first.
3.1 Understanding the Interconnect Hierarchy
Multi-card training performance is largely determined by the communication hierarchy:
- Intra-node high-speed interconnect: between GPUs within the same node, high bandwidth and low latency;
- Host-to-card data path: affects how fast data moves from host memory to device memory;
- Inter-node network: generally provides high-bandwidth, low-latency RDMA-class communication.
Designing a parallel strategy is essentially about placing the dimensions with the heaviest communication on the highest-bandwidth links.
3.2 Reasonable Rank Placement
For a 2-node × 8-card setup:
- Keep tensor parallel groups within a single node;
- Keep expert parallel groups within a node as much as possible;
- Across nodes, keep only dimensions with regular communication patterns, such as point-to-point transfers between pipeline stages and data-parallel gradient synchronization.
If parallel groups are mismatched with the physical topology, all performance optimization becomes a lot of wasted effort.
4. Step 2: Parallel Strategy and Memory Budget
4.1 Common Parallelism Dimensions
Large-model training usually combines multiple forms of parallelism:
- Data parallelism (DP): each data-parallel group processes a different data slice, with gradients synchronized between groups;
- Tensor parallelism (TP): splits matrix multiplications across cards by row or column, requiring reductions in both forward and backward passes;
- Pipeline parallelism (PP): splits the model into stages by layer, passing activations between stages point-to-point;
- Expert parallelism (EP): distributes different experts of an MoE model across cards, with a routing mechanism deciding where tokens go;
- Sequence/context parallelism (SP/CP): splits along the sequence dimension to relieve activation memory pressure under long context;
- Optimizer state sharding: shards optimizer state across the data-parallel group to reduce per-card resident memory.
What makes MoE special is that each token activates only a small fraction of the total parameters, so compute scales with the number of activated parameters. This makes the memory and communication challenges more pronounced than for dense models:
- The total number of expert parameters is large, and optimizer states take up a lot of memory;
- Routing introduces dynamic, unbalanced communication.
4.2 Memory Budget Estimation
Before designing a parallel plan, it is worth doing a memory budget first. Taking the Adam optimizer, common in training frameworks, as an example, the resident memory per parameter mainly includes:
| Component | Precision | Bytes |
|---|---|---|
| Weight | 16-bit float | 2 |
| Gradient | 16-bit float | 2 |
| Master weight copy | 32-bit float | 4 |
| First moment | 32-bit float | 4 |
| Second moment | 32-bit float | 4 |
| Total | — | ~16 |
That is, with no sharding at all, each parameter needs about 16 bytes of resident memory, plus the overhead of activations, communication buffers, and memory fragmentation.
A sample estimation function (numbers are empirical estimates only; actual values should be based on measurements on the target hardware):
# Memory budget estimation (schematic, not measured data)# base_total: total model parameters; activated: parameters activated per tokendef estimate_memory_gib(base_total, activated, batch, seq_len, layers, hidden,tp=1, pp=1, ep=1, dp=1, recompute=False):bytes_per_param = 16 # weight + grad + fp32 master + 1st moment + 2nd moment# Activated parameters are split by tensor/expert parallelism; total params by pipeline stagesact_local = activated / (tp * ep) * ppbase_local = base_total / (tp * ep) * ppresident = (act_local + base_local) * bytes_per_param / (1 << 30)# Activation estimate: per-layer intermediates; greatly reduced with recomputationact_factor = 0.2 if recompute else 1.0activation = batch * seq_len * hidden * layers * 2 * act_factor * pp / (1 << 30)buffer_gb = 4.0 # reserve for communication buffers and fragmentationtotal = resident + activation + buffer_gbreturn {"resident(GB)": round(resident, 1),"activation(GB)": round(activation, 1),"total(GB)": round(total, 1),}
This model is only for order-of-magnitude judgment; real trade-offs depend on measurements. For example, for an MoE model whose activated parameters are about one-tenth of the total, at 16 cards, both of the following configurations are viable:
- Coarse model sharding: tp=8, pp=2, dp=1, with activation recomputation enabled;
- Optimizer state sharding: tp=4, ep=2, dp=2, combined with optimizer state sharding.
The former has simple communication and small pipeline bubbles, suitable for small-scale validation; the latter has lower per-card resident memory and better scalability, suitable for scaling up later. During validation, prefer the configuration that is simple and has few failure points, leaving complexity for the scaling stage.
4.3 Sample Parallel Configuration
# Sample parallel configuration for the training job; tune values against measurementsconfig = {"tensor_model_parallel_size": 8, # tensor parallel group confined within a single node"pipeline_model_parallel_size": 2, # two machines each take one pipeline stage"expert_model_parallel_size": 1, # can be left off during validation, enabled after scaling up"recompute_activations": True, # trade compute for memory"micro_batch_size": 1,"global_batch_size": 512, # determined by micro_batch x grad accumulation x data parallel size"bf16": True, # prefer bf16 for 16-bit float; larger dynamic range}
5. Step 3: Three MoE-Specific Challenges
5.1 Expert Parallelism and All2All Communication
With expert parallelism enabled, each step requires two All2All communications:
- Dispatch: the routing layer sends each token to the card hosting its target expert;
- Combine: after expert computation, the results are sent back to the token’s original card.
Unlike AllReduce’s regular, fixed communication volume, All2All’s data volume depends on routing results and is prone to link hotspots and load skew. Common mitigations include:
- Use a capacity factor to cap the number of tokens a single expert accepts;
- Add a load-balancing auxiliary loss to make routing more uniform;
- Overlap dispatch communication with preceding computation;
- Keep expert parallel groups within a node to avoid cross-node All2All.
5.2 Numerical Sensitivity of the Routing Layer
MoE models are fairly sensitive to the numerical precision of the routing layer. Top-k selection is a discrete operation, and a tiny numerical drift can change expert assignment and thus the results of the whole chain. Recommended practice:
- Compute routing scores (e.g., softmax and top-k) in 32-bit float, while expert computation uses 16-bit float;
- Scale the load-balancing loss and auxiliary losses separately to avoid gradient magnitude imbalance.
5.3 Load Balancing and Capacity Factor
Early in training, routing tends to quickly concentrate on a few experts. Setting the capacity factor too small drops a large number of tokens, while setting it too large drives up memory and communication overhead; it generally needs to be tuned up gradually starting from around 1.0–1.25. At the same time, track “the standard deviation of tokens received per expert” and “the fraction of dropped tokens”—these are important signals for judging MoE training health.
6. Step 4: Operator Adaptation and Numerical Alignment
6.1 Operator Coverage Matrix
How mature a domestic accelerator’s software stack is largely reflects in operator coverage. It is worth mapping out an operator support matrix by category:
| Operator category | Typical operators | Adaptation focus |
|---|---|---|
| Linear algebra | Matrix multiply, batched matrix multiply | Tile sizes, accumulation precision |
| Normalization | Layer norm, RMS norm | Reduction precision, backward implementation |
| Attention | Attention kernels, masking, positional encoding | Long-sequence, variable-length input support |
| Routing | gather/scatter, top-k | Dynamic shapes, index stability |
| Optimizer | Adaptive moment estimation optimizers | 32-bit master weights, fused implementation |
Support status can be divided into four levels: natively supported, fallback available, unsupported, and needs custom implementation. Fallback paths determine the performance floor; unsupported operators determine the adaptation workload.
6.2 Layer-by-Layer Numerical Alignment
Never leave precision issues to be discovered only at end-to-end training. The recommended approach is to compare layer by layer, from “single operator → single layer → small model → full model”: run the same input on another validated reference environment, compare output errors, and set clear thresholds.
# Layer-by-layer numerical alignment (pseudo-code)def check_layer_parity(layer, x, ref_out, atol=1e-3, rtol=1e-3):out = layer(x)# Element-wise comparison; report max absolute and relative errormax_diff = max_abs(out - ref_out)assert within_tolerance(out, ref_out, atol, rtol), \f"{layer.name} exceeds alignment threshold: {max_diff}"return max_diff
6.3 Understanding Error Sources
In parallel training, gradients from all data-parallel ranks are ultimately summed onto the same parameter copy. Floating-point addition is not associative, so different reduction orders produce tiny differences—requiring bit-exact agreement across all cards is unrealistic. A more reasonable engineering criterion is:
- The overall trend of the loss curve matches the reference environment;
- Under the same data order and random seed, numerical deviations stay within an acceptable range;
- No persistent NaN or Inf appears.
If you suspect an operator itself has a problem, reproduce the same computation in single precision and check whether the error converges.
7. Step 5: Performance Profiling and Tuning
7.1 Per-Step Time Breakdown
The core metric for training efficiency is MFU (Model FLOPs Utilization)—the ratio of the effective compute actually achieved in training to the hardware’s theoretical peak compute. For MoE models, it can be roughly estimated as:
MFU ≈ (6 × activated parameters × tokens processed per step) / (cards × per-step time × per-card peak compute)
Here, 6 is the empirical factor for 2 forward and 4 backward multiply-adds, used only for quick estimation and not counting extra computation such as attention.
When MFU is low, break per-step time into computation, communication, data waiting, recomputation, optimizer, and so on, to find the real bottleneck:
# Segment timing for per-step time (schematic)timers = {"data": Timer(), # data loading"forward": Timer(), # forward"backward": Timer(), # backward"comm": Timer(), # gradient sync and expert communication"step": Timer(), # parameter update}
7.2 Tuning Order
Tuning should follow the order of “first remove stalls, then compress communication, and finally optimize operators”:
- Data pipeline: increase read threads and prefetch depth, move data processing to offline preprocessing, so data loading does not slow down computation.
- Communication: overlap gradient reduction with backward computation; keep tensor parallelism within nodes; group and overlap All2All.
- Operators: locate the few operators with the largest share and prioritize fusing them or replacing them with native implementations.
- Parallelism and hyperparameters: tune micro-batch size, gradient accumulation steps, and recomputation granularity to balance throughput and memory.
Schematic code:
# Overlapping communication with computation (schematic)with overlap_context(): # trigger gradient reduction per bucket during backwardloss.backward()finalize_grad_sync() # complete remaining sync before backward ends
| Symptom | Possible cause | Investigation |
|---|---|---|
| Low and fluctuating card utilization | Data loading is the bottleneck | Segment timing, observe data-wait share |
| Per-step time rises instead of falling as cards increase | Cross-node communication is the bottleneck | Compare single-node vs. two-node baselines, check parallel group placement |
| Memory keeps growing | Cache not released or checkpoint memory copy | Observe memory curve, check saving logic |
| Loss jumps suddenly | Learning rate too high, numerical overflow | Observe gradient norm, enable skipping anomalous steps |
8. Step 6: Fault Tolerance and Observability
8.1 Distributed Checkpoints
A checkpoint should save not just model weights but also optimizer states, learning-rate scheduler state, random number state, and the data-reading position; otherwise resuming training produces loss jumps and inconsistent training trajectories. Large-model checkpoints often run into hundreds of GB, and writing them synchronously blocks training for a long time. A common approach is to save in shards and write asynchronously to shared storage in the background.
8.2 A Fault-Tolerant Training Loop
# Fault-tolerant training loop (schematic)global_step = 0while global_step < total_steps:try:loss = train_step(dataloader)global_step += 1if global_step % log_interval == 0:metrics.report("loss", loss)metrics.report("grad_norm", grad_norm())if global_step % save_interval == 0:save_checkpoint_async(global_step) # sharded + async saveexcept (DeviceError, CommTimeout) as err:metrics.report("fault", str(err))global_step = load_checkpoint(latest_checkpoint()) # auto-resumetime.sleep(restart_backoff)
8.3 Observability Metrics
| Metric | Purpose |
|---|---|
| Loss and gradient norm | Judge convergence and numerical stability |
| Per-step time and MFU | Detect performance regressions |
| Memory usage and fragmentation | Anticipate memory overflow |
| Card temperature and ECC errors | Detect hardware hazards |
| Expert load and drop rate | Judge MoE routing health |
| Checkpoint time and size | Assess disaster-recovery overhead |
These metrics can be wired into general logging services and monitoring/alerting systems, with threshold alerts configured, so problems are caught before they waste large amounts of GPU time.
9. From 16-GPU Validation to Scaling Up
Passing 16-GPU validation is just the starting point. When scaling to dozens of cards or more, the following problems appear in concentrated form:
- Hierarchical communication: at larger scale, techniques such as optimizer state sharding and layered data-parallel group placement significantly affect scaling efficiency.
- Elastic fault tolerance: in large-scale training, single-card failures are almost inevitable, requiring finer-grained checkpoints, auto-resume, and fault isolation.
- Job orchestration: training jobs should run containerized, with a cluster scheduler managing resources and priorities.
- Storage architecture: datasets are best placed in object storage or a parallel file system, with local caching, to reduce bandwidth pressure when many nodes read.
If training runs on a cloud platform such as Baidu AI Cloud, the above capabilities can be combined as general capability categories:
- Container clusters host training jobs;
- Object storage holds datasets and checkpoints;
- Logging services and monitoring/alerting track runtime state and hardware health.
This reduces infrastructure operations overhead while letting the team focus on tuning the training itself.
10. Summary
A domestic accelerator platform completing a 400-step training validation on 16 cards across two nodes is essentially an engineering practice of “first make it run, then make it good.” For developers, a few key points can be distilled:
- Self-check first: without passing environment and communication baselines, subsequent optimization is moot;
- Do the math: use memory budgets to decide the parallel plan, then iterate in small steps;
- Align properly: align operators layer by layer so precision issues surface early and get resolved early;
- Read the numbers: use MFU and segment timing to locate bottlenecks, rather than tuning parameters blindly;
- Cover the basics: checkpoints, fault tolerance, and monitoring are all indispensable.
Adapting large-model training to domestic compute is a systems-engineering effort, and a single validation is only the start. Only by producing quantifiable baselines at every layer and continuously iterating through scaling can “being able to run” truly become “being able to train stably and efficiently over the long term.”
