Domestic AI Accelerator Training Adaptation: Two Nodes, 16 Cards, 400 Steps Verified

    This article presents a practical, layered method for adapting large language model training to a domestic AI accelerator. It explains how to define acceptance criteria, validate environment and operator compatibility, choose parallel strategies, align numerical behavior with a baseline, compare convergence on small and medium models, and verify stability through a two-node, 16-card, 400-step test. It also includes configuration examples, metrics to monitor, troubleshooting guidance, and engineering practices for repeatable hardware adaptation.

    1. Making the Training Path Work Is Harder Than Lighting Up the Card

    Hardware adaptation for large model training is often reduced to whether the model can be loaded onto an accelerator and produce the first loss value. The harder engineering problem is making the entire training path work end to end. At minimum, this includes four layers:

    • Environment layer: Drivers, runtime, communication libraries, training frameworks, and dependencies must be version-aligned.
    • Operator layer: Forward and backward operators used by the framework must be covered, and fused operators must be numerically reliable.
    • Communication layer: Collective communication for data parallelism, tensor parallelism, pipeline parallelism, and expert parallelism must complete correctly and efficiently.
    • Stability layer: Over hundreds of steps or longer, the loss curve must remain controllable, and checkpoints must be saved and restored correctly.

    If any link in this chain is missing, training may not start at all, or it may start but produce incorrect results.

    Recently, a China-developed AI accelerator card completed the training adaptation of a long-context large language model and finished a 400-step validation run on two nodes with 16 cards. This result shows that the migration path from mainstream large-model training frameworks to China-developed hardware is gradually becoming viable.

    Using this validation process as a guide, this article abstracts a reusable adaptation method: how to define acceptance criteria, how to troubleshoot compatibility layer by layer, and how to validate convergence and stability under limited resources.

    2. Core Principles: Correctness, Stability, Efficiency in That Order

    A common mistake in hardware adaptation is to reverse the priority order: starting with maximum throughput and fused operators, only to discover later that the model does not converge.

    A reasonable priority order is:

    1. Correctness: With the same inputs, random seed, and data order, the loss, gradients, and parameter updates on the accelerator should match the baseline. The baseline usually means the same model and hyperparameters run on a mature training stack.
    2. Stability: Over hundreds of steps, there should be no loss spikes, no gradient explosions, no communication hangs, and checkpoints should save and restore correctly.
    3. Efficiency: Only after the first two are satisfied should teams optimize operator fusion, parallelism partitioning, and communication overlap.

    Efficiency optimization is meaningful only when the baseline is reliable. Performance tuning performed before convergence is verified produces meaningless speedup numbers.

    3. Main Adaptation Challenges for a Long-Context Large Language Model

    For a typical long-context large language model, the adaptation challenges can be grouped into five categories. The exact characteristics depend on the actual model configuration.

    • Large model size and tight memory: As the parameter count grows, it becomes harder for a single card to hold the full model, gradients, and optimizer states. Parallel partitioning and memory optimizations are required.
    • Long-context attention bottleneck: As sequence length increases, intermediate tensors in attention computation grow quickly. If a fused attention kernel is used, its numerical behavior on the accelerator must be verified, especially for long sequences.
    • MoE structures introduce expert parallelism: Sparse activation models must route tokens across cards. The all-to-all operation in collective communication is sensitive to interconnect bandwidth, and load imbalance can create a bucket effect where the slowest path limits overall progress.
    • High precision requirements: These models usually use mixed-precision training. Different precision modes have different sensitivities to overflow and accumulated error, so precision modes cannot be switched blindly.
    • Complex parallelism combinations: When multiple parallelism methods are stacked, communication paths cross in complex ways. A mismatch in any communication path between two dimensions may appear as an occasional loss anomaly or a process hang.

    4. Overall Adaptation Workflow: Six Stages

    The adaptation work can be divided into six stages. Teams should move to the next stage only after the previous stage passes acceptance.

    1. Environment alignment: Unify the base image, dependency versions, and hardware information.
    2. Operator compatibility: Check operator coverage and numerical correctness item by item.
    3. Parallel strategy: Decide how to combine tensor parallelism, pipeline parallelism, expert parallelism, and data parallelism.
    4. Numerical consistency: Align results with the baseline on a small-scale model.
    5. Convergence comparison: Compare loss curves with the baseline using a medium-scale model.
    6. Stability validation: Complete the target validation, such as a 400-step run on two nodes with 16 cards.

    5. Environment Alignment: Make “Can Run” Reproducible

    A common waste of time during adaptation is getting different results in different environments. A strange problem that takes hours to investigate may simply come from version mismatch.

    At minimum, teams should lock down and record the following information in the repository README or CI configuration:

    • Base image version
    • Driver, runtime, and communication library versions
    • Training framework, plugins, and dependency versions
    • Hardware model and interconnect topology
    • Key environment variables

    An example inventory looks like this:

    1. # Environment inventory example: all fields should match the actual environment.
    2. image: <base image identifier>
    3. driver: <driver version>
    4. runtime: <hardware runtime version>
    5. comm_library: <collective communication library version>
    6. framework: <training framework and plugin versions>
    7. device: <accelerator card model>
    8. topology: <intra-node interconnect / inter-node network type>

    After fixing the environment, run device and runtime self-checks first:

    1. # Pseudocode: module names are placeholders; refer to the actual platform documentation for APIs.
    2. import hwrt as rt # Hardware runtime interface (placeholder)
    3. print("Number of visible devices:", rt.device_count())
    4. print("Device name:", rt.get_device_name(0))
    5. print("bf16 supported:", rt.is_dtype_supported("bf16"))
    6. print("Peer direct access:", rt.can_access_peer(0, 1)) # Check whether cards can communicate directly.

    Collective communication should also be tested separately:

    1. import hwrt as rt
    2. import time
    3. n = 8
    4. size = 64 * 1024 * 1024 # Buffer size per rank in bytes.
    5. buf = rt.empty(n, size) # Allocate buffers on each rank and fill them with non-zero data.
    6. rt.distributed.all_reduce(buf)
    7. rt.sync() # Warm up to exclude first-call overhead.
    8. t0 = time.perf_counter()
    9. for _ in range(20):
    10. rt.distributed.all_reduce(buf)
    11. rt.sync()
    12. elapsed = (time.perf_counter() - t0) / 20
    13. # Bus bandwidth reflects communication payload and data size.
    14. # When comparing with hardware specifications, use bus bandwidth rather than algorithm bandwidth.
    15. busbw = 2 * (n - 1) / n * size / elapsed
    16. print(f"all_reduce bus bandwidth: {busbw / 1e9:.2f} GB/s")

    It is recommended to test primitives such as all_reduce, all_gather, reduce_scatter, and all_to_all separately for intra-node and cross-node scenarios. If measured bandwidth is clearly lower than expected, prioritize checking interconnect configuration, NIC drivers, and routing settings instead of immediately suspecting the framework itself.

    6. Operator Compatibility: Layered Validation and Fallback Strategy

    6.1 Three-Layer Validation

    Error messages such as “operator not supported” often point only to the surface. Teams should locate the issue layer by layer:

    • Layer 1: Framework operator library. Check whether the operator implementations selected by the framework, such as attention, normalization, and cross-entropy, have corresponding implementations on the accelerator.
    • Layer 2: Vendor operator library. Check whether the optimized operators provided by the hardware vendor cover all interfaces and parameter combinations used by the model, such as different data types, masked operations, and variable-length sequences.
    • Layer 3: Custom kernels. Fused operators introduced for efficiency often depend on a specific compute backend. In this case, either switch to the vendor-provided implementation or compose an equivalent implementation from basic operators.

    Teams should also distinguish three types of failure:

    • The operator is completely missing and reports “not implemented”.
    • The operator exists, but a specific parameter combination is unsupported and only fails under certain configurations.
    • The operator runs, but the numerical result is incorrect. This is the most hidden case and can only be detected through numerical validation.

    6.2 Unit-Level Numerical Validation

    For critical operators, run fixed inputs on both the baseline and the accelerator, then compare the relative error of forward outputs and backward gradients. The following is a single-point validation example:

    1. # Single-point numerical validation using a linear layer as an example.
    2. import hwrt as rt
    3. import numpy as np
    4. rt.manual_seed(42)
    5. x = rt.randn(4, 128)
    6. w = rt.randn(128, 256)
    7. ref = rt.matmul(x, w) # Reference implementation.
    8. got = rt.matmul_opt(x, w) # Vendor optimized implementation. API name is a placeholder.
    9. diff = rt.max(rt.abs(ref - got)) / (rt.max(rt.abs(ref)) + 1e-8)
    10. print(f"Maximum forward relative error: {diff:.2e}")
    11. gx = rt.grad(rt.matmul_opt, x, w)
    12. assert rt.max(rt.abs(gx)) > 0 # Backward gradients should not be all zeros.

    A more thorough approach is to use unit tests that cover parameter combinations such as data types, shapes, masks, and sequence lengths. These tests can become a regression suite and be rerun automatically whenever the runtime or operator library is upgraded.

    6.3 Prioritized Fallback

    Fixing an operator is not always the first choice. During early adaptation, teams can use the following priority order:

    1. Use the corresponding implementation provided by the vendor.
    2. Compose an equivalent computation from basic operators.
    3. Switch to the framework’s generic implementation, which usually has the worst performance.

    Fallback options should be recorded as configuration items so they can be replaced one by one and revalidated later.

    7. Parallel Strategy: Keep Communication on the Right Path

    7.1 Basic Combinations

    Parallelism Role Communication Characteristics Deployment Recommendation
    Data Parallelism (DP) Replicates the model and splits the data Gradient reduction; communication volume depends on parameter size Use first for scale; can be combined with sharding schemes
    Tensor Parallelism (TP) Splits matrix computation within a single layer Communication is required before and after each layer; frequent and sensitive Place within the intra-node high-speed interconnect domain
    Pipeline Parallelism (PP) Splits layers across devices Point-to-point transmission of activations and gradients; can overlap with computation Can span nodes; requires micro-batch scheduling
    Expert Parallelism (EP) Distributes experts across devices All-to-all routing; bandwidth-sensitive and possibly load-imbalanced Tune expert placement and capacity factor together

    When a single card cannot hold the full model, gradients, and optimizer states, teams can consider sharded data parallel approaches, often referred to as ZeRO/FSDP-style methods. These approaches distribute parameters, gradients, and optimizer states across data parallel replicas, trading communication for memory.

    7.2 Partitioning Principles

    • TP groups should be placed within the same node whenever possible to use high-bandwidth intra-node interconnect.
    • PP stage partitioning should balance computation across stages; otherwise, pipeline bubbles will slow down the whole run.
    • EP communication crosses TP and DP. Teams should confirm that the communication library supports the required multi-dimensional communication groups.
    • Parallel degrees must match available resources. For example, with two nodes and 8 cards per node, setting TP to 8 or less is usually easier to place within a node. A very large DP degree amplifies communication overhead.

    7.3 Validation Methods

    1. Collective primitive correctness: Construct predictable data and verify that each primitive produces the expected result.
    2. Topology-aware comparison: Compare with the baseline under the same or similar parallel configuration. Focus on the loss curve rather than throughput alone.
    3. Parameter sensitivity: After changing the parallelism degree, the loss curve should remain consistent. Inconsistency usually points to communication or partitioning logic issues.

    8. Numerical Consistency: Align on a Small Model First

    Comparing loss curves directly on a large model is expensive and difficult to debug. It is better to start with a small 2-to-4-layer model trained on a TinyStories-style small story corpus. This type of corpus is simple and regular, and it can show clear convergence within minutes.

    Teams should fix the random seed, data order, and initialization parameters so that the accelerator and the baseline see exactly the same input sequence. An example is shown below:

    1. # Small-scale numerical consistency test (pseudocode)
    2. def run_baseline(steps=20):
    3. set_seed(42) # Fix all sources of randomness, including initialization and dropout.
    4. model = build_model(cfg).train()
    5. losses = []
    6. for step in range(steps):
    7. batch = get_batch(step) # Use a fixed data order identical to the accelerator run.
    8. loss = cross_entropy(model(batch), batch.labels)
    9. loss.backward()
    10. clip_grad_norm(model, 1.0)
    11. optimizer.step()
    12. losses.append(float(loss))
    13. return losses

    When comparing results, focus on the following four points:

    • Initial loss: At the beginning of training, the loss should be close to the natural logarithm of the vocabulary size. For example, if the vocabulary is about 32,000, the initial loss should be close to ln(32000), which is approximately 10.37. A clear deviation often indicates issues with weight initialization, data concatenation, or loss computation.
    • Step-by-step alignment: Losses at step 1, step 10, and step 20 should become closer. If the error grows quickly with steps, there may be an accumulated numerical issue.
    • Gradient statistics: Compare gradient norms layer by layer to identify which layer first diverges.
    • Determinism: With data shuffling and nondeterministic operators disabled, repeated runs should produce identical results. If not, prioritize checking communication reduction order or operator implementations.

    It should be noted that floating-point accumulation order differs across hardware, so bit-for-bit equality cannot be required. For low-precision training such as bf16, teams should focus on whether trends and magnitudes are consistent rather than demanding tiny differences be eliminated.

    9. Convergence Comparison: Use a Medium-Scale Model to Check the Curve

    After passing numerical consistency tests, teams can train a medium-scale model on real corpus data for hundreds of steps and compare it with the baseline. For example, the model may have tens of layers and a hidden dimension in the thousands.

    If the convergence curves match, the problem likely comes from a specific structure in the target model. If the deviation is large, the base training path still has issues.

    10. Two-Node 16-Card 400-Step Validation: Plan and Observations

    10.1 Configuration Design

    Under a two-node, 16-card setup, the following configuration can be used as a reference:

    1. # Example configuration for the 400-step validation.
    2. # Field names are placeholders; adjust values based on the actual setup.
    3. model:
    4. dtype: bf16
    5. max_seq_len: 4096
    6. parallel:
    7. tp: 8 # Tensor parallel group is placed within a node.
    8. dp: 2 # Data parallel spans two nodes.
    9. pp: 1
    10. ep: 8 # For MoE models.
    11. sequence_parallel: true
    12. training:
    13. micro_batch_size: 1
    14. grad_accum_steps: 8
    15. activation_checkpoint: true
    16. optimizer: adamw
    17. clip_grad_norm: 1.0
    18. data:
    19. dataloader_workers: 8
    20. # The total number of preprocessed tokens should be close to max_seq_len x global batch size x 400.

    Activation recomputation, also known as gradient checkpointing, trades about 30% additional computation for a significant reduction in memory usage. It is especially useful for small-scale validation where memory is tight.

    10.2 Data Throughput Estimation

    • Global batch size = data parallel degree 2 x micro-batch size 1 x gradient accumulation steps 8 = 16 sequences
    • Tokens processed per step = 16 x 4096 = approximately 65,500 tokens
    • Total tokens over 400 steps = approximately 26.2 million tokens

    Therefore, the preprocessing stage should prepare at least 30 million tokens to avoid running out of data during validation.

    10.3 Launch and Monitoring

    1. # Two-node 16-card launch example.
    2. # Parameters are placeholders; refer to the platform documentation for actual usage.
    3. <hw_launcher> \
    4. --nodes 2 --devices-per-node 8 \
    5. --master-addr <node0-address> --master-port <port> \
    6. --config train.yaml --max-steps 400

    The following metrics are recommended:

    Metric Meaning What to Watch
    loss Average loss per step Overall trend, moving average, abnormal spikes
    grad_norm Global gradient norm Changes before and after clipping; whether it stays at the ceiling
    lr Current learning rate Whether it follows the warmup and decay schedule
    step_time Time per step Whether it fluctuates due to communication or data loading
    tokens/s Training throughput Ratio to the hardware’s theoretical capability
    peak_memory Peak memory usage per card Whether it is close to the limit
    bad_tokens Data pipeline anomaly count Whether it is zero

    11. Stability Validation: What Must Be Stable Across 400 Steps

    A 400-step run is not enough to reflect the final quality of a model, but as a stability validation, it should answer at least four questions:

    1. Is the trend stable? The loss should decrease smoothly overall and should not contain spikes that cause obvious damage.
    2. Are gradients controllable? The gradient norm should fluctuate slightly around the clipping threshold rather than continuously increasing.
    3. Is memory stable? Memory usage should remain stable and should not grow with steps, which would suggest a memory leak.
    4. Is recovery correct? Checkpoints should save and load correctly.

    The following pseudocode can be used to check convergence:

    1. # Convergence check (pseudocode)
    2. import numpy as np
    3. def check_convergence(losses, grad_norms, window=20):
    4. smooth = np.convolve(losses, np.ones(window) / window, mode="valid")
    5. ratios = smooth[1:] / smooth[:-1]
    6. assert ratios.max() < 1.0, "Smoothed loss did not keep decreasing."
    7. assert np.all(np.isfinite(grad_norms)), "Gradient contains NaN or Inf."
    8. assert np.max(grad_norms) < 100 * np.median(grad_norms), "Abnormal gradient spike detected."
    9. assert losses[-1] < 0.8 * losses[0], "Loss reduction is insufficient."
    10. return {"start": losses[0], "end": losses[-1], "max_ratio": ratios.max()}

    Checkpoint resume testing also requires dedicated fault drills:

    1. # Fault injection example: simulate node failure during training.
    2. def fault_injection_check(train_fn, fault_step=200, save_dir="./ckpt"):
    3. train_fn(max_steps=fault_step)
    4. save_checkpoint(save_dir, step=fault_step)
    5. kill_node(1) # Simulate node 1 failure. API name is a placeholder.
    6. restart_all_nodes()
    7. train_fn(resume_from=f"{save_dir}/step-{fault_step}", max_steps=400)
    8. base = get_recorded_losses()[:fault_step]
    9. resumed = get_recorded_losses()[fault_step:]
    10. # After resuming, the relative change between adjacent steps should not be significantly larger
    11. # than normal step-to-step variation.
    12. assert max(abs(resumed[0] - base[-1]) / base[-1],
    13. np.std(np.diff(base)) / np.mean(base)) < 0.05

    12. Common Issues and Troubleshooting Checklist

    Layer Typical Symptom Investigation Direction
    Environment The same script produces different results on different machines Driver, runtime, and communication library versions
    Operator Error reports “not implemented” for a specific parameter combination Fall back to a basic operator implementation and perform numerical validation
    Numerical Initial loss deviates clearly from ln(vocabulary size) Initialization, data concatenation, loss computation
    Communication Training hangs or ranks progress at different speeds Communication group creation, alignment of collective calls, interconnect health
    Data Throughput keeps decreasing during training Data loader concurrency, decode preprocessing, data cache
    Memory Memory usage grows slowly with steps Cache leak, delayed release of computation graph, cache allocation policy
    Precision Occasional NaN or loss spikes Whether overflow-sensitive layers stay in fp32; whether optimizer state precision is correct

    13. Engineering Practice: Turn Adaptation into a Pipeline

    When the same model needs to be adapted to multiple hardware platforms, teams should:

    • Use a unified entry point: Model code and training scripts should avoid hardware-specific branches as much as possible. Differences should be hidden through configuration and operator backend selection.
    • Layer the tests: Operator unit tests, small-scale convergence tests, and multi-node stability tests should all be included in CI pipelines.
    • Improve observability: Training logs, metrics, and checkpoints should be collected centrally to help multiple teams locate problems efficiently.
    • Use cloud validation: Cloud resources that can be requested on demand and released after use can help teams build multi-node, multi-card validation environments quickly and reduce hardware procurement and operations costs.

    14. After 400 Steps: From Validation to Large-Scale Training

    A 400-step run validates that the training path is usable. Large-scale training still faces four additional challenges:

    • Longer duration: Thousand-step, ten-thousand-step, or full pre-training stages require longer observation of loss spikes and gradient anomalies.
    • Larger scale: Expanding to more nodes increases the communication share, so teams need to evaluate scaling efficiency and topology adaptability.
    • More structures: New structures such as long context, MoE, and multimodal models impose new requirements on operators and communication.
    • Fault tolerance: At thousand-card scale, hardware failures are almost inevitable, so automatic detection, isolation, and recovery mechanisms are required.

    Completing 400 training steps on two nodes with 16 cards is one milestone in the process of migrating the training path to domestic AI accelerators. It shows that mainstream training tasks can run end to end on China-developed hardware. Larger-scale, longer-duration, and more scalable validation will be the key to judging whether a hardware platform is truly usable.

    For developers and enterprises, building up compatibility testing, numerical validation, and stability drill methods in advance is essential. As hardware iteration accelerates, these practices help turn compute resources into real training efficiency.