MODULE 32: SETTING UP DISTRIBUTED DATA PARALLEL (DDP) TRAINING

Master multi-GPU and multi-node distributed deep learning in PyTorch. Engineer process groups with NCCL/Gloo, torchrun rendezvous launchers, DistributedSampler epoch shuffling, SyncBatchNorm conversion, no_sync() gradient accumulation, AMP mixed precision, safe Rank-0 checkpointing, AllReduce metric aggregation, elastic fault tolerance, and unused parameter graph debugging.

⚑ Real-World Context: Scaling Deep Learning Across Multi-GPU & Multi-Node Clusters

When model capacity and training corpora outgrow a single accelerator, legacy nn.DataParallel suffers from Python GIL contention, uneven GPU-0 memory saturation, and single-node limits. DistributedDataParallel (DDP) overcomes every bottleneck by spawning an independent OS process per GPU (WORLD_SIZE processes), overlapping backward-pass gradient computation with bucketed Ring All-Reduce communication across NVLink and InfiniBand.

Production distributed pipelines rely on ten foundational engineering patterns: initializing RANK, LOCAL_RANK, and WORLD_SIZE via torchrun, sharding data cleanly with DistributedSampler, launching multi-node clusters via c10d rendezvous, converting SyncBatchNorm, skipping intermediate syncs with no_sync(), pairing AMP GradScaler with DDP, saving race-free Rank-0 checkpoints, aggregating global validation metrics via dist.all_reduce, surviving Spot preemptions elastically, and handling dynamic branches with find_unused_parameters.

1. Single-Node Multi-GPU Baseline with torchrun & NCCL Process Group
Initializing a 4-GPU single-node DDP training job via dist.init_process_group(backend="nccl"), reading RANK, LOCAL_RANK, and WORLD_SIZE injected by torchrun, pinning each process to its dedicated CUDA device via torch.cuda.set_device(local_rank), and wrapping the model in DistributedDataParallel.
Python (ddp_single_node_torchrun.py)
import os
import torch
import torch.nn as nn
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP

# Launch command: torchrun --standalone --nproc_per_node=4 ddp_single_node_torchrun.py
def setup_ddp():
    dist.init_process_group(backend="nccl")
    rank = int(os.environ["RANK"])
    local_rank = int(os.environ["LOCAL_RANK"])
    world_size = int(os.environ["WORLD_SIZE"])
    torch.cuda.set_device(local_rank)
    return rank, local_rank, world_size

def train_worker():
    rank, local_rank, world_size = setup_ddp()
    model = nn.Sequential(nn.Linear(1024, 512), nn.ReLU(), nn.Linear(512, 10)).to(local_rank)
    ddp_model = DDP(model, device_ids=[local_rank], output_device=local_rank)
    optimizer = torch.optim.AdamW(ddp_model.parameters(), lr=1e-3)

    x = torch.randn(64, 1024, device=local_rank)
    y = torch.randint(0, 10, (64,), device=local_rank)
    optimizer.zero_grad()
    loss = nn.CrossEntropyLoss()(ddp_model(x), y)
    loss.backward()  # Automatically triggers bucketed Ring All-Reduce across all 4 GPUs
    optimizer.step()

    if rank == 0:
        print(f"[Rank {rank}/{world_size}] Local GPU={local_rank} | Loss={loss.item():.4f} | Global Batch={64 * world_size}")
    dist.destroy_process_group()
Output:
$ torchrun --standalone --nproc_per_node=4 ddp_single_node_torchrun.py
[Rank 0/4] Local GPU=0 | Loss=2.3041 | Global Batch=256
2. DistributedSampler & Deterministic Epoch Shuffling for 50M-Row Datasets
Partitioning a recommendation corpus across WORLD_SIZE = 4 ranks using DistributedSampler(dataset, shuffle=True, drop_last=True) so every GPU receives a disjoint slice of indices, while invoking sampler.set_epoch(epoch) before each epoch to guarantee fresh deterministic shuffles across epochs without duplicate or missing samples.
Python (ddp_distributed_sampler_shuffling.py)
import torch
from torch.utils.data import TensorDataset, DataLoader
from torch.utils.data.distributed import DistributedSampler

# Simulated 16-sample dataset partitioned across 4 DDP GPU ranks
dataset = TensorDataset(torch.arange(16).unsqueeze(1).float())

for rank in range(4):
    sampler = DistributedSampler(dataset, num_replicas=4, rank=rank, shuffle=True, seed=42, drop_last=True)
    sampler.set_epoch(0)
    indices_ep0 = list(iter(sampler))
    sampler.set_epoch(1)
    indices_ep1 = list(iter(sampler))
    print(f"Rank {rank} | Epoch 0 Indices: {indices_ep0} | Epoch 1 Indices: {indices_ep1}")
Output:
Rank 0 | Epoch 0 Indices: [5, 11, 2, 13] | Epoch 1 Indices: [14, 3, 9, 0]
Rank 1 | Epoch 0 Indices: [8, 0, 14, 7]  | Epoch 1 Indices: [6, 11, 1, 12]
Rank 2 | Epoch 0 Indices: [15, 4, 9, 1]  | Epoch 1 Indices: [15, 4, 8, 2]
Rank 3 | Epoch 0 Indices: [10, 6, 12, 3] | Epoch 1 Indices: [10, 7, 13, 5]
3. Multi-Node Cluster Setup with c10d Rendezvous Networking (32 GPUs Across 4 Nodes)
Scaling a 7B parameter LLM pre-training run across 4 physical InfiniBand nodes (8 GPUs per node = WORLD_SIZE 32) using torchrun with --rdzv_backend=c10d and --rdzv_endpoint=10.0.1.10:29500, verifying how global RANK maps cleanly to (node_rank * nproc_per_node + local_rank).
Python (ddp_multinode_c10d_rendezvous.py)
# Node 0 (Master): torchrun --nnodes=4 --nproc_per_node=8 --node_rank=0 --rdzv_id=llm_42 --rdzv_backend=c10d --rdzv_endpoint=10.0.1.10:29500 train_llm.py
# Node 1..3:       torchrun --nnodes=4 --nproc_per_node=8 --node_rank=$NODE_RANK --rdzv_id=llm_42 --rdzv_backend=c10d --rdzv_endpoint=10.0.1.10:29500 train_llm.py

nnodes = 4
nproc_per_node = 8
world_size = nnodes * nproc_per_node

for node_rank in range(nnodes):
    first_global_rank = node_rank * nproc_per_node
    last_global_rank = first_global_rank + nproc_per_node - 1
    print(f"Node {node_rank} (8x H100) -> Global Ranks [{first_global_rank:02d} .. {last_global_rank:02d}] | World Size = {world_size}")
Output:
Node 0 (8x H100) -> Global Ranks [00 .. 07] | World Size = 32
Node 1 (8x H100) -> Global Ranks [08 .. 15] | World Size = 32
Node 2 (8x H100) -> Global Ranks [16 .. 23] | World Size = 32
Node 3 (8x H100) -> Global Ranks [24 .. 31] | World Size = 32
4. SyncBatchNorm Conversion for High-Resolution Multi-GPU Computer Vision
In high-resolution Mask R-CNN or 3D medical segmentation where VRAM restricts per-GPU batch size to 2 images, standard BatchNorm2d suffers noisy per-GPU mean/variance estimates. Calling nn.SyncBatchNorm.convert_sync_batchnorm(model) before wrapping in DDP synchronizes statistics across all GPUs (effective batch size = 8).
Python (ddp_sync_batchnorm_conversion.py)
import torch
import torch.nn as nn

vision_encoder = nn.Sequential(
    nn.Conv2d(3, 32, kernel_size=3, padding=1, bias=False),
    nn.BatchNorm2d(32),
    nn.ReLU(inplace=True),
    nn.Conv2d(32, 64, kernel_size=3, padding=1, bias=False),
    nn.BatchNorm2d(64)
)

# CRITICAL ORDER: Convert BatchNorm2d -> SyncBatchNorm BEFORE calling DDP(model, ...)
sync_encoder = nn.SyncBatchNorm.convert_sync_batchnorm(vision_encoder)

torch.manual_seed(7)
rank_batches = [torch.randn(2, 1, 16, 16) + r * 1.5 for r in range(4)]
local_means = [round(b.mean().item(), 3) for b in rank_batches]
global_mean = torch.cat(rank_batches, dim=0).mean().item()

print("Converted Modules :", [type(m).__name__ for m in sync_encoder if "Norm" in type(m).__name__])
print("Per-GPU Local Mean:", local_means, "-> Synced Global Mean:", round(global_mean, 4))
Output:
Converted Modules : ['SyncBatchNorm', 'SyncBatchNorm']
Per-GPU Local Mean: [0.012, 1.489, 3.021, 4.496] -> Synced Global Mean: 2.2545
5. Gradient Accumulation with ddp_model.no_sync() to Cut NCCL Overhead
Scaling effective global batch size to 2,048 across 4 GPUs using accum_steps = 4 micro-batches while wrapping intermediate micro-steps in with ddp_model.no_sync():β€”suppressing redundant NCCL All-Reduce network traffic until the final accumulation step executes loss.backward() and optimizer.step().
Python (ddp_gradient_accumulation_nosync.py)
from contextlib import nullcontext
import torch
import torch.nn as nn

torch.manual_seed(12)
model = nn.Linear(32, 4)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
accum_steps = 4

optimizer.zero_grad()
for micro_step in range(accum_steps):
    is_sync_step = (micro_step + 1) == accum_steps
    # In DDP: sync_ctx = nullcontext() if is_sync_step else ddp_model.no_sync()
    sync_ctx = nullcontext() if is_sync_step else nullcontext()
    with sync_ctx:
        x = torch.randn(128, 32)
        y = torch.randint(0, 4, (128,))
        loss = nn.CrossEntropyLoss()(model(x), y) / accum_steps
        loss.backward()
    mode_tag = "ALL-REDUCE SYNC + STEP" if is_sync_step else "no_sync() LOCAL ACCUM"
    print(f"Micro-Step {micro_step + 1}/{accum_steps} | Grad Norm: {model.weight.grad.norm().item():.4f} | {mode_tag}")
    if is_sync_step:
        optimizer.step()
        optimizer.zero_grad()
Output:
Micro-Step 1/4 | Grad Norm: 0.2148 | no_sync() LOCAL ACCUM
Micro-Step 2/4 | Grad Norm: 0.3019 | no_sync() LOCAL ACCUM
Micro-Step 3/4 | Grad Norm: 0.3694 | no_sync() LOCAL ACCUM
Micro-Step 4/4 | Grad Norm: 0.4281 | ALL-REDUCE SYNC + STEP
6. Automatic Mixed Precision (AMP) + GradScaler Inside DDP Training Loops
Combining torch.amp.autocast(dtype=torch.float16) and GradScaler with DistributedDataParallel so forward activations run in FP16 Tensor Cores, scaled gradients synchronize across GPUs during scaler.scale(loss).backward(), and scaler.unscale_(optimizer) unscales gradients cleanly prior to clip_grad_norm_.
Python (ddp_amp_mixed_precision.py)
import torch
import torch.nn as nn
from torch.amp import autocast, GradScaler

device = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(24)
model = nn.Sequential(nn.Linear(256, 256), nn.GELU(), nn.Linear(256, 10)).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
scaler = GradScaler("cuda", enabled=(device == "cuda"))

x = torch.randn(32, 256, device=device)
y = torch.randint(0, 10, (32,), device=device)

optimizer.zero_grad()
with autocast(device_type=device, dtype=torch.float16 if device == "cuda" else torch.bfloat16):
    logits = model(x)
    loss = nn.CrossEntropyLoss()(logits, y)

scaler.scale(loss).backward()          # DDP All-Reduce occurs on scaled gradients
scaler.unscale_(optimizer)             # Unscale before gradient norm clipping
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer)
scaler.update()

print(f"AMP Compute Dtype: {logits.dtype} | Loss: {loss.item():.4f} | Clipped Grad Norm: {grad_norm.item():.4f}")
Output:
AMP Compute Dtype: torch.bfloat16 | Loss: 2.3189 | Clipped Grad Norm: 0.4812
7. Safe Rank-0 Checkpointing, Unwrapping .module & Barrier Synchronization
Preventing shared-filesystem write collisions and module. state-dict key mismatches by saving ddp_model.module.state_dict() exclusively on RANK == 0, synchronizing all ranks via dist.barrier(), and loading checkpoints with map_location={"cuda:0": f"cuda:{local_rank}"} to avoid Rank-0 GPU OOM spikes.
Python (ddp_rank0_checkpoint_barrier.py)
import io
import torch
import torch.nn as nn

# Unwrapped model state_dict avoids "module." prefix keys so checkpoints load cleanly on single-GPU inference
base_model = nn.Sequential(nn.Linear(16, 8), nn.ReLU(), nn.Linear(8, 2))
optimizer = torch.optim.Adam(base_model.parameters(), lr=1e-3)

# Rank 0 serialization (ddp_model.module.state_dict())
buffer = io.BytesIO()
checkpoint = {
    "epoch": 5,
    "model_state_dict": base_model.state_dict(),
    "optimizer_state_dict": optimizer.state_dict()
}
torch.save(checkpoint, buffer)
# dist.barrier() blocks Ranks 1..N until Rank 0 completes disk write

buffer.seek(0)
restored = torch.load(buffer, map_location="cpu", weights_only=True)
print("Saved State Keys :", list(restored["model_state_dict"].keys()))
print("Restored Epoch   :", restored["epoch"], "| Clean Single-GPU Inference Ready: True")
Output:
Saved State Keys : ['0.weight', '0.bias', '2.weight', '2.bias']
Restored Epoch   : 5 | Clean Single-GPU Inference Ready: True
8. Global Validation Metric Aggregation via dist.all_reduce Across GPU Shards
Because DistributedSampler splits validation samples across all GPUs, logging Rank 0's local accuracy only reflects 1 / WORLD_SIZE of the validation set. Packing [loss_sum, correct_count, sample_count] into a 3-element GPU tensor and calling dist.all_reduce(stats, op=dist.ReduceOp.SUM) computes exact global validation metrics.
Python (ddp_global_validation_allreduce.py)
import torch

# Simulated local validation accumulators [loss_sum, correct_preds, total_samples] across 4 DDP GPUs
rank_stats = torch.tensor([
    [142.4, 892.0, 1000.0],  # GPU 0 (89.2% local acc)
    [158.1, 874.0, 1000.0],  # GPU 1 (87.4% local acc)
    [131.9, 908.0, 1000.0],  # GPU 2 (90.8% local acc)
    [149.6, 886.0, 1000.0],  # GPU 3 (88.6% local acc)
], dtype=torch.float64)

# Equivalent to dist.all_reduce(stats, op=dist.ReduceOp.SUM) across all 4 ranks
global_stats = rank_stats.sum(dim=0)
global_loss = (global_stats[0] / global_stats[2]).item()
global_acc = (global_stats[1] / global_stats[2]).item() * 100.0

print(f"Rank 0 Local-Only Acc : {(rank_stats[0, 1] / rank_stats[0, 2]).item() * 100:.2f}% (Biased 1/4 shard)")
print(f"AllReduce Global Loss : {global_loss:.4f} | Global Acc: {global_acc:.2f}% (Exact 4,000 samples)")
Output:
Rank 0 Local-Only Acc : 89.20% (Biased 1/4 shard)
AllReduce Global Loss : 0.1455 | Global Acc: 89.00% (Exact 4,000 samples)
9. Elastic Fault-Tolerant Training on Preemptible Cloud Spot GPUs
Configuring torchrun --nnodes=1:4 --nproc_per_node=8 --max_restarts=3 with checkpoint epoch recovery so when a preemptible cloud Spot node is reclaimed mid-run, the remaining workers automatically re-form the rendezvous group and resume training seamlessly from the last committed epoch without losing progress.
Python (ddp_elastic_spot_recovery.py)
# Launch command:
# torchrun --nnodes=1:4 --nproc_per_node=8 --max_restarts=3 --rdzv_id=spot_job_9 --rdzv_backend=c10d --rdzv_endpoint=10.0.1.10:29500 elastic_train.py

state = {"epoch": 0, "global_step": 0, "active_nodes": 4}
total_target_epochs = 6

for ep in range(1, total_target_epochs + 1):
    if ep == 4 and state["active_nodes"] == 4:
        # Simulate Spot preemption on Node 3 -> torchrun restarts workers with 3 active nodes from epoch 3
        state["active_nodes"] = 3
        print(f"[ALERT] Spot Node Preempted at Epoch {ep}! Rendezvous Re-formed (Nodes={state['active_nodes']}, GPUs={state['active_nodes']*8}) -> Resuming from Epoch {state['epoch']}")
    state["epoch"] = ep
    state["global_step"] += 500
    print(f"Committed Epoch {state['epoch']}/{total_target_epochs} | Active GPUs={state['active_nodes']*8} | Step={state['global_step']}")
Output:
Committed Epoch 1/6 | Active GPUs=32 | Step=500
Committed Epoch 2/6 | Active GPUs=32 | Step=1000
Committed Epoch 3/6 | Active GPUs=32 | Step=1500
[ALERT] Spot Node Preempted at Epoch 4! Rendezvous Re-formed (Nodes=3, GPUs=24) -> Resuming from Epoch 3
Committed Epoch 4/6 | Active GPUs=24 | Step=2000
Committed Epoch 5/6 | Active GPUs=24 | Step=2500
Committed Epoch 6/6 | Active GPUs=24 | Step=3000
10. Handling Conditional Branches & Unused Parameters in Multi-Task / MoE Models
In multi-task or Mixture-of-Experts (MoE) networks where conditional routing skips certain task heads on specific batches, standard DDP hangs waiting for unused parameter gradient buckets. Passing find_unused_parameters=True (and static_graph=True when unused sets are constant) inspects the autograd graph so DDP reduces only active parameters.
Python (ddp_unused_parameters_moe.py)
import torch
import torch.nn as nn

class MultiTaskRoutingNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.shared_trunk = nn.Linear(32, 32)
        self.vision_head = nn.Linear(32, 5)
        self.language_head = nn.Linear(32, 10)

    def forward(self, x: torch.Tensor, route: str) -> torch.Tensor:
        h = torch.relu(self.shared_trunk(x))
        return self.vision_head(h) if route == "vision" else self.language_head(h)

torch.manual_seed(5)
model = MultiTaskRoutingNet()
# Wrap in DDP with: DDP(model, device_ids=[local_rank], find_unused_parameters=True)

for route in ["vision", "language"]:
    model.zero_grad()
    out = model(torch.randn(8, 32), route=route)
    out.sum().backward()
    unused = [name for name, p in model.named_parameters() if p.grad is None]
    print(f"Route='{route:<8}' | Active Params: {6 - len(unused)}/6 | Unused Params Bypassed by DDP: {unused}")
Output:
Route='vision  ' | Active Params: 4/6 | Unused Params Bypassed by DDP: ['language_head.weight', 'language_head.bias']
Route='language' | Active Params: 4/6 | Unused Params Bypassed by DDP: ['vision_head.weight', 'vision_head.bias']