Data Parallelism and All-Reduce
Every strategy so far ran on one device. That stops being enough when an epoch takes a day: pretraining a backbone on millions of images, fine-tuning on a large corpus, or rerunning a training job many times for a hyperparameter search. The simplest way to use more devices is data parallelism: give every device a full copy of the model, give each one a different slice of every mini-batch, and make them agree on one gradient before anybody updates. Done right, the result is the same model you would get on one machine with the big batch, only faster.
The idea
One step has four parts. Scatter the mini-batch into equal shards. Compute forward and backward on each worker, independently and in parallel. All-reduce the gradients: every worker ends up holding their average. Update with the same optimiser on every worker. Because the copies start identical and apply identical updates, they never drift apart, and nobody has to send weights around after the first step.
Why the averaged gradient is the same gradient
Training minimises the mean loss over a mini-batch of size . Split into disjoint shards of equal size . Because the gradient of a sum is the sum of the gradients:
So data parallelism is not an approximation: it computes exactly the gradient of the global batch, up to floating-point rounding. Two conditions make this true: the shards are equally large (otherwise each must be weighted by ), and the loss of one example depends only on that example and . Batch normalisation breaks the second condition, because it normalises with statistics of the local shard; more on that under pitfalls. (Why the mini-batch gradient is a good estimate of the full gradient in the first place is the subject of stochastic gradient descent and batches, steps and epochs.)
From scratch: four workers in NumPy
Logistic regression on 512 generated examples. One mini-batch of 128 is split into four shards of 32; each "worker" sees only its shard. Then both versions train for 200 steps on the same mini-batches.
import numpy as np
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=512, n_features=10, n_informative=6, random_state=0)
X = np.hstack([X, np.ones((len(X), 1))]) # bias column
def grad(w, X, y):
"""Gradient of the mean log-loss of logistic regression on (X, y)."""
p = 1 / (1 + np.exp(-X @ w))
return X.T @ (p - y) / len(y)
rng = np.random.default_rng(0)
w0 = rng.normal(0, 0.1, X.shape[1])
batch = rng.choice(len(y), 128, replace=False) # one mini-batch of 128 examples
Xb, yb = X[batch], y[batch]
g_single = grad(w0, Xb, yb) # one machine, whole batch
N = 4
shards = np.array_split(np.arange(128), N) # 4 workers, 32 examples each
g_workers = [grad(w0, Xb[s], yb[s]) for s in shards] # each worker: its own shard only
g_avg = np.mean(g_workers, axis=0) # all-reduce (sum) / N
print("worker 0 gradient (first 3):", np.round(g_workers[0][:3], 4))
print("worker 1 gradient (first 3):", np.round(g_workers[1][:3], 4))
print("average of 4 workers :", np.round(g_avg[:3], 4))
print("single machine, batch 128 :", np.round(g_single[:3], 4))
print("equal up to rounding (< 1e-12):", bool(np.abs(g_avg - g_single).max() < 1e-12))
# train both ways for 200 steps with the same mini-batches
w_one, w_dp = w0.copy(), w0.copy()
for step in range(200):
b = rng.choice(len(y), 128, replace=False)
w_one -= 0.5 * grad(w_one, X[b], y[b])
g = np.mean([grad(w_dp, X[b[s]], y[b[s]]) for s in shards], axis=0)
w_dp -= 0.5 * g # every replica applies the same update
acc = lambda w: ((X @ w > 0) == y).mean()
print(f"after 200 steps: weights equal (< 1e-12): {bool(np.abs(w_one - w_dp).max() < 1e-12)}, "
f"training accuracy {acc(w_one):.3f} vs {acc(w_dp):.3f}")
# unequal shards: a plain mean of worker gradients is no longer the batch gradient
uneven = [np.arange(0, 80), np.arange(80, 128)]
g_plain = np.mean([grad(w0, Xb[s], yb[s]) for s in uneven], axis=0)
g_weighted = sum(len(s) * grad(w0, Xb[s], yb[s]) for s in uneven) / 128
print(f"shards of 80 and 48: plain mean off by {np.abs(g_plain - g_single).max():.4f}, "
f"size-weighted off by less than 1e-12: {bool(np.abs(g_weighted - g_single).max() < 1e-12)}")worker 0 gradient (first 3): [-0.4801 0.3162 0.2519]
worker 1 gradient (first 3): [-0.5674 0.4287 0.5398]
average of 4 workers : [-0.2518 0.2264 0.2777]
single machine, batch 128 : [-0.2518 0.2264 0.2777]
equal up to rounding (< 1e-12): True
after 200 steps: weights equal (< 1e-12): True, training accuracy 0.861 vs 0.861
shards of 80 and 48: plain mean off by 0.0493, size-weighted off by less than 1e-12: True
Each worker's gradient is a noisy estimate from 32 examples (worker 0 and worker 1 disagree in every coordinate), but their average is the 128-example gradient. After 200 steps the two training runs still have the same weights, so they reach the same training accuracy, 0.861. With unequal shards the plain mean is off by 0.0493 in one coordinate; weighting each gradient by its shard size fixes it. Libraries avoid the problem by giving every worker the same number of examples (PyTorch's DistributedSampler pads or drops to make shards equal).
All-reduce: how the workers agree
All-reduce takes one vector from each of workers and leaves every worker holding their sum (divide by for the mean). The obvious implementation is a parameter server: everyone sends its gradient of numbers to one machine, which adds them and sends the result back. The server then receives numbers per step, and its network link becomes the bottleneck as grows.
Ring all-reduce removes the central machine. The workers form a ring, and each splits its vector into chunks:
- Reduce-scatter, steps: in every step each worker sends one chunk to its right neighbour, which adds it to its own copy of that chunk. After steps each worker holds the complete sum of one chunk.
- All-gather, more steps: the finished chunks travel round the ring, and each worker overwrites its stale copy.
Each worker sends chunks of size , so the traffic per worker is
which barely grows with : adding workers does not make the all-reduce much slower, as long as the ring's links run in parallel. The simulation below runs both phases on four workers, prints which chunk moves where, and counts the traffic.
import numpy as np
def ring_all_reduce(grads, verbose=False):
"""Sum equal-length vectors held by N workers in a ring; every worker ends with the sum."""
N = len(grads)
chunks = [np.array_split(g.astype(float), N) for g in grads] # chunks[worker][c]
sent = 0
# phase 1, reduce-scatter: in step s, worker r sends chunk (r - s) % N to worker r + 1, which adds it
for s in range(N - 1):
msgs = [(r, (r - s) % N, chunks[r][(r - s) % N].copy()) for r in range(N)]
for r, c, data in msgs:
chunks[(r + 1) % N][c] += data
sent += data.size
if verbose:
print(f"reduce-scatter step {s + 1}: " + ", ".join(f"w{r}->w{(r + 1) % N} chunk {c}" for r, c, _ in msgs))
# now worker r holds the full sum of chunk (r + 1) % N
# phase 2, all-gather: pass the finished chunks around the ring, overwriting
for s in range(N - 1):
msgs = [(r, (r + 1 - s) % N, chunks[r][(r + 1 - s) % N].copy()) for r in range(N)]
for r, c, data in msgs:
chunks[(r + 1) % N][c] = data
sent += data.size
if verbose:
print(f"all-gather step {s + 1}: " + ", ".join(f"w{r}->w{(r + 1) % N} chunk {c}" for r, c, _ in msgs))
return [np.concatenate(c) for c in chunks], sent
grads = [np.array([1, 2, 3, 4]) * (r + 1) for r in range(4)] # worker r holds (r+1) * [1, 2, 3, 4]
out, sent = ring_all_reduce(grads, verbose=True)
print("expected sum :", sum(grads))
for r, o in enumerate(out):
print(f"worker {r} ends with:", o.astype(int))
print("\nnumbers sent per worker for a gradient of M = 120,000 numbers")
rng = np.random.default_rng(0)
M = 120_000
for N in [2, 4, 8, 16]:
gs = [rng.normal(size=M) for _ in range(N)]
out, sent = ring_all_reduce(gs)
ok = all(np.allclose(o, sum(gs)) for o in out)
print(f"N = {N:2d}: ring {sent // N:>7,d} (formula {2 * (N - 1) * M // N:>7,d}), "
f"a parameter server receives {N * M:>9,d}, correct: {ok}")reduce-scatter step 1: w0->w1 chunk 0, w1->w2 chunk 1, w2->w3 chunk 2, w3->w0 chunk 3
reduce-scatter step 2: w0->w1 chunk 3, w1->w2 chunk 0, w2->w3 chunk 1, w3->w0 chunk 2
reduce-scatter step 3: w0->w1 chunk 2, w1->w2 chunk 3, w2->w3 chunk 0, w3->w0 chunk 1
all-gather step 1: w0->w1 chunk 1, w1->w2 chunk 2, w2->w3 chunk 3, w3->w0 chunk 0
all-gather step 2: w0->w1 chunk 0, w1->w2 chunk 1, w2->w3 chunk 2, w3->w0 chunk 3
all-gather step 3: w0->w1 chunk 3, w1->w2 chunk 0, w2->w3 chunk 1, w3->w0 chunk 2
expected sum : [10 20 30 40]
worker 0 ends with: [10 20 30 40]
worker 1 ends with: [10 20 30 40]
worker 2 ends with: [10 20 30 40]
worker 3 ends with: [10 20 30 40]
numbers sent per worker for a gradient of M = 120,000 numbers
N = 2: ring 120,000 (formula 120,000), a parameter server receives 240,000, correct: True
N = 4: ring 180,000 (formula 180,000), a parameter server receives 480,000, correct: True
N = 8: ring 210,000 (formula 210,000), a parameter server receives 960,000, correct: True
N = 16: ring 225,000 (formula 225,000), a parameter server receives 1,920,000, correct: True
Follow chunk 0 in the log: worker 0 sends it to worker 1 in step 1, worker 1 adds its own and passes it to worker 2 in step 2, worker 2 to worker 3 in step 3. Worker 3 now holds chunk 0 summed over all four workers, and the all-gather phase hands it on to worker 0, 1 and 2. Going from 2 to 16 workers, the ring traffic per worker grows only from 120,000 to 225,000 numbers, while a parameter server would have to receive 16 times the gradient. Real libraries (NCCL on GPUs, Gloo on CPUs) use rings, trees or a mix, but the cost is the same order: about per worker.
With PyTorch: torch.distributed.all_reduce
PyTorch's torch.distributed package provides all-reduce for real processes. The example starts 4 processes on the CPU with the gloo backend, all-reduces a small tensor, then averages gradients by hand exactly as the NumPy version did, and compares with one process that sees all 128 examples.
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch import nn
def worker(rank, world_size):
os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT="29501", GLOO_SOCKET_IFNAME="lo")
dist.init_process_group("gloo", rank=rank, world_size=world_size) # gloo = the CPU backend
# 1. all_reduce on a small tensor: every rank ends with the sum
t = torch.tensor([1.0, 2.0, 3.0, 4.0]) * (rank + 1)
before = t.clone()
dist.all_reduce(t, op=dist.ReduceOp.SUM)
rows = [None] * world_size
dist.all_gather_object(rows, (rank, before.tolist(), t.tolist()))
# 2. gradient averaging by hand: same model on every rank, a different shard of the batch
torch.manual_seed(0) # same seed -> same initial weights everywhere
model = nn.Linear(10, 1)
g = torch.Generator().manual_seed(1)
X, y = torch.randn(128, 10, generator=g), torch.randn(128, 1, generator=g)
shard = slice(rank * 32, (rank + 1) * 32) # rank r gets examples 32r .. 32r+31
nn.functional.mse_loss(model(X[shard]), y[shard]).backward()
for p in model.parameters():
dist.all_reduce(p.grad, op=dist.ReduceOp.SUM) # sum over ranks ...
p.grad /= world_size # ... then average
if rank == 0:
for r, b, a in rows:
print(f"rank {r}: before {b} -> after all_reduce {a}")
torch.manual_seed(0)
ref = nn.Linear(10, 1) # the same initial weights
nn.functional.mse_loss(ref(X), y).backward() # one process, all 128 examples
diff = (ref.weight.grad - model.weight.grad).abs().max().item()
print("averaged gradient == single-process gradient on 128 examples (float32, < 1e-6):", diff < 1e-6)
dist.destroy_process_group()
if __name__ == "__main__":
mp.spawn(worker, args=(4,), nprocs=4) # 4 processes on 4 CPU threadsrank 0: before [1.0, 2.0, 3.0, 4.0] -> after all_reduce [10.0, 20.0, 30.0, 40.0]
rank 1: before [2.0, 4.0, 6.0, 8.0] -> after all_reduce [10.0, 20.0, 30.0, 40.0]
rank 2: before [3.0, 6.0, 9.0, 12.0] -> after all_reduce [10.0, 20.0, 30.0, 40.0]
rank 3: before [4.0, 8.0, 12.0, 16.0] -> after all_reduce [10.0, 20.0, 30.0, 40.0]
averaged gradient == single-process gradient on 128 examples (float32, < 1e-6): True
The vocabulary: the world size is the number of processes, the rank is a process's number (0 to world size - 1), and rank 0 usually does the printing, logging and saving. init_process_group connects the processes through a rendezvous address (MASTER_ADDR, MASTER_PORT); on GPUs the backend is nccl, on CPUs gloo. Writing the all-reduce loop yourself works but is slow, because it waits for the whole backward pass before communicating. DDP in PyTorch does the same averaging automatically and overlaps it with the backward pass.
How much faster? A step-time model
Data parallelism keeps the per-device batch fixed (as large as fits in memory) and grows the global batch to times that, so an epoch needs times fewer steps. Each step now costs the compute time plus the all-reduce time, unless the two overlap. A back-of-the-envelope model for a 100-million-parameter model (fp32 gradients, 400 MB per step) with 0.30 s of compute per step:
# A step-time model for data parallelism (arithmetic only, no real hardware)
params = 100e6 # 100 million parameters
grad_bytes = params * 4 # fp32 gradients: 400 MB per step
compute = 0.30 # seconds per step on one device, per-device batch fixed at 32
examples = 1_280_000 # one epoch
def epoch_minutes(N, bandwidth, overlap):
comm = 2 * (N - 1) / N * grad_bytes / bandwidth if N > 1 else 0.0 # ring all-reduce
step = max(compute, comm) if overlap else compute + comm
steps = examples / (32 * N) # global batch = 32 N
return steps * step / 60, comm
base = epoch_minutes(1, 1, False)[0]
print(f"1 device: {base:.0f} min per epoch")
for name, bw in [("1.25 GB/s (10 Gbit Ethernet)", 1.25e9), ("10 GB/s (PCIe-class)", 10e9),
("100 GB/s (NVLink-class)", 100e9)]:
print(name)
for N in [2, 4, 8, 16]:
t_seq, comm = epoch_minutes(N, bw, overlap=False)
t_ovl, _ = epoch_minutes(N, bw, overlap=True)
print(f" N = {N:2d}: all-reduce {comm * 1000:3.0f} ms/step | speed-up {base / t_seq:5.2f} "
f"without overlap, {base / t_ovl:5.2f} with overlap")1 device: 200 min per epoch
1.25 GB/s (10 Gbit Ethernet)
N = 2: all-reduce 320 ms/step | speed-up 0.97 without overlap, 1.88 with overlap
N = 4: all-reduce 480 ms/step | speed-up 1.54 without overlap, 2.50 with overlap
N = 8: all-reduce 560 ms/step | speed-up 2.79 without overlap, 4.29 with overlap
N = 16: all-reduce 600 ms/step | speed-up 5.33 without overlap, 8.00 with overlap
10 GB/s (PCIe-class)
N = 2: all-reduce 40 ms/step | speed-up 1.76 without overlap, 2.00 with overlap
N = 4: all-reduce 60 ms/step | speed-up 3.33 without overlap, 4.00 with overlap
N = 8: all-reduce 70 ms/step | speed-up 6.49 without overlap, 8.00 with overlap
N = 16: all-reduce 75 ms/step | speed-up 12.80 without overlap, 16.00 with overlap
100 GB/s (NVLink-class)
N = 2: all-reduce 4 ms/step | speed-up 1.97 without overlap, 2.00 with overlap
N = 4: all-reduce 6 ms/step | speed-up 3.92 without overlap, 4.00 with overlap
N = 8: all-reduce 7 ms/step | speed-up 7.82 without overlap, 8.00 with overlap
N = 16: all-reduce 8 ms/step | speed-up 15.61 without overlap, 16.00 with overlap
Three lessons from the arithmetic. With a fast interconnect the all-reduce is a few milliseconds and the speed-up is close to . Over 10 Gbit Ethernet the 400 MB all-reduce takes longer than the compute: two machines without overlap are slower than one (0.97), and even with perfect overlap 16 machines give only 8 times the speed. And overlap matters: DDP starts all-reducing the gradients of the last layers while backward is still computing the first ones. The model ignores latency, stragglers and data loading, so real speed-ups are lower; measure, do not assume.
The batch size changes: learning rate and warm-up
With workers and a per-device batch of , the optimiser sees a global batch of . Larger batches give less noisy gradients but fewer steps per epoch, so the same learning rate makes less progress per epoch. The common linear scaling rule multiplies the learning rate by along with the batch, , and ramps it up over the first few hundred steps (warm-up) because a large learning rate on random weights is unstable. It is a rule of thumb, not a law: beyond some batch size (it depends on the problem) accuracy drops however the learning rate is set, and adaptive optimisers such as Adam usually need less than linear scaling. When you change the number of devices, you change a hyperparameter; re-tune on the validation set.
The other direction also works. Gradient accumulation simulates workers on one device: run micro-batches one after another, add their gradients, and update once. It gives exactly the same update as data parallelism with workers (same mathematics as above), only times slower, which is handy to reproduce a large-batch run on a small machine.
Pitfalls
- Different initial weights. Every replica must start from the same weights (same seed, or rank 0 broadcasts them; DDP broadcasts at construction). Otherwise the averaged gradient belongs to no model.
- Every rank reading the same data. Each rank needs its own shard; a
DistributedSampler(withset_epoch(epoch)every epoch, or the shuffle repeats) does this. Without it, workers process the same examples times. - Batch normalisation. BatchNorm statistics are computed per device, so with small per-device batches they are noisy and the result differs from single-device training.
SyncBatchNormall-reduces the statistics too, at a communication cost. - Logging and saving from every rank. Four processes writing the same checkpoint file corrupt it, and four progress bars are unreadable. Rank 0 saves and logs; the others wait at a barrier.
- Expecting bit-identical results. Floating-point addition is not associative, so summing the same gradients in a different order (another ring size, another library) changes the last bits. Results are reproducible for a fixed setup, not across different numbers of devices.
- Forgetting the learning rate. Doubling the devices doubles the global batch; the old learning rate is now a different experiment.
Practice
- A model has 350 million parameters and trains with fp32 gradients on 8 GPUs with ring all-reduce. How many bytes does each GPU send per step?
- Four workers have shards of 40, 40, 40 and 8 examples (the last batch of an epoch). They all-reduce and divide by 4. Which examples get too much weight?
- You trained on 1 GPU with batch 64 and learning rate 0.1. You move to 4 GPUs with batch 64 each. What learning rate does the linear scaling rule suggest, and what else should you add?
- In the step-time model, why is the speed-up with overlap exactly for the two faster links but not for Ethernet?
Answers
- The gradient is GB. Each GPU sends GB per step.
- The 8 examples of the last shard: their mean gradient counts as much as each shard of 40, so each of them weighs 5 times as much as an example in the other shards. Weight by shard size, or drop or pad the last batch so all shards are equal (
drop_last=True). - Global batch 256, so by the rule, with a warm-up from a small value over the first few hundred steps. Then check the validation curve, since the rule is only a starting point.
- With overlap a step costs . On the two faster links the all-reduce (at most 75 ms) is shorter than the 300 ms of compute, so it hides completely and each step still costs 300 ms. On Ethernet it takes 320 to 600 ms, longer than the compute, so communication sets the step time.
Test yourself
Four workers each compute the mean-loss gradient on an equal shard of a 128-example batch. What does averaging the four gradients give?
- An approximation that gets better with more workers
- Exactly the gradient of the mean loss on all 128 examples, up to rounding
- The gradient of the largest shard
- A gradient 4 times too large
In ring all-reduce with workers and a gradient of numbers, how much does each worker send?
Why must every data-parallel replica start from the same weights?
- To save memory
- Because the averaged gradient is applied to every replica; if they start different, they stay different and the average belongs to no model
- Because the backend requires it for gloo only
- It does not matter
You go from 1 to 8 GPUs with the same per-device batch. What changes for the optimiser?
- Nothing
- The global batch is 8 times larger, so the learning rate (and warm-up) usually needs to change
- The loss function
- The number of parameters