LLM Training Adaptation on Domestic GPUs: From Inference to Full-Scale Training

    This article explains how to distinguish three levels of model-hardware compatibility: Day-0 inference adaptation, training adaptation, and foundation model pretraining. It then walks through a sharded training path built around FSDP2, covering model loading, sharded scheduling, gradient synchronization, and the global gradient norm in mixed-precision clipping. Next, it explains cross-node coordination on a two-node, 16-GPU cluster, including parallelism strategy combinations, topology-aware scheduling, and common pitfalls such as NCCL hangs and mismatched random seeds. Developers will also find a stability acceptance checklist based on consecutive optimizer updates and NaN/Inf handling. The article closes with practical recommendations and an FAQ for teams evaluating domestic GPU solutions.

    1. First, Define the Terms: Inference Adaptation, Training Adaptation, and Foundation Pretraining

    In the domestic compute ecosystem, claims such as “a chip now supports a given LLM” are easy to misread. To understand what they actually mean, start by separating three concepts that are often used interchangeably:

    • Day 0 inference adaptation: on the day a model is released, the chip vendor has already integrated the required operators and runtime. The model can run on the hardware and complete forward inference, which verifies that the inference path is usable.
    • Training adaptation: establishing the full training loop, including model loading, parameter sharding and scheduling, forward and backward computation, gradient synchronization, and optimizer updates. This requires the framework, communication libraries, mixed-precision handling, and memory management to work together stably over long runs.
    • Foundation pretraining: training a model from random initialization on massive corpora. It involves scheduling at the thousand-GPU scale, checkpoint resumption, and fault tolerance over weeks or even months.

    The three levels can be compared as follows:

    Dimension Inference adaptation Training adaptation Foundation pretraining
    Acceptance goal Forward pass runs end to end Backward loop is stable Convergence and model quality targets are met
    Typical timeframe Days Weeks Weeks to months
    Compute scale Single GPU to single node Two nodes to tens of GPUs Thousand-GPU clusters
    Toolchain requirements Inference engine Training framework + communication libraries Full-stack fault-tolerant scheduling

    Completing training adaptation for a model on a chip does not mean the model has been pre-trained on that chip. Conflating “one training run works” with “full pretraining is supported” is the most common misconception in technical discussions today. Understanding this boundary is essential for accurately assessing how mature a domestic compute solution really is.

    2. The Training Path: Sharded Training Built Around FSDP2

    The core challenge in trillion-parameter training is that a single GPU’s memory cannot hold the full set of parameters, optimizer states, and activations. Fully Sharded Data Parallel (FSDP) dynamically aggregates and releases parameter shards at each stage of training, spreading memory overhead across all nodes. Compared with earlier versions, FSDP2 places more emphasis on explicit per-parameter sharding. This makes shard state more controllable and makes combining sharding with quantization and various parallelism strategies clearer.

    A complete sharded training path consists of three stages:

    1. Model loading: split the full set of weights according to the sharding rules and assign the shards to each device’s memory, avoiding peak memory usage on any single GPU.
    2. Sharded scheduling: during the forward pass, parameter shards are gathered with all-gather on demand and released immediately after computation. The backward pass gathers the parameter shards again to recompute gradients, then reduces the gradients with reduce-scatter. Note that gradient shards do not directly participate in backward re-aggregation. Backward propagation needs the complete parameters to recompute activation gradients, and gradients are only sharded and reduced after they have been computed.
    3. Gradient synchronization: reduce-scatter reduces gradients across nodes and scatters the results back to each local shard. Each optimizer then updates its local parameter shard.

    Minimum runnable dependencies (align these before verification):

    • PyTorch ≥ 2.4 (stable version of the high-level fully_shard API)
    • A matching CUDA and GPU driver version
    • An NCCL communication library version compatible with the hardware

    Example verification command: torchrun --nproc_per_node=N train.py.

    The following is a sample FSDP2 training skeleton:

    1. import torch
    2. from torch.distributed.fsdp import fully_shard
    3. from torch.distributed.device_mesh import init_device_mesh
    4. # Environment variables injected by torchrun: MASTER_ADDR, MASTER_PORT, RANK, WORLD_SIZE
    5. torch.distributed.init_process_group(backend="nccl")
    6. world_size = torch.distributed.get_world_size()
    7. mesh = init_device_mesh("cuda", (world_size,))
    8. # Apply sharding layer by layer to the Transformer blocks and the root module
    9. model = MyModel(config)
    10. for block in model.transformer_blocks:
    11. fully_shard(block, mesh=mesh)
    12. fully_shard(model, mesh=mesh)
    13. for step, batch in enumerate(dataloader):
    14. loss = model(**batch).loss
    15. loss.backward()
    16. # Under FSDP2, clip_grad_norm_ all-reduces the squared local norms of all shards
    17. # across shards and takes the square root of the sum to return the global
    18. # gradient norm (works with DTensors)
    19. grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
    20. optimizer.step()
    21. optimizer.zero_grad(set_to_none=True)

    A note on how gradient clipping is computed: under FSDP2/DTensor, parameters and gradients are sharded DTensors. clip_grad_norm_ all-reduces the squared local norm of each shard across all shards and takes the square root of the total, which yields the global gradient norm. Therefore, isfinite checks and logging should use this aggregated global norm, not per-GPU local values. Otherwise, you may misjudge training stability. For multimodal models, the vision encoder, the cross-modal alignment layers, and the language backbone often use different sharding strategies. The training path must coordinate these heterogeneous submodules within a unified scheduling framework.

    3. Cross-Node Distributed Coordination: Two Nodes, 16 GPUs

    Single-node multi-GPU runs can only verify tensor parallelism and inter-GPU communication. Real training must cross node boundaries. Consider a mid-sized validation cluster of two nodes and 16 GPUs:

    • Combining parallelism strategies: data parallelism (DP) scales throughput, tensor parallelism (TP) splits individual layers, pipeline parallelism (PP) splits layers across stages, and expert parallelism (EP) handles sparse MoE models. All four must be configured together according to model size and network topology.
    • Collective communication efficiency: cross-node traffic relies mainly on all-reduce, reduce-scatter, and all-gather. Performance depends heavily on network bandwidth and topology. Communication volume must be effectively overlapped with computation, or it will become a bottleneck.
    • Topology-aware scheduling: keep TP groups, which have high communication density, within a single node’s high-speed interconnect. Reserve cross-node links for the DP and PP dimensions, whose communication is relatively sparse.
    • Consistency and fault tolerance: optimizer states, random seeds, and data sampling order must remain consistent across all processes.

    Common mistakes:

    • Choosing the wrong NIC: using the management NIC instead of the high-speed RDMA/RoCE NIC causes a sharp drop in bandwidth.
    • NCCL hangs: NCCL_SOCKET_IFNAME and NCCL_IB_HCA are not set correctly, so collective operations deadlock.
    • Mismatched random seeds: seeds are not aligned across processes, so forward results diverge.
    • State drift: optimizer states or data sampling order differ across processes. The inconsistencies accumulate and eventually cause training to diverge.

    During validation, have all 16 training processes complete several hundred to a thousand consecutive optimizer updates. A few hundred steps cover normal communication pressure. A thousand steps help expose cumulative state inconsistencies and occasional numerical issues. The exact number depends on cluster size and validation goals. The larger the cluster and the closer it is to production, the higher the count should be.

    4. Training Stability: Acceptance Checklist

    Numerical overflow (NaN/Inf) is the most insidious and most critical failure mode. It may surface only after hundreds of steps and is hard to reproduce. Whether a training adaptation is truly reliable comes down to a core question: do the loss and gradient norm stay finite across consecutive updates? Common safeguards include:

    • Mixed-precision strategy: use BF16/FP16 for forward and backward passes. FP16 requires loss scaling to prevent small gradients from underflowing, while BF16 is more robust thanks to its larger dynamic range.
    • Gradient clipping: use clip_grad_norm to cap the gradient norm and suppress occasional gradient spikes.
    • Numerical health checks: verify at every step that the loss and gradient norm are finite.

    Acceptance checklist:

    • Number of consecutive update steps: several hundred to a thousand consecutive optimizer updates with no abnormal interruptions.
    • Log fields: step, loss, grad_norm, lr, throughput, and memory usage, all traceable throughout the run.
    • Handling of non-finite values: when NaN/Inf is detected, log the context and trigger skip_update.
    • Rollback or skip strategy: specify whether to skip the current update or roll back to the most recent healthy checkpoint.
    • Reproducibility criteria: fix random seeds, data sampling order, and dependency versions so that results can be reproduced.
    1. if not torch.isfinite(loss) or not torch.isfinite(grad_norm):
    2. log.warning(f"step={step} non-finite: loss={loss.item()}, "
    3. f"grad_norm={grad_norm.item()}")
    4. skip_update = True # Skip this update and trigger diagnostics

    Keeping the loss and gradient norm finite across several hundred to a thousand consecutive updates, with no overflow and no abnormal interruptions, means three things have been verified together: operator numerical correctness, communication consistency, and the soundness of the precision strategy. That is worth far more than a single successful forward pass.

    5. From “Training Works” to “Out-of-the-Box Training”

    Getting one training run to work is only the starting point. The real challenge is reproducible engineering capability:

    1. Depth of operator adaptation: extend coverage from forward inference operators to complete, performance-tuned implementations of backward gradient, communication, and optimizer operators.
    2. Automated toolchain: automate training configuration generation, checkpoint resumption, failure self-healing, and precision alignment checks. This determines whether users can migrate with minimal code changes.
    3. Progressive validation at scale: work upward from training tens-of-billions-scale scientific foundation models from scratch to full-stack native training of emerging modalities such as world models and embodied brain models. This validates the framework’s generality layer by layer.

    “Out-of-the-box training” means reducing migration and modification effort under standard interfaces and compatible software versions. It is not an unconditional promise. Developers can get a development experience close to that of the mainstream ecosystem without making deep code changes for the underlying hardware. However, this depends on aligned dependency versions, and on standard interfaces such as containerized scheduling, object storage, and monitoring and alerting continuing to evolve across the chip, framework, model, and cloud service layers.

    6. Practical Advice for Developers and FAQ

    • Distinguish the requirement level: first determine whether the goal is inference validation, training adaptation, or full pretraining. Then assess the required compute scale and toolchain depth accordingly.
    • Use stability as the benchmark: treat whether numerical values stay finite and results remain reproducible over long runs of consecutive updates as the core acceptance criterion.
    • Match parallelism strategies to the topology: combine DP/TP/PP/EP based on model structure and network topology rather than simply stacking more GPUs.

    FAQ:

    • How do I choose a solution? First consider the target level and cluster size. Then check dependency version alignment and operator coverage. Avoid judging only by whether a single step runs.
    • How do I verify a setup? Run several hundred to a thousand consecutive updates. Monitor that the loss and global gradient norm stay finite and that results are reproducible. Standardize your logs and reproducibility criteria.
    • What are common causes of failure? Choosing the wrong NIC, NCCL misconfiguration causing hangs, mismatched random seeds, and incorrect calculation of the gradient norm.

    In summary, completing training adaptation for large models on domestic full-function GPUs shows that domestic compute is moving from supporting inference to supporting stable, end-to-end training. Understanding its technical meaning, acceptance criteria, and engineering evolution path will help developers assess and adopt domestic compute solutions more rationally.