Practical Guide to Running Large Model Pre-Training on Domestic GPU Clusters
This article walks through the engineering practice of bringing up a complete large model pre-training pipeline on a domestic accelerator card cluster and sustaining several hundred stable iterations. It covers three-layer environment validation, parallelism design for a two-node sixteen-card setup, mixed-precision and optimizer details for numerical stability, throughput bottleneck localization, long-run reliability with checkpointing and fault tolerance, and quantifiable acceptance criteria. Readers will find concrete configuration examples, code snippets, and a reusable checklist for moving a non-mainstream hardware platform from demo-ready to production-ready.
1. Background and Problem Definition
In large model pre-training, self-reliant and controllable compute platforms have become a practical concern for engineering teams. The core scenario described here can be abstracted into a broadly applicable technical problem: bringing up a complete large model pre-training pipeline on a cluster of domestic accelerator cards from a non-mainstream ecosystem, and completing several hundred stable iterations.
It is worth distinguishing “running through” from “running to completion.” Running through means the full loop is closed: data loading, forward computation, backward propagation, gradient synchronization, optimizer updates, and checkpoint saving and restoration. Running four hundred steps means the pipeline remains numerically stable over a meaningful duration, with no loss spikes, no communication timeouts, and no memory leaks. These two points mark the dividing line between “good enough for a demo” and “good enough for production.”
Common failure modes in practice include:
- Missing operators or inconsistent precision behavior, causing forward results to deviate from the reference implementation;
- A collective communication library that does not match the network topology, resulting in very low gradient synchronization bandwidth utilization;
- Memory fragmentation, leading to allocation failures after a few dozen steps;
- Insufficient data pipeline throughput, leaving accelerator cards idle and waiting.
2. Environment Preparation: Surface Uncertainties Early
The first principle of deploying on a heterogeneous compute platform is to expose problems as early as possible. It is recommended to complete three layers of validation before formal training.
The first layer is hardware and drivers. Confirm that accelerator card firmware, drivers, and the communication library are mutually compatible. Use point-to-point bandwidth and collective communication benchmarks to measure actual intra-node interconnect and inter-node network throughput, and record baseline data so there is a reference point when performance regresses later.
The second layer is operators. Run numerical alignment tests on the matrix multiplication, normalization, attention, and activation operators the training will use. Fix the random seed for inputs and compare relative error against the reference implementation:
# Example: numerical alignment check for operatorsimport numpy as npdef check_close(out, ref, rtol=1e-3, atol=1e-4):ok = np.allclose(out, ref, rtol=rtol, atol=atol)max_err = float(np.max(np.abs(out - ref)))print(f"aligned={ok}, max_abs_err={max_err:.3e}")return ok
The third layer is the pipeline itself. Run a few dozen steps with a minimal model configuration (for example, two or three layers with a very small hidden dimension) to clear out configuration errors, path errors, and permission issues before scaling up to the target size.
3. Parallelism Strategy for Two Nodes and Sixteen Cards
Two machines with sixteen accelerator cards in total is a typical “small-scale multi-node” scenario, and the key design goal is minimizing communication volume.
- Data parallelism as the backbone: each card holds a full model replica and performs all-reduce on gradients after the backward pass. The gradient volume equals the parameter count and is the main source of communication cost.
- Tensor parallelism confined within a node: split the large matrices of a single layer across multiple cards on the same machine, leveraging high intra-node interconnect bandwidth and avoiding frequent cross-node synchronization.
- Pipeline parallelism used cautiously: with few machines, too many stages amplify the bubble ratio, so it is typically enabled only when the model has many layers, together with a reasonable number of micro-batches.
- Activation recomputation to trade compute for memory: using a small amount of repeated computation to reduce activation memory is the most direct approach when a single card is tight on memory.
- Optimizer state sharding: partitioning optimizer state along the data parallel dimension can significantly reduce peak per-card memory.
A typical way to organize the launch configuration is shown below (structure only):
# Process count per node and node count are injected by platform scheduling parametersexport NUM_NODES=2export GPUS_PER_NODE=8export MASTER_ADDR=<injected by scheduler>export MASTER_PORT=<injected by scheduler>python train.py \--tensor-parallel-size 4 \--pipeline-parallel-size 1 \--micro-batch-size 1 \--gradient-checkpointing true \--zero-stage 2
Note that there is no universal optimum for the specific parallel degrees. They should be determined jointly by four variables: model parameter count, per-card memory, intra-node interconnect bandwidth, and inter-node bandwidth. In practice, a small-scale grid search is used to settle on the configuration.
4. Numerical Stability: Mixed Precision and Optimizer Details
Mixed precision training is key to efficiency and also a source of numerical risk. Common practices include:
- Use lower precision for computation to gain throughput, while maintaining a higher-precision master copy of the parameters;
- Introduce loss scaling to prevent small gradients from underflowing to zero during conversion, with the scaling factor adjusted dynamically;
- Keep normalization layers and loss computation in higher precision to reduce accumulated error;
- Apply gradient clipping by global norm to suppress update explosions caused by abnormal samples.
For logging and metrics, record at least: per-step loss, global gradient norm, loss scaling factor, peak per-card memory, and the time share of each stage. When the scaling factor keeps decreasing or the gradient norm spikes periodically, it usually points to data anomalies or improper precision configuration.
5. Throughput Optimization and Bottleneck Localization
Whether four hundred steps finish in an acceptable time depends on how accurately the bottleneck is located. The recommended order is:
- First look at accelerator utilization. Persistently low utilization means the cards are waiting on data, and the problem is in the data pipeline;
- Then look at the communication share. If communication time exceeds computation time, the parallel partitioning does not match the topology;
- Finally look at kernel efficiency. If the workload is compute-bound but throughput is low, inspect the operator implementations and memory access patterns.
Common data-side techniques include mixing sequential and random sampling, prefetching and multi-process decoding, packing samples into fixed-length sequences to reduce padding waste, and converting the dataset into a sequentially readable shard format combined with object storage or a parallel file system cache.
6. Reliability and Long-Run Stability
Running through a short run does not equal long-run stability. Production readiness requires:
- Checkpoint strategy: save the model, optimizer, scheduler, and data reading position at fixed step intervals so that any interruption can resume training precisely;
- Fault tolerance and automatic restart: when a single card fails, the scheduling layer relaunches the job and restores from the most recent checkpoint;
- Observability: unified collection of metrics, logs, and tracing, combined with monitoring and alerting to intervene early on anomalies;
- Environment consistency: pin dependency versions in container images to avoid environment drift across nodes.
# Example: minimal loop for checkpoint saving and restorationdef save_ckpt(step, model, opt, path):state = {"step": step, "model": model.state_dict(),"opt": opt.state_dict()}tmp = f"{path}.tmp"torch.save(state, tmp) # write to a temporary file firstos.replace(tmp, path) # atomic replace to avoid a partially written filedef load_ckpt(path, model, opt):state = torch.load(path, map_location="cpu")model.load_state_dict(state["model"])opt.load_state_dict(state["opt"])return state["step"]
Atomic writes are a commonly overlooked detail: when overwriting the target file directly, killing the process mid-write leaves a corrupted checkpoint that cannot be resumed from.
7. Acceptance Criteria and Reuse Recommendations
Break acceptance into quantifiable items: the pipeline runs continuously for at least the specified number of steps without interruption; the loss curve decreases monotonically and stays within a reasonable range; the single-node to multi-node throughput ratio matches expectations; peak memory leaves a safety margin; training resumes from a checkpoint after interruption with continuous loss; and key metrics can be fully traced back in the monitoring dashboard.
Once this process is consolidated into a standardized checklist and environment baseline, changing the model size or adjusting the number of machines only requires re-running the parameter grid rather than hitting the same pitfalls again. This is the engineering path for domestic compute platforms to move from “it runs” to “it works well,” and it can be combined with general cloud capabilities such as the container platform, object storage, and monitoring and alerting offered by Baidu AI Cloud to form a complete training infrastructure.
