Adapting Domestic GPUs for LLM Training: Key Steps and Validation Boundaries
Training adaptation on domestic GPUs is far more demanding than inference adaptation because the software stack must support the full training pipeline—weight loading, parameter sharding, forward and backward computation, gradient synchronization, optimizer updates, and checkpointing—over days or weeks of continuous operation. This article explains why short tests can hide critical failures, demonstrates how to implement FSDP2 sharded training with memory estimation formulas, and shows how to measure cross-node collective communication bandwidth to validate a training setup.
1. Why Training Adaptation Is Harder Than Inference Adaptation
Inference adaptation typically requires only wiring up the key operators, running the forward pass, and comparing the output against a reference. This cycle is short and can be done on a single machine with a single GPU. Training adaptation, by contrast, requires the software stack to support the complete pipeline: weight loading, parameter sharding, forward and backward computation, gradient synchronization, optimizer updates, and checkpoint saving. The entire pipeline must also run continuously for days or even weeks.
The differences are summarized in the table below.
| Dimension | Inference Adaptation | Training Adaptation | Common Validation Method |
|---|---|---|---|
| Operator coverage | Forward operators only | All operators needed for forward, backward, and the optimizer | Compare outputs and gradients operator by operator against a reference implementation |
| Communication volume | Usually small, possibly only tensor parallelism | Parameter gathering and gradient reduction coexist, with heavy cross-node traffic | Measure collective communication bandwidth and record per-step communication time |
| Numerical stability | A single correct forward output is enough | No overflow or divergence over long runs | Log per-step loss, gradient norm, and non-finite value counts |
| Fault recovery | Generally not needed | Jobs must resume from checkpoints after interruption | Kill the process mid-run, resume, and compare loss curves before and after |
Every item in this table can be masked by a short test. For example, a test that runs a few dozen steps can cover the common operators but may never hit a backward operator with an uncommon shape. Therefore, training adaptation validation must be layered, and each layer should clearly state what was tested and what was not.
2. How to Implement FSDP2 Sharded Training
FSDP2 is PyTorch’s fully sharded data parallelism solution. It shards each layer’s parameters, gradients, and optimizer states across all GPUs. During the forward pass, the full parameters needed by a given layer are temporarily reconstructed via an all-gather operation and released immediately after computation. As a result, each GPU only holds its own shard long-term, and memory usage scales down linearly with the number of GPUs.
The code skeleton below uses the PyTorch 2.x API as an example. Device strings, communication backend names, and dependency versions must be replaced according to the vendor’s documentation—do not assume they match an NVIDIA environment.
import osimport torchimport torch.distributed as distfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicydef setup():# Backend name and device string depend on the vendor's docs;# NCCL-style naming is used heredist.init_process_group(backend="nccl")local_rank = int(os.environ["LOCAL_RANK"])torch.cuda.set_device(local_rank)return init_device_mesh("cuda", (dist.get_world_size(),))def wrap_model(model, mesh):mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, # precision for forward and backward computationreduce_dtype=torch.float32, # precision for gradient reduction)for layer in model.layers: # shard layer by layer to lower peak memoryfully_shard(layer, mesh=mesh, mp_policy=mp)fully_shard(model, mesh=mesh, mp_policy=mp)return modeldef build_optimizer(model):# The optimizer must be created after sharding; otherwise it references# the pre-sharding parametersreturn torch.optim.AdamW(model.parameters(), lr=1e-4, betas=(0.9, 0.95))
Three points matter in practice. First, shard the model before creating the optimizer. Reversing the order makes the optimizer update parameters that differ from those used in the forward pass; the symptom is a loss that never decreases, and it may not raise any error. Second, the granularity of per-layer sharding affects both peak memory and communication overlap. Shards that are too large produce large temporary all-gather buffers; shards that are too small increase the number of communication calls and their overhead. Third, model initialization is best done on a meta device or CPU, with weights sharded as they are loaded, to avoid the full model first occupying a single GPU.
Memory Estimation Method
Estimating memory with a formula before launching can prevent most first-step OOM failures.
Under mixed precision, the per-parameter state memory during training is approximately:
- Parameters (stored in fp32): 4 bytes
- Gradients (stored in fp32): 4 bytes
- AdamW first and second moments: 8 bytes
That totals roughly 16 bytes per parameter. For a model with P parameters on N GPUs, the persistent state memory per GPU after sharding is about 16P / N bytes.
For a 7B model on 8 GPUs: 16 × 7×10⁹ / 8 ≈ 14 GB. Without sharding, the full model state would be about 112 GB, which does not fit on a single 64 GB GPU.
This is only the persistent state. The actual peak also includes:
- Activations: related to batch size, sequence length, and layer count—usually the largest variable. Activation recomputation reduces this at the cost of extra computation.
- All-gather buffers: only one full layer resides in memory at a time, but larger layers mean larger buffers.
- Communication workspace and memory fragmentation: as a rule of thumb, reserve 20%–30% headroom. This ratio is empirical and should be confirmed against measured peaks.
The estimate must be verified with the actual configuration. Record the peak memory before and after the first step and compare it against the formula. If the measured value is significantly higher than the estimate, check the sequence length and activation recomputation settings first.
3. How to Measure Cross-Node Communication
The per-step communication volume of FSDP2 can be roughly estimated. For a 7B model, the forward and backward passes each require one bf16 parameter all-gather of about 14 GB; gradient reduction in fp32 is about 28 GB. The theoretical per-step traffic per GPU is roughly 56 GB, multiplied by the (N−1)/N factor. This figure excludes communication-computation overlap and any other collective operations.
Actual time depends on link bandwidth and the degree of communication-computation overlap. The test method is to first measure raw collective communication bandwidth, then compare it against the per-step communication time observed during training. The script below measures algorithm bandwidth and bus bandwidth using all-reduce.
import timeimport torchimport torch.distributed as distdef bench_allreduce(size_mb=1024, iters=20):n = dist.get_world_size()x = torch.ones(size_mb * 1024 * 1024 // 4, device="cuda", dtype=torch.float32)for _ in range(5): # warm-up to exclude first-time setup overheaddist.all_reduce(x)torch.cuda.synchronize()t0 = time.time()for _ in range(iters):dist.all_reduce(x)torch.cuda.synchronize()dt = (time.time() - t0) / itersalgbw = (size_mb / 1024) / dt # GB/sbusbw = algbw * 2 * (n - 1) / n # all-reduce bus bandwidth conversionif dist.get_rank() == 0:print(f"nodes_ranks={n} algbw={algbw:.2f} GB/s busbw={busbw:.2f} GB/s")
When running these tests, keep the relevant considerations in mind and validate the results against the actual training configuration.
