Building a Two-Node, 16-GPU Training Pipeline: A Stable 400-Step Practice Guide

    This technical article presents a complete, reproducible setup for distributed training of a 13B-parameter transformer model across two servers with 16 GPUs. It covers parallel strategy design (tensor parallelism within a node, data parallelism across nodes), DeepSpeed ZeRO-2 configuration, initialization code, communication overlap, memory management, and step-by-step validation for running 400 stable training steps. Practical configuration examples and performance monitoring metrics are included, allowing readers to replicate and verify the same pipeline in their own environments.

    Introduction

    Training a large model on two servers with a total of 16 GPUs requires solving three challenges simultaneously: memory capacity, cross-node communication, and long-run stability. This article describes a complete pipeline based on a two-node, 16-GPU distributed training practice—from parallel configuration and initialization code to a stable 400-step run. The configurations provided here can be reused directly, and the acceptance criteria are clearly defined so that you can validate your own environment using the same method.

    Example Environment and Assumptions

    The example environment used in this article is:

    • Two servers, each with 8 GPUs of 80 GB memory, interconnected via NVLink within each server.
    • 200 Gb/s InfiniBand network between the two servers.
    • PyTorch 2.x, CUDA 12.1, NCCL 2.18, DeepSpeed 0.14.
    • Model: a decoder-only Transformer with 13B parameters, hidden size 5120, 40 attention heads, context length 4096.

    The 13B scale is selected because it fits on 16 GPUs and is easy to reproduce. For models with hundreds of billions of parameters on the same GPU count, ZeRO-3 with CPU or NVMe offloading is typically required, and both memory and throughput must be re-evaluated; the configuration in this article does not directly apply.

    Parallel Strategy: Tensor Parallelism Within a Node, Data Parallelism Across Nodes

    The two-node, 16-GPU topology determines the parallel approach. Bandwidth between GPUs inside a node is much higher than between nodes, so communication-intensive tensor parallelism should be confined within a single node, while data parallelism—which has lower communication overhead—can span nodes.

    This example uses a 2D parallel configuration with TP=8 and DP=2:

    • Tensor parallelism (TP) group: the 8 GPUs on each server. Every layer performs all-reduce during both forward and backward passes, requiring frequent communication that must use the intra-node NVLink.
    • Data parallelism (DP) group: GPUs with the same index across servers, e.g., GPU 0 on server 0 and GPU 0 on server 1 (or in rank terms, rank 0 and rank 8). Only one gradient synchronization is needed per training step.

    The TP degree must divide the model’s attention head count, hidden dimension, and FFN dimension. In this example, 40 attention heads are divisible by 8, so each GPU handles 5 heads. If the model had 36 heads, TP=8 would not be valid; you would need TP=4 or TP=6 and re-check the topology.

    This article does not introduce pipeline parallelism (PP). Pipeline parallelism between two machines would introduce bubbles, and with TP=8 + ZeRO-2 the 13B model already fits in memory, so adding PP would bring limited benefit while increasing debugging complexity.

    ZeRO Sharding Scope and Stage Selection

    ZeRO shards states within a data-parallel group. In this example, DP=2, so the ZeRO sharding factor is 2, not 16. Treating all 16 GPUs as a single sharding pool would be incorrect.

    The three ZeRO stages differ as follows:

    • ZeRO-1: shards optimizer states (fp32 master weights and Adam momentum).
    • ZeRO-2: additionally shards gradients.
    • ZeRO-3: shards model parameters as well, performing all-gather on demand during forward and backward.

    ZeRO-2 is chosen for two reasons. First, based on this configuration, after TP sharding each GPU holds about 1.63B parameters. The bf16 weights account for roughly 3.25 GB, gradients after 2-way sharding ~1.6 GB, and optimizer states after 2-way sharding ~9.75 GB. The total is about 15 GB plus activations and communication buffers, leaving adequate headroom. Second, ZeRO-3 would perform cross-node all-gather of parameters at each layer’s forward and backward, and this communication overhead is not worthwhile given the limited inter-node bandwidth in this setup.

    Initialization and Training Entry Point

    Launch Command

    Execute these commands on each server. Node 0 uses NODE_RANK=0, node 1 uses NODE_RANK=1.

    1. export MASTER_ADDR=10.0.0.1 # Node 0's internal IP
    2. export NCCL_SOCKET_IFNAME=eth0 # Replace with your network interface name
    3. export NCCL_IB_HCA=mlx5 # Replace with your IB device name
    4. export TORCH_NCCL_ASYNC_ERROR_HANDLING=1
    5. torchrun --nnodes=2 --nproc_per_node=8 --node_rank=${NODE_RANK} \
    6. --master_addr=${MASTER_ADDR} --master_port=29500 \
    7. train.py --config cfg.yaml

    torchrun injects environment variables such as RANK, WORLD_SIZE, and LOCAL_RANK for each process.

    Distributed Initialization

    1. import os
    2. import torch
    3. import torch.distributed as dist
    4. def init_dist():
    5. rank = int(os.environ["RANK"])
    6. world_size = int(os.environ["WORLD_SIZE"])
    7. local_rank = int(os.environ["LOCAL_RANK"])
    8. torch.cuda.set_device(local_rank)
    9. dist.init_process_group(
    10. backend="nccl",
    11. init_method="env://",
    12. rank=rank,
    13. world_size=world_size,
    14. )
    15. dist.barrier()
    16. return rank, world_size, local_rank

    Calling set_device before initializing the process group prevents all processes from defaulting to GPU 0.

    Building TP and DP Groups

    torch.distributed.new_group must be called by every process for every group, so the following loop runs on all ranks.

    1. import torch.distributed as dist
    2. def build_parallel_groups(world_size, tp_size):
    3. assert world_size % tp_size == 0
    4. dp_size = world_size // tp_size
    5. # Consecutive tp_size ranks form a TP group, i.e., the 8 GPUs within one server
    6. tp_ranks = [list(range(i * tp_size, (i + 1) * tp_size))
    7. for i in range(dp_size)]
    8. # Ranks with stride tp_size form a DP group, i.e., GPUs with the same index across servers
    9. dp_ranks = [list(range(j, world_size, tp_size))
    10. for j in range(tp_size)]
    11. my_rank = dist.get_rank()
    12. my_tp_group, my_dp_group = None, None
    13. for ranks in tp_ranks:
    14. group = dist.new_group(ranks)
    15. if my_rank in ranks:
    16. my_tp_group = group
    17. for ranks in dp_ranks:
    18. group = dist.new_group(ranks)
    19. if my_rank in ranks:
    20. my_dp_group = group
    21. return my_tp_group, my_dp_group

    With world_size=16 and tp_size=8, the TP groups are [0..7] and [8..15], and the DP groups are [0, 8], [1, 9], …, [7, 15].

    DeepSpeed Configuration and Batch Calculation

    1. ds_config = {
    2. "train_batch_size": 32,
    3. "train_micro_batch_size_per_gpu": 2,
    4. "gradient_accumulation_steps": 8,
    5. "bf16": {"enabled": True},
    6. "gradient_clipping": 1.0,
    7. "zero_optimization": {
    8. "stage": 2,
    9. "overlap_comm": True,
    10. "contiguous_gradients": True,
    11. "reduce_bucket_size": 500000000,
    12. },
    13. }

    train_batch_size equals the product of micro-batch size per GPU, gradient accumulation steps, and DP size: 2 × 8 × 2 = 32. When using TP, you must pass the TP group information to DeepSpeed via the mpu interface; otherwise, DeepSpeed will treat all 16 GPUs as data-parallel and compute incorrect batch sizes.

    The global tokens per training step are 32 × 4096 = 131072. Use this number for throughput and MFU calculations later.

    Computation-Communication Overlap

    After the backward pass, gradients need to be reduce-scattered across nodes. If communication waits until the entire backward pass completes, the network is idle during computation and computation is idle during communication.

    This example applies three techniques:

    1. Enable overlap_comm. Gradients are grouped into buckets. As soon as gradients for a bucket are computed, an asynchronous all-reduce is started on a separate communication stream, while backward computation for earlier layers continues.
    2. Tune reduce_bucket_size. A bucket that is too large delays communication start; too small creates many small messages with high launch overhead. This example starts with 5e8 elements and compares two or three values between 1e8 and 1e9.
    3. Synchronize gradients only on the last micro-batch. During gradient accumulation, earlier micro-batches do not need communication. DeepSpeed handles this automatically; if using native DDP, wrap earlier micro-batches with no_sync.

    Two common pitfalls:

    • Asynchronous synchronization requires that all gradients in a bucket are ready. If you have custom gradient hooks or changed the order of parameter computation, check bucket dependencies, otherwise silent gradient errors may occur.
    • Do not frequently call synchronous CUDA operations like loss.item() or tensor.cpu() in the training loop. Read scalar values only at logging intervals; otherwise the overlap effect is disrupted.

    On the first run, set NCCL_DEBUG=INFO to confirm that communication uses InfiniBand rather than Socket. If the log shows NET/Socket, cross-node communication has degraded to TCP and throughput will drop significantly. In that case, check NCCL_IB_HCA and network interface settings before adjusting the model or parallel strategy.

    Memory Management

    Activation Recomputation

    This example enables activation recomputation for every Transformer layer. During the forward pass, only the layer input is saved; activations inside the layer are recomputed during backward. This significantly reduces activation memory at the cost of extra computation (roughly one additional forward pass), increasing total training time by about one-third.

    Therefore, recomputation is not enabled by default. Test without recomputation first, and only enable it if peak memory approaches the limit. Record tokens/s before and after enabling.

    Allocator Configuration

    Over long runs, memory fragmentation can cause out-of-memory (OOM) errors even when free memory exists. This example sets:

    1. export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

    Also record torch.cuda.max_memory_allocated() every 50 steps to detect if peak memory gradually rises over time. A persistent increase often indicates unreleased references or cached intermediate tensors.

    OOM Troubleshooting Order

    When an OOM occurs, follow this order, changing one thing at a time:

    1. Reduce the micro-batch size and increase gradient accumulation steps to keep the global batch size unchanged.
    2. Enable activation recomputation.
    3. Check whether sequence lengths exceed the configuration, e.g., abnormally long samples in the data.
    4. As a last resort, consider ZeRO-3 or CPU offloading, as these add significant communication or CPU overhead.

    Running and Validating 400 Training Steps

    Pre-Run Checks

    Before the full run, execute 10 steps with the same configuration and confirm:

    • Both nodes’ processes initialize correctly and print the expected rank and world_size.
    • Per-GPU memory usage is close to the estimated value.
    • The loss at the first step is a finite number (not NaN or Inf).

    Monitoring Metrics

    During training, record the following:

    • Loss and gradient norm. The gradient norm should stay below the clipping threshold and not remain pinned at the maximum.
    • Time per step and tokens/s.
    • Peak memory usage.
    • MFU.

    MFU is calculated as:

    MFU = 6 × N × T ÷ (G × P)

    where N is the number of model parameters, T is tokens processed per second, G is the number of GPUs, and P is the theoretical peak FLOPS per GPU. For this example, N=13e9, G=16, and P is 312 TFLOPS (the dense bf16 peak for an A100).

    Using this formula, each token requires about 7.8e10 floating-point operations, and the cluster’s theoretical peak is about 4.99e15 FLOPS, giving a theoretical throughput upper limit of about 64k tokens/s. Actual MFU is usually far below 100% because communication, data loading, and non-matrix operations consume time.

    Two clarifications: First, the formula ignores attention computation (which is masked out for simplicity), and second, accuracy can be improved by substituting the actual number of floating-point operations for the forward and backward pass per token if precision is needed.