Building a Dual-Node 16-GPU Training Pipeline: DDP, FP16, and Checkpointing
For teams without massive GPU clusters, validating a complete multi-node training pipeline is crucial. This article explores building a dual-node, 16-GPU training setup using Distributed Data Parallel (DDP), FP16 mixed precision, and checkpointing. It addresses common training bottlenecks such as out-of-memory errors, communication overhead, and data loading inefficiencies. Furthermore, it provides practical steps for environment verification, DDP implementation, and ensuring seamless training recovery.
I. What This Article Covers
Many teams operate with only one or two multi-GPU servers rather than large-scale clusters. For such environments, the primary goal is usually not maximizing throughput, but verifying the integrity of the training pipeline: ensuring environment version consistency, establishing multi-node communication, guaranteeing stable data reading, and enabling training recovery.
Common issues encountered during training generally fall into four categories:
- Out of Memory (OOM): Model weights, gradients, optimizer states, and activations all consume VRAM. Taking AdamW with FP32 as an example, each parameter occupies about 16 bytes (4 bytes for weights, 4 for gradients, and 4 each for the two optimizer states). For a one-billion-parameter model, this alone requires roughly 16GB, excluding activations. Whether it fits depends on the sequence length and batch size, which requires actual measurement.
- Communication Overhead: Gradient synchronization occurs at every step. Lower inter-node bandwidth means synchronization takes up a larger proportion of the time within a single step.
- Data Loading Bottlenecks: If data reading and preprocessing cannot overlap with GPU computation, the GPU will idle while waiting for data.
- Long Task Interruptions: Driver exceptions, network jitter, or OOM errors can terminate tasks. Without checkpoints, training must start from scratch.
The following sections outline environment verification, training code, mixed precision, checkpoints, measurement methods, and common issues.
II. Environment Version Verification
The test environment for this article consists of two compute nodes, each with 8 GPUs (16 in total), with 80GB of VRAM per card. Intra-node GPUs communicate via NVLink or PCIe, while inter-node communication uses a 40Gbps Ethernet network. This is a common real-world setup, though not an ideal configuration. Using RDMA or InfiniBand typically reduces communication overhead significantly.
The CUDA, driver, PyTorch, and NCCL versions on both nodes must match. Inconsistent versions often result in training starting successfully but hanging on a communication operation, or producing inexplicable deviations in the results. Before launching, run the following commands on both nodes and compare the outputs:
nvidia-smi --query-gpu=driver_version --format=csv,noheadernvcc --version | tail -n 1python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.nccl.version())"
nvcc requires the CUDA Toolkit to be installed. If only the runtime is installed on the node, you can use the output of torch.version.cuda as an alternative.
Shared storage must also be verified. Datasets and checkpoints are placed on a NAS (Network Attached Storage), and both nodes must be able to access the same path. Checkpoint writing relies on file renaming operations, so ensure the NAS mount supports renaming and that both nodes see the exact same directory.
III. Training Code Using Data Parallelism
3.1 Why Start with Data Parallelism Only
The test model in this article fits within the VRAM of a single GPU, meaning parameters and optimizer states do not need to be sharded. Data parallelism is simple to implement and has fewer potential points of failure, making it ideal for initially validating the entire pipeline. Each GPU uses 64 samples as a micro-batch, resulting in a global batch size of 16 × 64 = 1024 across 16 GPUs.
Only when the model is too large for a single GPU do you need tensor parallelism or pipeline parallelism. These methods increase communication and debugging costs and should only be enabled when genuinely necessary.
3.2 Launch Command
Execute these commands on the two nodes separately. Set master_addr to the internal IP of node 0, and use the same port for both nodes.
# Node 0torchrun --nnodes=2 --nproc_per_node=8 --node_rank=0 \--master_addr=10.0.0.1 --master_port=29500 train.py# Node 1torchrun --nnodes=2 --nproc_per_node=8 --node_rank=1 \--master_addr=10.0.0.1 --master_port=29500 train.py
In a 40Gbps Ethernet environment, it is recommended to explicitly specify the network interface used by NCCL and disable InfiniBand probing:
export NCCL_SOCKET_IFNAME=eth0 # Replace with your actual internal network interface nameexport NCCL_IB_DISABLE=1 # Use TCP transport when IB or RDMA is unavailableexport NCCL_DEBUG=WARN # Change to INFO when troubleshooting
3.3 Training Script
The script below includes DDP initialization, DistributedSampler, mixed precision, gradient clipping, periodic checkpointing, and resume logic. build_model, build_dataset, and loss_fn need to be replaced with your own implementations.
```python
import os
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
LR = 3e-4
MICRO_BATCH = 64 # Micro-batch per GPU
TOTAL_STEPS = 400
SAVE_EVERY = 100
CKPT_PATH = “/nas/ckpt/latest.pt”
def main():
dist.init_process_group(backend=”nccl”)
local_rank = int(os.environ[“LOCAL_RANK”])
rank = dist.get_rank()
torch.cuda.set_device(local_rank)
device = torch.device(“cuda”, local_rank)
model = build_model().to(device)model = DDP(model, device_ids=[local_rank])optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=0.1)scaler = torch.amp.GradScaler("cuda")dataset = build_dataset()sampler = DistributedSampler(dataset, shuffle=True, drop_last=True)loader = DataLoader(dataset,batch_size=MICRO_BATCH,sampler=sampler,num_workers=8,pin_memory=True,drop_last=True,persistent_workers=True,)step, epoch = 0, 0if os.path.exists(CKPT_PATH):step, epoch = load_checkpoint(CKPT_PATH, model, optimizer, scaler)if rank == 0:print(f"resumed from step {step}")while step < TOTAL_STEPS:sampler.set_epoch(epoch)for x, y in loader:if step >= TOTAL_STEPS:breakx = x.to(device, non_blocking=True)y = y.to(device, non_blocking=True)with torch.autocast("cuda", dtype=torch.float16):loss = loss_fn(model(x), y)optimizer.zero_grad(set_to_none=True)scaler.scale(loss).backward()scaler.unscale_(optimizer)torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)scaler.step(optimizer)scaler.update()step += 1if step
