Large Model Training on Domestic GPUs: From Runnable to Re-trainable
This article explains how to adapt large language model training to domestic GPU hardware and move from a run that merely works to one that is reproducible and recoverable. It distinguishes training adaptation from base-model pre-training, compares parallelism strategies (DDP, FSDP2, and tensor parallelism), and provides a minimum runnable FSDP2 reference skeleton together with a domestic GPU adaptation checklist. It then covers cross-node distributed training, numerical stability techniques, an acceptance checklist, and a troubleshooting table. The code is a reference skeleton and has not been tested on any specific domestic GPU software stack; operator coverage, the collective communication backend, and memory peaks must be verified against the target hardware documentation before deployment.
Conclusion First
- “Adaptation success” usually means that operators and parallel strategies run and can be verified on the target hardware — not that the base weights were pre-trained on that hardware. When selecting hardware, first decide whether you need ecosystem compatibility or large-scale pre-training capability.
- The engineering focus of stable training is “reproducible verification criteria + recoverable failure paths,” not simply adding more GPUs.
- The code in this article is a reference skeleton and has not been tested on any specific domestic GPU software stack. Before deployment, you must verify operator coverage, the collective communication backend, and memory peaks item by item against the target hardware documentation.
1. Clarify the concepts first: training adaptation ≠ base pre-training
When people say “a domestic GPU has completed adaptation for a frontier large model,” the most easily misread point is that adaptation success does not mean the model was pre-trained from scratch on that chip. The two differ fundamentally in compute demand, engineering complexity, and verification goals.
| Dimension | Training adaptation | Base pre-training |
|---|---|---|
| Starting point | Existing weights; may also start from random initialization for closed-loop validation | Randomly initialized weights |
| Goal | Runs, runs correctly, runs stably | Trains successfully, trains well |
| Data scale | Mainly small-scale slice validation | Trillion-level token corpus |
| Main risks | Missing operators, precision fallback, communication failure | Numerical divergence, interruption loss, cost overrun |
| Focus | Ecosystem compatibility, operator coverage | Large-scale stability and efficiency |
When industry reports that “an open-source large model has been validated on a certain class of chips,” this more often refers to feasibility validation of training adaptation and inference operators. Developers should split “adaptation validation” and “native pre-training” into two categories: the former is about the operator list and software-stack maturity; the latter is about long-run training stability and fault-recovery capability.
2. Choosing a parallelism strategy: DDP, FSDP2, or tensor parallelism
| Option | Applicable scale | Communication cost | Domestic GPU notes |
|---|---|---|---|
| DDP | A single GPU can hold all parameters; recommend memory usage <70% | One full gradient AllReduce per step, growing linearly with parameters | Verify the communication library’s support for low-precision full AllReduce |
| FSDP2 | Single GPU can’t fit; across multiple machines and GPUs | One round of AllGather + ReduceScatter each for forward/backward | Focus on verifying the memory peak of shard aggregation and the collective communication primitives |
| Tensor parallelism (TP) | A single layer can’t be placed; ultra-large models | Multiple AllReduce per layer, extremely sensitive to bandwidth | Recommend limiting to the intra-node high-bandwidth domain; can combine with sequence parallelism to reduce activation memory |
Common combination: intra-node TP + inter-node FSDP/DP. First check “can a single layer fit in one machine,” then decide whether TP is necessary; whatever FSDP2 can solve should use less TP, which significantly reduces the tuning surface on a domestic stack.
3. Minimum runnable prerequisites and an FSDP2 reference skeleton
3.1 Environment prerequisites
- Framework version: the
fully_shardinterface of FSDP2 is available in relatively recent PyTorch mainline versions (around 2.6 and above); confirm this empirically withpython -c "import torch; print(torch.__version__)"in your local environment. Older versions only have the FSDP1 interface, with a different API shape. - Launch method: use
torchrunor an equivalent launcher to injectRANK,WORLD_SIZE, andLOCAL_RANK; no longer specify them manually in code. - Device setup: you must call
set_devicefirst, then move parameters to the target device and shard. Reversing the order causes shards to land on the wrong device. - Data side:
DistributedSamplermust be passednum_replicasandrank; otherwise each rank reads the same data, and the gradient is equivalent to enlarging the batch rather than distributing the data. - Nature of the example:
build_model()anddatasetare placeholder objects that readers must replace with their own model and data; the code cannot be treated as a directly runnable complete program.
3.2 Reference skeleton
The code below is a structural illustration and has not been tested on this domestic GPU software stack. build_model() and dataset are placeholder implementations that need to be replaced with a real model and dataset.
import osimport torchimport torch.distributed as distfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicyfrom torch.utils.data import DataLoader, DistributedSampler# build_model() and dataset are placeholders; replace them with your model and data.def build_model():return YourModel() # Placeholder: replace with the real modeldataset = YourDataset() # Placeholder: replace with the real datasetdef setup():rank = int(os.environ["RANK"])world_size = int(os.environ["WORLD_SIZE"])local_rank = int(os.environ["LOCAL_RANK"])# The backend name and device interface usually need to be replaced on domestic stacks,# e.g. a vendor communication backend or a device compatibility layerdist.init_process_group(backend="nccl", rank=rank, world_size=world_size)torch.cuda.set_device(local_rank)return rank, world_size, local_rankdef main():rank, world_size, local_rank = setup()device = f"cuda:{local_rank}"num_epochs = 3 # Replace with the actual number of training epochsmodel = build_model().to(device) # Move to the device first, then shardmesh = init_device_mesh("cuda", (world_size,), mesh_dim_names=("fsdp",))model = fully_shard(model,mesh=mesh,mp_policy=MixedPrecisionPolicy(param_dtype=torch.bfloat16,reduce_dtype=torch.float32,),)sampler = DistributedSampler(dataset,num_replicas=world_size,rank=rank,shuffle=True,seed=42,)loader = DataLoader(dataset, sampler=sampler, batch_size=8)optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)for epoch in range(num_epochs):sampler.set_epoch(epoch) # Call once before iterating the loader for each epochfor step, batch in enumerate(loader):batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}loss = model(**batch).lossloss.backward()grad_norm = torch.clip_grad_norm_(model.parameters(), max_norm=1.0)optimizer.step()optimizer.zero_grad(set_to_none=True)if rank == 0 and step % 20 == 0:print(epoch, step, loss.item(), grad_norm.item(), flush=True)dist.destroy_process_group()if __name__ == "__main__":main()
The names of key arguments such as MixedPrecisionPolicy, the backend name, and the device interface may all differ across framework versions and domestic software stacks; always refer to your local version documentation.
3.3 Domestic GPU adaptation checklist
- Software-stack versions: archive the driver, communication library, and framework version numbers, identical to the validation environment;
- Operator coverage: list operators against the model structure and mark missing ones and precision fallbacks. Falling back to FP32 significantly slows training;
- Collective communication: confirm that AllGather, ReduceScatter, AllReduce, and Broadcast have all been validated on the target backend;
- Memory peak: record the peak at the moment of shard aggregation, not the steady-state average;
- Mixed precision: confirm the accumulation precision and loss-scaling behavior on the low-precision path.
Until each item is verified, all code in this article should be treated as pseudocode and should not be claimed as “directly runnable” in external materials.
4. Cross-node distributed training: topology, communication, and fault recovery
Example configuration: “2 nodes, 16 GPUs total,” with TP=4 (intra-node) and FSDP/DP=4 (inter-node). The parallelism converts to TP=4 × FSDP/DP=4 = world_size 16. This way, per-step inter-node communication carries only the shard aggregation and gradient reduction needed by data parallelism, avoiding TP’s per-layer AllReduce crossing the inter-node link.
Executable actions and checks
- Topology verification: after launch, print
world_size,rank,local_rank, and the actual topology, confirming that the intra-node/inter-node grouping matches expectations; - Communication log collection: raise the communication library’s log level and record the time distribution and retry behavior of each collective communication to locate slow nodes;
- Node health check: before training, inspect NIC status and the inter-node bandwidth baseline; you can run a small collective-communication benchmark, and also check process and memory usage;
- Compute-communication overlap: confirm that parameter aggregation and gradient reduction overlap with computation, observing whether communication time is hidden rather than added to the critical path.
Checkpoint recovery steps
- Checkpoint metadata records: rank, world_size, parallelism degree, random seed, framework, and software-stack versions;
- Save the dataloader consumption position, including sampler epoch and step, to avoid re-consuming data after recovery;
- Save/restore the random number states of Python, NumPy, and the device;
- Before recovery, verify parallelism consistency and that the number of weight shards matches;
- After recovery, continue for a few steps and compare whether the loss and grad_norm curves are continuous with those before the interruption.
Risk note: during long-run training, node jitter, process exceptions, and communication timeouts all interrupt the job; the checkpoint interval should be estimated by “per-step time × acceptable loss duration” — do not default to reusing parameters from another cluster.
5. Numerical stability: from “can train” to “trains stably”
The most common failure mode in large-scale training is not insufficient memory but numerical instability: loss turning into NaN, gradient norm exploding, parameter updates diverging. There are four common techniques:
- Mixed precision and loss scaling: low precision saves memory and bandwidth. Loss scaling mainly targets fp16, used to avoid small gradients underflowing to zero in low precision. bf16 has the same exponent bits as fp32 and a wider dynamic range, so it usually needs no loss scaling. Therefore this article’s skeleton uses bf16 and does not add
GradScaler. If you switch to fp16, you need to enable loss scaling. - Gradient clipping: clip the global gradient norm before the optimizer update to suppress abnormal gradients.
- Normalization layers: properly using layer normalization suppresses activation scale drift. Note that batch normalization needs synchronized statistics in cross-GPU scenarios.
- Metrics monitoring: collect loss, gradient norm, learning rate, memory, and throughput per step, feeding into a unified logging, monitoring, and alerting platform. Set threshold alerts for NaN/Inf and for curves deviating from normal ranges.
Verification criteria (avoiding meaningless conclusions such as “ran a few hundred steps”): fix the random seed, data slice, parallelism degree, and batch size; on this basis, train continuously to a team-defined baseline step count, recommended to be no fewer than a step interval that represents real workload. Require loss and gradient norm to be finite throughout, with no NaN/Inf and no process restarts, and require that checkpoints can be successfully recovered. Only by comparing across hardware under the same criteria are conclusions comparable; step counts that have not been measured should not be given as specific numbers in documentation.
6. Training adaptation acceptance checklist
- Runnable: a complete forward, backward, and optimizer-update loop, with no operator-fallback warnings;
- Numerically stable: continuous training under fixed criteria, with loss and grad_norm finite throughout;
- Communication normal: intra-node/inter-node collective communication time within the baseline range, with no timeout retries;
- Checkpoint resume: after saving and recovering, the loss curve is continuous and data is not re-consumed;
- Performance baseline: under fixed sequence length, fixed global batch, and after warm-up to steady state, record throughput, memory peak, MFU, and other metrics as a basis for subsequent regression comparison.
7. Common errors and troubleshooting table
| Symptom | Common root cause | Troubleshooting action |
|---|---|---|
| Device-related error at startup | Backend name or device interface not aligned | Print rank/world_size/local_rank; confirm the backend and device-number mapping |
| Missing operator or precision fallback | Insufficient operator coverage | Check against the operator list; replace the implementation or report it to the software-stack vendor |
| loss turns into NaN | Low-precision underflow, gradient explosion, insufficient precision in mask/loss computation | Enable loss scaling; inspect grad_norm; lower lr; verify loss precision |
| Communication timeout | Slow node, missing environment variables, abnormal inter-node bandwidth | Collect communication logs; run a bandwidth baseline test; do node health inspection |
| Memory OOM at the aggregation moment | Shard-aggregation peak stacking with activations | Lower batch or sequence length; enable activation recomputation; adjust shard granularity |
| loss jump on checkpoint resume | Inconsistent parallelism or data position | Verify metadata, parallelism, sampler position, and RNG state |
8. FAQ
- How do you do training adaptation on a domestic GPU? First do an operator-coverage inventory, then build a minimum closed loop, e.g. a single machine with a few GPUs; after passing, scale to cross-node, and finally archive everything against the acceptance checklist.
- How do you configure FSDP2 on a domestic GPU? Confirm the framework version supports
fully_shard, usetorchrunto inject environment variables, set the device before sharding, and correctly passnum_replicasandranktoDistributedSampler. - How do you troubleshoot loss turning into NaN during domestic GPU training? First check whether the gradient norm is abnormal, then whether fp16 is used, whether loss scaling is missing, and whether the learning rate is too large, and verify the computation precision of loss and mask.
- What do you do about data re-consumption during domestic GPU checkpoint resume? Save the sampler epoch, step, random number states, and parallelism metadata; verify consistency before recovery, and compare the loss curve after recovery.
- What is the difference between FSDP2 and FSDP1? The interface shape and shard management model differ; when upgrading you cannot just change the import — you need to re-run the acceptance checklist.
- Can adaptation validation demonstrate base capability? No. It validates feasibility and stability, not the final effect and cost of large-scale pre-training.
9. Summary
Domestic GPUs completing frontier large-model training adaptation marks a key step in compute self-reliance moving from “operators run” to “full-chain stable training.” The path to adoption is not mysterious: first distinguish the goals of adaptation versus pre-training, then choose the right parallelism strategy, fill in the minimum runnable prerequisites and adaptation checklist, verify numerical stability under fixed criteria, make fault recovery and checkpointing standard actions, and finally solidify them into a reusable process with the acceptance checklist.
After passing the acceptance checklist, the training pipeline can enter a near-out-of-the-box state that is reproducible, recoverable, and maintainable. As the operator ecosystem matures and automated toolchains develop, frontier large models are expected to truly achieve the leap on domestic full-function GPUs from “can train” to “stably re-trainable.”
