Large Model Training Adaptation on Domestic GPUs: An Out-of-the-Box Training Guide
This article explains the engineering differences between inference adaptation and training adaptation for large models on domestic GPUs. It outlines the key training adaptation path, provides an FSDP2 training skeleton, and describes multi-node communication verification, numerical stability monitoring, common troubleshooting items, and an acceptance checklist for stable out-of-the-box training.
1. First Clarify: What Is the Difference Between Training Adaptation and Inference Adaptation?
Before working on large model training adaptation on domestic GPUs, an engineering question must be answered first: are we validating inference deployment, or are we validating full-chain training capability?
Many projects mistakenly treat “the model can load and can perform a forward pass” as “training adaptation is complete.” This often leads to rework later during long-running training, multi-node communication, and numerical stability validation.
| Dimension | Inference adaptation | Training adaptation | Acceptance focus |
|---|---|---|---|
| Objective | The model can load and produce results | The model can complete forward pass, backward pass, gradient synchronization, and optimizer updates | Whether a complete training loop is completed |
| GPU memory | Mainly weights and KV cache | Parameters, gradients, optimizer states, and activations all consume GPU memory | Whether sharding, recomputation, and offload are supported |
| Numerical stability | Single-pass precision is acceptable | No NaN/Inf or loss divergence during multi-step iterations | Gradient norm, loss curve, and overflow monitoring |
| Communication | Mostly single-GPU or few-GPU cases | Frequent collective communication across multiple nodes and GPUs | Communication bandwidth, overlap efficiency, and topology matching |
| Fault tolerance | Failures can be restarted | Long-running training requires checkpoint resume | Checkpoints, recovery consistency, and automatic rescheduling |
The conclusion is straightforward: inference adaptation focuses on “whether it can run,” while training adaptation focuses on “whether it can run continuously, stably, and scalably.”
Therefore, domestic GPU large model training adaptation cannot stop at validating a single forward pass. The acceptance scope should include model loading, sharding scheduling, forward computation, backward propagation, gradient synchronization, optimizer updates, checkpoint saving, and monitoring.
2. Key Path for Large Model Training Adaptation on Domestic GPUs
A qualified training adaptation usually needs to cover the following stages:
- Model loading and weight initialization: Confirm that weight formats, tokenizers, configuration files, and model structure registries can be correctly parsed on the domestic platform.
- Operator coverage and precision validation: Check whether operators such as attention, normalization, activation, matrix multiplication, embedding, and RoPE have usable implementations.
- Parallel strategy design: Choose data parallelism, tensor parallelism, pipeline parallelism, or FSDP sharding based on model size, GPU memory, and bandwidth.
- Communication path validation: Verify intra-node GPU interconnect, inter-node networking, collective communication backends, and topology affinity.
- Numerical stability monitoring: Continuously observe loss, gradient norm, overflow, learning rate, GPU memory usage, and communication time.
- Fault tolerance and resume training: Verify checkpoint saving, breakpoint recovery, fault rescheduling, and log traceability.
- Toolchain accumulation: Turn manual commands into scripts, configurations, monitoring, and troubleshooting manuals so they form a reusable engineering system.
3. How to Do It: FSDP2 Training Path and Executable Skeleton
In large model training adaptation, data parallelism is the most common basic strategy, and fully sharded data parallelism is an important path for current large model training.
Compared with traditional FSDP1, which often wraps the whole model, FSDP2 emphasizes module-level sharding, mixed precision policies, and tighter integration with compilers and toolchains.
Below is a generic FSDP2 example used to explain the training main loop and key interfaces. It is not a one-click runnable script. In actual use, model construction, data loading, checkpoint saving, and log collection must be completed, and the backend, drivers, and launch method on the domestic platform must be replaced.
import osimport torchimport torch.distributed as distfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicyfrom torch.distributed.device_mesh import init_device_mesh# Generic FSDP2 example: build_model, data_loader, save_checkpoint, and log_metrics must be completed.# On domestic platforms, replace the backend, drivers, collective communication library, and launch method.def build_model():# This function should create a concrete model through the model registry, for example a Transformer/LLM.raise NotImplementedErrordef main():rank = int(os.environ["RANK"])world_size = int(os.environ["WORLD_SIZE"])local_rank = int(os.environ.get("LOCAL_RANK", 0))torch.cuda.set_device(local_rank)# On domestic platforms, replace with a vendor-supported collective communication backend, such as vendor-provided RCCL/HCCL/CCL backends.backend = os.environ.get("VENDOR_BACKEND", "nccl")dist.init_process_group(backend=backend)mesh = init_device_mesh("cuda", (world_size,), mesh_dim_names=("fsdp",))model = build_model().to(f"cuda:{local_rank}")model = fully_shard(model,mesh=mesh,mp_policy=MixedPrecisionPolicy(param_dtype=torch.bfloat16,reduce_dtype=torch.float32,),)optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)for step in range(num_steps):batch = next(data_loader).to(f"cuda:{local_rank}", non_blocking=True)loss = model(batch)loss.backward()grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)optimizer.step()optimizer.zero_grad()if step % 20 == 0:save_checkpoint(step, model, optimizer)log_metrics(step=step,loss=loss.item(),grad_norm=float(grad_norm),memory=torch.cuda.max_memory_allocated() / 1024**3,)dist.destroy_process_group()if __name__ == "__main__":main()
Before running, the following key information must be completed:
- PyTorch version: The version must support the FSDP2 capability of
torch.distributed.fsdp.fully_shard. - Domestic platform dependencies: Vendor drivers, runtime, compiler, collective communication library, PyTorch distribution, monitoring tools, and log collection components.
- Process group initialization: Use
torch.distributed.init_process_group, and ensureRANK,WORLD_SIZE, andLOCAL_RANKare correctly read. - Launch method: Prefer
torchrun. If the domestic platform uses a vendor launcher or MPI launcher, ensure all required environment variables are set. - Communication backend: Do not assume
backendis NCCL by default. It should be set to the collective communication backend documented by the domestic GPU platform.
A torchrun example for a two-node, eight-GPU-per-node scenario is shown below:
export MASTER_ADDR=<node_0_address>export MASTER_PORT=29500torchrun \--nnodes=2 \--nproc_per_node=8 \--rdzv_backend=c10d \--rdzv_endpoint=$MASTER_ADDR:29500 \train.py
If the platform does not use torchrun, a vendor-provided launcher can also be used, but the training script should still read the standard environment variables:
RANK: Global process ID.WORLD_SIZE: Total number of global processes.LOCAL_RANK: Local device ID on the current node.MASTER_ADDR/MASTER_PORT: Address and port used for process group initialization.
4. Multi-Node Multi-GPU Coordination: How to Diagnose and Verify Communication Bottlenecks?
When training moves from a single node to multiple nodes and multiple GPUs, the core challenge is no longer only whether a single GPU is fast enough. Instead, it is whether communication is smooth, whether the topology is matched, and whether failures can be recovered.
Common troubleshooting items for network and communication bottlenecks in multi-node multi-GPU training on domestic GPUs include:
- Intra-node GPU interconnect: Check whether high-speed inter-GPU links are working correctly, whether topology affinity is reasonable, and whether there are link slowdowns or errors.
- Inter-node network: Check inter-node bandwidth, latency, congestion, retransmission, MTU, link jitter, and RDMA-type high-speed network configuration.
- Communication backend: Check the vendor collective communication library version, environment variables, timeout settings, log output, and exception retry mechanism.
- Topology affinity: Parallel groups with heavy communication should be placed within high-bandwidth domains as much as possible. For example, tensor parallelism should be placed first in a high-bandwidth intra-node domain, while data parallelism can scale across nodes.
- Parallel strategy matching: Combine data parallelism, tensor parallelism, pipeline parallelism, or sequence parallelism to avoid sending all communication across nodes.
It is recommended to turn “continuous multi-step stable operation” into a formal acceptance step. Taking two nodes with 16 GPUs as an example:
- Environment acceptance: Confirm two nodes with eight GPUs each, and verify that driver, runtime, compiler, and collective communication library versions are consistent.
- Launch acceptance: Use
torchrunor a vendor launcher to start 16 training processes. - Metric collection: Record loss, gradient norm, learning rate, GPU memory usage, communication time, step time, throughput, and NaN/Inf counts per step.
- Checkpoint strategy: Checkpoints are recommended every 20 steps. The checkpoint should include model shards, optimizer states, learning rate scheduler, random state, training step, and data loading progress. At least the latest three healthy checkpoints should be retained.
- Failure recovery: If a rank exits unexpectedly, the scheduling system should automatically restart the process and restore from the latest checkpoint. If NaN/Inf is detected, the training should roll back to the previous healthy checkpoint rather than continue training.
- Pass criteria: Complete more than 500 consecutive training steps without interruption, NaN/Inf, or communication timeouts. After recovery, loss and gradient norm should align, and throughput fluctuation should remain within an acceptable range.
5. Numerical Stability: Exception Detection and Handling Checklist
Numerical stability is the lifeline of training adaptation. A single forward pass may look correct, but that does not mean the entire training path is stable. Numerical issues often appear only after hundreds of steps.
Recommended logging granularity:
- Per step: loss, global gradient norm, maximum absolute gradient, NaN/Inf count, learning rate, step time, GPU memory usage, communication time, and throughput.
- Every 10 or 50 steps: layer-wise gradient norm, parameter update norm, key layer output statistics, and activation ranges.
- At exception time: operator call stack for the corresponding step, input/output statistics, communication time, data batch index, and the latest healthy checkpoint.
Common exceptions and recommended handling actions:
| Exception | Possible cause | Handling action |
|---|---|---|
| Loss becomes NaN/Inf | Abnormal input, improper loss scaling, FP16 overflow, or numerically unstable operators | Roll back to the latest healthy checkpoint and check data, loss scaling, and precision mode |
| Gradient norm suddenly spikes | Learning rate too high, gradient spikes, abnormal batches, or operator overflow | Enable gradient clipping, lower the learning rate, skip abnormal batches, and locate the abnormal layer |
| GPU memory keeps rising | Cache not released, too many activations, or improper sharding strategy | Enable activation checkpointing, reduce micro-batch size, and check memory statistics |
| Communication timeout or hang | Communication backend exception, network jitter, or topology mismatch | Check links, communication library logs, timeout settings, and parallel group mapping |
| Loss differs across ranks | Inconsistent initialization, inconsistent data order, or unaligned random seeds | Align random seeds, data sampling, and model initialization |
| Divergence in later training stages | Learning rate too high, data quality changes, or accumulated numerical error | Roll back to a checkpoint and adjust learning rate or optimizer parameters |
6. Common Troubleshooting for Domestic GPU Adaptation
| Symptom | Possible cause | Troubleshooting action | Acceptance evidence |
|---|---|---|---|
| Operator missing or error occurs | The domestic GPU operator library lacks a corresponding implementation | Check the operator coverage list, switch to an equivalent implementation, or fall back to another operator | Operator tests pass, and logs show no unknown operator errors |
| Precision differs from the reference implementation | Precision mode, accumulation order, or compiler differences | Compare single-layer outputs, error thresholds, and precision modes | Error is within an acceptable range, and long-running training remains stable |
| Graph mode or compilation errors | Compiler, graph capture, or dynamic shape compatibility issues | Switch to eager mode or fix shape constraints | Graph mode and eager mode produce consistent results |
| Collective communication fails | Communication library version, backend parameters, or network configuration errors | Check vendor communication library, environment variables, and link status | Small-scale communication tests pass |
| Low scaling efficiency across multiple nodes | Poor topology affinity or excessive inter-node communication | Adjust parallel strategy and check communication overlap | Scaling efficiency meets acceptance targets |
| Logs unavailable | Missing monitoring tools or logging standards | Complete log collection, metric reporting, and alerting | Issues can be traced to step, rank, and operator |
7. How to Choose: FSDP2 Sharding and Parallelism Strategies
| Strategy | Suitable scenario | Cost | Selection advice |
|---|---|---|---|
| Full sharding | The model is very large and a single GPU does not have enough memory | Frequent communication | Evaluate first in high-bandwidth multi-node scenarios |
| Hybrid sharding | Inter-node bandwidth is relatively weak | Requires high intra-node bandwidth coordination | Use full sharding inside a node, and replication or shallow sharding across nodes |
| CPU offload | GPU memory is extremely tight | Throughput decreases | Enable only when necessary |
| Activation checkpointing | Activation memory is too high | Recomputation overhead | Commonly used for long sequences or large models |
Common mistakes include:
- Treating inference success as training completion.
- Running only a few steps and declaring the training stable.
- Looking only at loss without checking gradient norm.
- Ignoring cross-node communication bottlenecks.
- Running long-period training without checkpoints, which increases risk.
- Blindly enabling offload or mixed precision, which can create a poor balance between performance and stability.
8. Out-of-the-Box Training Acceptance Checklist
The final goal of large model training adaptation on domestic GPUs is not a one-time “it can train” validation. It should reach a mature state of “out-of-the-box training.”
A checklist can be used for evaluation:
- Model architecture: Mainstream Transformer or LLM architectures can be loaded directly, and training can start by replacing configurations.
- Startup environment:
torchrunor a vendor launcher can start training with one command and automatically validate drivers, communication libraries, and environment variables. - Multi-step stability: More than 500 steps without NaN/Inf, a reasonable loss curve, and controlled gradient norm.
- Scaling efficiency: Scaling efficiency for single-node, dual-node, and multi-node setups meets targets, and communication can overlap with computation.
- Fault tolerance and resume: Checkpoints are saved automatically, breakpoint recovery succeeds, and metrics align after recovery.
- Toolchain compatibility: Supports configuration management, log collection, visualization monitoring, fault diagnosis, and version locking.
- Domestic GPU-specific checks: Operator coverage, precision modes, compiler, collective communication library, interconnect topology, monitoring tools, and logging standards.
- Pre-release checks: Documentation examples can run, the dependency list is complete, and failure drills pass.
For enterprises and developers who need to run large model training on domestic compute platforms, the landing advice can be summarized in four sentences:
- First distinguish training adaptation from inference adaptation.
- Use continuous multi-step stable operation as the acceptance criterion.
- Include numerical stability and communication bottlenecks in monitoring.
- Turn a one-time successful run into a reusable toolchain.
Only after completing these engineering loops can advanced large models move steadily from “can train” to “out-of-the-box training” on domestic full-featured GPUs.
