Foundations to Frontier
Tests
C. Programming, Tools and HPC › C6 Distributed Training

Data Parallelism (DDP)

Data parallelism is the simplest way to train on many GPUs: every GPU holds a full copy of the model, processes a different slice of each batch, and the gradients are averaged with an all-reduce so all copies take the same step. This topic covers PyTorch DistributedDataParallel (process groups, launching with torchrun, DistributedSampler and set_epoch, parameter broadcast, gradient buckets overlapping communication with backward, no_sync, SyncBatchNorm), why the result equals large-batch training, and the optimization side of scaling: the effective batch size grows with the number of GPUs, so learning rates must be adjusted (linear or square-root scaling, warmup) and very large batches eventually stop helping. In the exercises you simulate DDP to show it equals global-batch training, implement DistributedSampler, and examine BatchNorm statistics; then you train with 1 to 128 simulated workers to measure how learning-rate rules preserve accuracy as the batch grows.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Many students, one textbook

Imagine a class learning from a huge pile of exercises. Each student takes a different handful, works out how the shared notes should be corrected, and then everyone compares and averages their corrections before updating the notes together. Everyone ends up with identical notes, and the pile is finished many times faster. That’s data parallelism: every GPU has the same model, works on different data, and they average what they learned.

One data-parallel training step
rank 0rank 1rank 2rank 3rank 4rank 5rank 6rank 7blue forward · purple backward · orange all-reduce · dashed: waiting for the slowest rank
step time 44.1 ms
throughput 5809 samples/s
scaling efficiency 70%
Each worker processes 32 samples in 30 ms. The all-reduce time grows to about twice the gradient size divided by the link bandwidth, almost independent of P; hiding it behind the backward pass keeps efficiency high. Synchronous training runs at the pace of the slowest worker, so a single slow GPU, node or network link costs the whole job.
Why engineers care

Training perception models for satellites and robots on terabytes of imagery, or neural surrogates on huge simulation datasets, takes weeks on one GPU and hours on many. Data parallelism is the first tool to reach for, and understanding its batch-size and communication effects decides whether 64 GPUs actually give a 64× speed-up.

📝 Quick check (Level 0)
0/3 answered
  1. 1. In data parallelism, each GPU holds…
  2. 2. Why do the GPUs average their gradients?
  3. 3. In the demo, what does one slow GPU do?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

DistributedDataParallel

# launch: torchrun --nproc_per_node=8 --nnodes=2 --rdzv_endpoint=$MASTER:29500 train.py
import torch, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler

dist.init_process_group("nccl")                            # rank, world size from environment variables
local_rank = int(os.environ["LOCAL_RANK"]); torch.cuda.set_device(local_rank)
model = DDP(MyModel().cuda(), device_ids=[local_rank])     # broadcasts rank 0's weights to all ranks
sampler = DistributedSampler(dataset, shuffle=True)        # disjoint 1/P of the data per rank
loader = DataLoader(dataset, batch_size=32, sampler=sampler, num_workers=8, pin_memory=True)
for epoch in range(epochs):
    sampler.set_epoch(epoch)                               # otherwise every epoch uses the same shuffle
    for x, y in loader:
        loss = loss_fn(model(x.cuda()), y.cuda())
        loss.backward()                                    # gradients all-reduced (averaged) in buckets during backward
        opt.step(); opt.zero_grad()
dist.destroy_process_group()

The global batch is P × the per-GPU batch. Only rank 0 should write checkpoints and logs.

📝 Quick check (Level 1)
0/3 answered
  1. 1. 8 GPUs with batch_size=32 each give a global batch of…
  2. 2. Forgetting sampler.set_epoch(epoch)…
  3. 3. Which tool launches one process per GPU?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Why DDP equals large-batch training

With a mean loss and equal shard sizes, the average of the P shard gradients is exactly the gradient of the global batch: (1/P)Σ_p (1/b)Σ_(i∈p) ∇ℓ_i = (1/(Pb))Σ_i ∇ℓ_i. Starting from identical weights (DDP broadcasts rank 0’s at construction) and applying identical updates keeps the replicas identical. Exceptions: unequal shards weight samples unequally (the sampler pads to equal sizes; drop_last avoids the padding), BatchNorm computes statistics per GPU (use SyncBatchNorm for small per-GPU batches), and dropout and data augmentation must use different random streams per rank.

Engineering details

  • Buckets: gradients are grouped (25 MB default) and each bucket’s all-reduce starts as soon as it is ready, overlapping the rest of backward (C5.10).
  • no_sync(): skip the all-reduce on intermediate micro-batches of gradient accumulation (C6.5).
  • Unused parameters: models with conditional branches need find_unused_parameters=True (slower) or restructuring.
  • Stragglers: synchronous training runs at the speed of the slowest rank; check per-rank step times.
🐍 Exercise 1: simulating DDP
Implement DistributedSampler (padding, disjoint ranks, epoch-dependent shuffle), a DDP step that averages per-shard gradients of a linear model, rank-0 broadcast of the initial weights and per-rank versus global BatchNorm statistics; show that DDP gradients and 50 training steps equal single-device training on the global batch, and that unequal shards do not.
📝 Quick check (Level 2)
0/3 answered
  1. 1. With equal shard sizes, averaging shard gradients gives…
  2. 2. SyncBatchNorm is needed when…
  3. 3. Who should save checkpoints in DDP?

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Scaling the batch

More GPUs at a fixed per-GPU batch means a larger global batch and fewer optimizer steps per epoch. With the same learning rate, each step makes the same size move from a less noisy gradient, so training for a fixed number of epochs gets less done. Common rules: linear scaling (lr ∝ batch, Goyal et al.) with a warmup for deep networks whose early training is unstable at high learning rates; square-root scaling (lr ∝ √batch), closer to what adaptive optimizers want; layer-wise adaptive methods (LARS, LAMB) for very large batches. Beyond a problem-dependent critical batch size, larger batches give diminishing returns: you need more epochs to reach the same accuracy, so extra GPUs buy less.

Systems efficiency

Scaling efficiency = actual throughput / (P × single-GPU throughput). Communication of a G-byte gradient costs about 2G/bandwidth per step regardless of P, so efficiency depends on hiding it behind compute (bigger per-GPU batch, overlap, faster links) and on avoiding stragglers.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Linear scaling: base lr 0.1 at batch 256. lr at batch 8192?
  2. 2. Why warm up the learning rate in large-batch training?
  3. 3. Past the critical batch size, adding GPUs…

Level 4: Expert

★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.

Data parallelism, measured

Exercise 1. The sampler pads 10 samples to 12 for 4 ranks (3 each, all samples covered) and reshuffles when the epoch changes. For P = 1, 2, 4, 8 equal shards of a 256-sample batch, the averaged gradient equals the global-batch gradient, and 50 DDP steps reproduce single-device training exactly; 250 samples over 8 ranks (unequal shards) do not. With two differently distributed halves of a batch, per-rank BatchNorm means differ by more than 2 while the global mean is 1.5.

Exercise 2: scaling the batch. A 20-64-10 MLP on a 10-class problem whose best achievable accuracy is about 0.69 (32 768 samples), SGD with momentum, 32 samples per worker, base learning rate 0.01, 3 epochs:

Workers (global batch, steps) 1 (32, 3072) 8 (256, 384) 32 (1024, 96) 128 (4096, 24)
same learning rate 0.689 0.687 0.661 0.460
linear scaling 0.689 0.684 0.689 0.674
linear + 1-epoch warmup 0.689 0.687 0.687 0.659
square-root scaling 0.689 0.685 0.688 0.678

Keeping the learning rate while growing the batch starves training of progress (24 small steps at 128 workers). Scaling the learning rate recovers almost all the accuracy up to 128 workers. Warmup doesn’t help this shallow network and costs a third of its 24 steps; it matters for deep networks. A throughput model with 1 ms per sample and a 100 MB gradient over 25 GB/s links (no overlap) gives scaling efficiencies of 82%, 80% and 78% at 8, 32 and 128 workers.

🐍 Exercise 2 (research): scaling the batch with the workers
Train a small MLP with simulated data-parallel SGD (exact global-batch gradients) for 1 to 128 workers at a fixed per-worker batch and number of epochs, comparing a fixed learning rate, linear scaling, linear scaling with warmup and square-root scaling; also compute scaling efficiency from a compute-plus-all-reduce step model.

Data parallelism in AI, robotics and aerospace

  • Vision models for Earth observation and planetary imagery trained across many GPUs with DDP.
  • Neural surrogates of CFD or orbital dynamics, trained on large simulation datasets.
  • Reinforcement learning: many parallel environment workers feeding a data-parallel learner.
  • Federated variants: averaging updates across devices or ground stations that cannot share raw data.

References

  1. S. Li et al. (2020). “PyTorch Distributed: experiences on accelerating data parallel training.” Proc. VLDB Endowment, 13(12).
  2. P. Goyal et al. (2017). “Accurate, large minibatch SGD: training ImageNet in 1 hour.” arXiv:1706.02677.
  3. S. McCandlish, J. Kaplan, D. Amodei et al. (2018). “An empirical model of large-batch training.” arXiv:1812.06162.
  4. Y. You et al. (2020). “Large batch optimization for deep learning: training BERT in 76 minutes.” ICLR (LAMB).
  5. PyTorch documentation (pytorch.org/docs): DistributedDataParallel, torchrun, DistributedSampler.