Large Model Training Adaptation on Domestic GPUs: From Can-Train to Out-of-the-Box Ready
A practical guide to adapting large language model training pipelines to domestic (homegrown) GPU accelerators. It distinguishes training adaptation from pretraining, maps common challenges—memory, operator coverage, communication, numerical stability, and long-run fault tolerance—to concrete checks and debugging paths, then walks through FSDP sharding and multi-node distributed initialization with runnable pseudocode. It also covers engineering safeguards for numerical stability, checkpoint/resume pitfalls, and a staged acceptance checklist that moves a model from merely training to running out of the box.
1. Clarifying the concepts: training adaptation is not pretraining
When discussing domestic accelerators supporting large model training, the most easily confused distinction is between “successful training adaptation” and “the model completed pretraining on this hardware.” Both are often lumped together as “running a large model,” but their technical meanings are completely different.
What is the difference between training adaptation and pretraining?
- Training adaptation: Getting the complete training pipeline of a model with existing weights (model loading, parameter sharding, forward computation, backpropagation, gradient synchronization, optimizer updates) working on the target hardware and software stack, and verifying that it can iterate stably with loss converging normally.
- Pretraining: The original training of a base model from random initialization on massive corpora, whose compute source must be explicitly stated by the releasing party.
So “a certain hardware completed training adaptation for an open-source model” indicates that the hardware has the engineering capability to support training of this kind of model. It does not mean the model’s original base was trained on this hardware. Directly equating “adaptation/integration success” with “pretraining capability is in place” is the most common pitfall when evaluating the true training capability of domestic compute.
2. Core challenges and tool mapping
Getting a trillion-parameter model fully running involves far more than “can do forward, can do backward.” The following table maps challenges to checklist items, monitoring metrics, and common debugging directions.
| Challenge | Check/Tool | Monitoring Metric | Common Debugging Direction |
|---|---|---|---|
| Memory bottleneck | Sharding + recomputation, nvidia-smi/vendor tools |
Per-GPU memory usage, OOM count | Lower batch, enable activation checkpointing |
| Operator coverage | Unit tests + precision alignment scripts | Forward/backward numerical error of operators | Fall back to equivalent native operators |
| Communication efficiency | Communication library profiler | all-reduce bandwidth, communication ratio | Check topology, NCCL/HCCL environment variables |
| Numerical stability | Main loop instrumentation | loss, grad_norm, NaN/Inf count | Check loss scale, initialization |
| Long-run fault tolerance | Checkpointing + health probes | Node dropout rate, recovery time | Investigate hardware fluctuations, communication timeouts |
3. How FSDP reduces memory
In data parallelism, every GPU holds complete parameters, gradients, and optimizer states, which is highly redundant. Fully Sharded Data Parallel (FSDP) shards these states along the data-parallel dimension, so each GPU stores only a portion and aggregates on demand during forward/backward, significantly reducing per-GPU memory.
How does FSDP reduce memory? It shards and stores optimizer states, gradients, and parameters by rank, avoiding a full replica on each GPU. Memory estimation can reference: per-GPU peak ≈ model shard + gradient shard + optimizer state shard + activations of the current layer.
Complete, reproducible single-step training pseudocode (version example: Python 3.10 + PyTorch 2.1+, or the PyTorch adaptation version for the corresponding domestic software stack):
# Pseudocode: single training step with FSDP sharded data parallelismimport osimport torchimport torch.nn as nnfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDPfrom torch.distributed.fsdp import ShardingStrategy, MixedPrecisionfrom torch.amp import autocastdevice = setup_distributed() # Distributed init see Section 4model = MyModel().to(device) # Replace with the concrete model definitionloss_fn = nn.CrossEntropyLoss()model.train() # Key: switch to training mode before training# Wrap with the FULL_SHARD strategy: parameters/gradients/optimizer states are sharded along the DP dimensionmodel = FSDP(model,sharding_strategy=ShardingStrategy.FULL_SHARD,mixed_precision=MixedPrecision(param_dtype=torch.bfloat16),)optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)for step, batch in enumerate(dataloader):batch = batch.to(device)with autocast(device_type="cuda", dtype=torch.bfloat16):# Forward: FSDP automatically all-gathers sharded parameters on demand before computingloss = loss_fn(model(batch), batch.label)optimizer.zero_grad(set_to_none=True) # Clear gradients before backwardloss.backward() # Compute sharded gradients then reduce-scatter to aggregategrad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)optimizer.step() # Each rank only updates the shard it holds# Numerical anomaly protection: trigger recovery if loss or gradient norm is invalidif not torch.isfinite(loss) or not torch.isfinite(grad_norm):load_latest_checkpoint(step) # Recovery entry see Section 5continue
Launch example (torchrun injects the RANK/LOCAL_RANK/WORLD_SIZE environment variables):
torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 \--master_addr=<primary node IP> --master_port=29500 train.py
4. Multi-node, multi-GPU joint training and stability verification
Cross-node training must handle not only intra-node communication but also correct process group initialization, global rank assignment, and node synchronization. The key point of distributed initialization is that the backend and device abstraction must correspond to the target software stack; you cannot directly assume nccl and torch.cuda:
# Pseudocode: cross-node distributed initialization (backend/device vary by software stack)import osimport torchimport torch.distributed as distdef setup_distributed():rank = int(os.environ["RANK"])local_rank = int(os.environ["LOCAL_RANK"])world_size = int(os.environ["WORLD_SIZE"])assert world_size >= 1, f"invalid world_size: {world_size}"# Backend must correspond to the target software stack:# NVIDIA/CUDA -> "nccl"# Huawei Ascend torch_npu -> "hccl"# Cambricon torch_mlu -> "cncl"# Other domestic stacks -> use the backend given in the vendor documentationbackend = os.environ.get("DIST_BACKEND", "nccl")dist.init_process_group(backend=backend, rank=rank, world_size=world_size)# Device abstraction also varies by stack:# CUDA -> torch.cuda.set_device; torch_npu -> torch.npu.set_device ...device = torch.device(f"cuda:{local_rank}")torch.cuda.set_device(local_rank)return device# Split data loading by rank to avoid duplication or missing samplessampler = torch.utils.data.distributed.DistributedSampler(dataset, num_replicas=world_size, rank=global_rank)
Test criteria (verifiable example): The following is an illustrative validation, not a universal conclusion. The configuration is 16 accelerators across two nodes (e.g., 16 of a certain domestic card model), a model of roughly several hundred million parameters, an open-source instruction-tuning dataset, a parallel strategy of FSDP-FULL_SHARD + bf16, and the corresponding vendor’s PyTorch adaptation version as the software stack; 16 training processes completed 400 consecutive optimizer updates. Judgment threshold: loss remains finite and generally decreasing throughout, grad_norm stays within a reasonable range (example threshold: no repeated hitting of the ceiling after ≤ 1.0 clipping), and the NaN/Inf count is 0.
Judging whether adaptation is “truly working” should not rely solely on whether it can start, but on observing whether loss decreases steadily, whether the gradient norm is reasonable, and whether there are any NaN/Inf values over hundreds of consecutive steps.
5. Engineering safeguards for numerical stability
To hold loss and grad_norm across long training runs, a combination of techniques is usually needed:
- Mixed-precision training: bf16/fp16 reduce memory and bandwidth, while keeping fp32 master weights to preserve precision.
- Loss scaling: Under fp16, scale small gradients to prevent underflow to 0.
- Gradient clipping: Limit the gradient norm within a threshold to avoid overly aggressive single-step updates that diverge.
- Continuous monitoring: Record loss and gradient norms in real time, and alert immediately upon illegal values.
- Checkpoint-resume: Periodically save checkpoints and recover from the most recent valid state upon anomalies.
Recovery risk note: Checkpoint-resume cannot store only model weights. The checkpoint must simultaneously verify and restore model, optimizer state, learning rate scheduler, random number state, and dataloader progress, otherwise after recovery you easily encounter data duplication or missing samples, learning rate misalignment, and lost momentum. It is recommended to save the number of samples already consumed by the dataloader or the sampler state, and align set_epoch/skip on recovery.
6. Engineering system for full-pipeline training
Having only inference deployment capability is a different order of engineering requirement from having full-pipeline stable training capability. A mature training support system needs to cover operator adaptation, multi-GPU collaborative communication, training script organization, monitoring and alerting, and automation tooling. According to public information and some partnership case statements (subject to official disclosure), there are currently multiple practices underway, including foundation model training, world model training oriented to physical laws, and embodied intelligence model training. These practices provide a reference for domestic full-function GPUs moving from “inference-ready” to “training-reliable,” but they do not constitute a universal capability conclusion for any given model.
7. Evolution path from “can train” to “out-of-the-box training”
What to do when NaN appears in multi-node training? First troubleshoot with the combination of techniques in Section 5: confirm whether the loss scale has overflowed, whether gradient clipping is taking effect, and whether initialization and data are abnormal, then recover from the most recent valid checkpoint.
The training maturity of domestic compute can be quantitatively divided into three stages:
- Can train: Completed operator adaptation and single-machine/small-scale running. Acceptance: single-GPU/single-machine ≥ 100 consecutive steps without crash, loss finite.
- Trains stably: Multi-node, multi-GPU long-step runs maintaining numerical stability. Acceptance: ≥ 400 consecutive steps with steady loss, reasonable grad_norm, NaN/Inf = 0, and a checkpoint recovery success rate that meets the target.
- Out-of-the-box training: Automation tooling masks low-level details. Acceptance: standard scripts meet end-to-end success rate and throughput targets, and users can start without modifying low-level configuration.
8. Acceptance checklist
- Environment/version/backend correspond to the software stack,
world_sizevalidation passes - Start 100 steps without crash, loss finite and generally decreasing
- 400 consecutive steps with steady loss, reasonable grad_norm, NaN/Inf = 0
- Throughput and communication time recorded within the expected range, no persistent communication timeouts
- Trigger one checkpoint recovery, model/optimizer/scheduler/dataloader states consistent
- No data duplication/missing after recovery, no learning rate misalignment
9. Practical recommendations
- Prioritize building a sharded data-parallel path, benefiting from both memory and scalability;
- Incorporate numerical stability monitoring (loss, grad_norm, anomaly detection) into the main training loop, rather than troubleshooting after the fact;
- Establish a complete checkpoint and recovery mechanism, including scheduler and dataloader states;
- Use “hundreds of consecutive steps without anomalies” as a hard acceptance metric, rather than only verifying whether it can start.
Completing the training adaptation of ultra-large-scale models marks a key step for domestic compute in training engineering capability. To truly make this capability accessible to developers, continued investment is still needed in the operator ecosystem, collaborative communication, and automation tooling, driving frontier large models on domestic hardware to move solidly from “can train” to “out-of-the-box training.”
