Adapting Domestic GPUs for Large Model Training: From Basic Inference to Stable Training

    This article explains the key differences between inference and training adaptation for domestic GPUs, and provides a practical guide to achieving stable large-scale model training. It covers memory reduction with Fully Sharded Data Parallel (FSDP), initialization and offloading strategies, gradient synchronization and communication overlap, and numerical stability checks with a code example for mixed-precision training. The focus is on engineering practices that move from merely running a model to sustaining reliable multi-GPU training.

    一、From Inference Adaptation to Training Adaptation

    When a chip vendor announces “Day-0 support” for a new model, that usually means inference verification: the model loads and forward computation produces outputs. Training adaptation demands far more. Training requires backward propagation, optimizer updates, and continuous operation across multiple GPUs and nodes for days or longer. The two scenarios differ significantly in operator coverage, memory planning, and communication requirements, so they should be evaluated separately.

    二、Reducing Per-GPU Memory with FSDP

    In traditional data parallelism (DP), every GPU holds a full copy of parameters, gradients, and optimizer states. With mixed precision and the Adam optimizer, a common estimate is about 16 bytes per parameter; the larger the model, the harder it is to fit on a single GPU. Fully Sharded Data Parallel (FSDP) shards these three components across ranks. When computing a specific layer, the layer’s parameters are first gathered, then released immediately after computation, so each GPU only needs to permanently store its own shard.

    Multimodal models include visual encoders, text embedding layers, and cross-modal attention modules, each with widely different structures and computational loads. In practice, the sharding wrapper should be configured at module granularity, letting each module be sharded and gathered separately, avoiding the gathering of overly large parameter blocks at once.

    The following table summarizes different parallelism strategies:

    Strategy Memory Footprint Main Communication Suitable Scenarios
    DP Full copy per GPU, highest Gradient All-Reduce Model fits entirely on a single GPU
    FSDP Parameters, gradients, optimizer states all sharded, low All-Gather and Reduce-Scatter Large parameter count, but single layers fit per GPU
    Tensor Parallelism (TP) Layer matrices split Frequent communication per layer Very large layers, with high-bandwidth interconnect within a node
    Pipeline Parallelism (PP) Layers split across devices Activations passed between adjacent stages Many layers, cross-node deployment

    In practice, start with FSDP to get training running, then decide whether to add TP or PP based on per-layer memory usage and communication overhead.

    三、Controlling Initialization Peaks and Offloading Strategies

    Out-of-memory (OOM) errors often occur during initialization when loading large models. One approach is to build the model structure on the meta device first, then instantiate parameters shard by shard, so that no single GPU ever holds the complete model at once. Checkpoints should also be read in a sharded manner, with each rank reading only its own portion.

    Offloading can further reduce memory usage. CPU offloading places parameters or optimizer states in host memory; NVMe offloading uses solid-state drives, with progressively slower speeds. Offloading increases data movement overhead and reduces throughput, so enable it only based on measured results.

    Activation checkpointing is another technique that trades computation for memory: it recomputes some forward results during backward propagation. The extra cost is roughly equivalent to one extra forward pass. It addresses a different bottleneck than offloading, and the two can be used together.

    四、Gradient Synchronization and Communication Overlap

    Cross-node gradient synchronization is a major performance bottleneck in distributed training. Ring All-Reduce has high bandwidth utilization and suits large messages; Tree All-Reduce has lower latency and suits small messages. The choice depends on gradient bucket size and network topology.

    In practice, gradient bucketing is commonly used: during backward propagation, gradients are grouped into buckets in reverse order of computation. When one bucket’s gradients are ready, its asynchronous communication starts immediately while other buckets continue computing. This overlaps communication with computation. If profiling shows that communication is not hidden, check bucket size, communication library version, and network configuration one by one. On RoCE v2 networks, verify that traffic actually uses the RDMA path, and check PFC and ECN settings.

    五、Numerical Stability Code and Troubleshooting Checklist

    Overflow and NaN are common issues in mixed-precision training. The training step function below supports both BF16 and FP16. BF16 has the same exponent bits as FP32, so GradScaler is usually unnecessary. FP16 requires GradScaler, otherwise small gradients can underflow to zero.

    1. import torch
    2. def train_step(model, optimizer, batch, loss_fn, scaler=None,
    3. max_norm=1.0, use_amp=True, amp_dtype=torch.bfloat16):
    4. """Single training step: mixed-precision forward, gradient clipping,
    5. skip update when gradients are non-finite."""
    6. optimizer.zero_grad(set_to_none=True)
    7. # Set device_type according to the PyTorch backend provided by the GPU vendor
    8. with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=use_amp):
    9. outputs = model(batch["inputs"])
    10. loss = loss_fn(outputs, batch["labels"])
    11. # FSDP parameters are sharded; use the model's own clipping method
    12. # to obtain the global gradient norm
    13. def clip(params_owner):
    14. if hasattr(params_owner, "clip_grad_norm_"):
    15. return params_owner.clip_grad_norm_(max_norm)
    16. else:
    17. return torch.nn.utils.clip_grad_norm_(
    18. params_owner.parameters(), max_norm)
    19. grad_norm = clip(model)
    20. # Use GradScaler for FP16, but skip update if gradients are non-finite
    21. if scaler is not None:
    22. scaler.scale(loss).backward()
    23. scaler.unscale_(optimizer)
    24. if torch.isfinite(grad_norm):
    25. scaler.step(optimizer)
    26. scaler.update()
    27. else:
    28. loss.backward()
    29. if torch.isfinite(grad_norm):
    30. optimizer.step()
    31. return loss

    When debugging NaN or divergence, check the learning rate and loss scale, inspect the gradient norms of different layers, and verify that the input data does not contain NaN or Inf. Also confirm that random seeds are set consistently across ranks for reproducible initialization.