Data parallelism: DDP, buckets and overlap
The simplest parallelism, always present: identical replicas process different data and average gradients. We prove equivalence to a large batch, build DDP from scratch through bucketed all-reduce overlap with backward, and address distributed sampling, unsynchronized accumulation, batch normalization and diverging ranks. We finish with scaling limits from communication and critical batch size.
After this lesson you can
- Prove data parallelism with mean all-reduce is equivalent to SGD on the global batch.
- Implement DDP from scratch with reverse-order buckets and asynchronous all-reduce overlapping backward.
- Configure distributed loading and no_sync accumulation without duplicating examples or communication.
- Estimate scaling efficiency from compute, communication and critical batch size.
- Detect and correct replica desynchronization.
Before you start
- 21Collective communication primitivesRing all-reduceProcess groups and distributed launchGradient accumulation
- 15Learning rate and batch size scalingCritical batch sizeBatch normalizationBatch norm running statistics
- 00Map-style and iterable datasetsSamplers and data orderModule hooksPseudorandom generators and independent streams
- 09Counter-based RNGs
One update, multiple machines
Imagine four copies of a network starting with the same weights. Each processes a quarter of a batch; they then exchange gradients before updating. If each copy performs exactly the same update, they remain copies and the process can repeat. The challenge is to finish communication without leaving the GPU waiting too long, and ensure the averaged loss really represents the global batch.
The figure is not a measurement. It assumes eight layers each with one compute and one data unit, latency of 0.45 per call, and one communication resource. Each bucket starts when all its layers are ready and previous communication ends. Step time is the maximum of the two finish times. It excludes interference between compute and network, ordering changes, and variation between layers. It reveals the tension between latency and overlap rather than predicting a cluster.
The average is the global-batch gradient
Synchronous data parallelism maintains one model replica per rank. Each rank computes loss on its examples and an all-reduce delivers the same reduced gradient to all. With ranks and examples per rank, the global batch has examples, assuming partitions do not overlap.
Proof
For rank , . By linearity of differentiation and summation,
Applying the same update function to the same parameter, gradient, and state produces the same result. In floating point, summation order can change rounding. Equality also requires corresponding randomness when comparing with a particular monolithic run.
∎Averaging local means is insufficient if valid token counts differ. If rank has tokens and loss sum , the correct loss is , not . DDP averages gradients across ranks: to obtain the global token mean, each rank can backpropagate after communicating the denominator. The accumulated batch adds a time dimension: normalization must cover all its microbatches too.
Buckets and launch order
The naive version computes all backward, flattens the gradient, and executes all-reduce. The network is idle until computation ends. Gradient bucketing and overlap organizes parameters into buckets. A hook marks a gradient available; when all members of the next bucket are ready, an asynchronous collective starts. Backward continues while communication progresses, provided backend and hardware permit concurrency.
Order approximately reverse to registration often places parameters near the output ready first. This is a heuristic: branches, shared weights, and actual autograd order can change it. Every replica must call collectives in the same order: hook arrival alone cannot determine call order. In the lab we maintain an ordered queue of ready buckets. We wait for all handles before using gradients; the sent buffer must remain alive and unmodified during the operation.
A parameter without a gradient never triggers its hook. In a naive implementation it leaves the bucket waiting. DDP can detect unused parameters with find_unused_parameters=True, at the cost of traversing the graph. All replicas must follow a compatible collective protocol even if the graph varies. See the DDP design notes and hook documentation: the post-accumulation hook is registered on leaf tensors and receives the parameter, not the gradient, as its argument.
Data, accumulation, and normalization
Distributed sampling gives each rank a partition of a shared permutation. DistributedSampler receives the same global size and seed, and rank identifies its part. Call sampler.set_epoch(epoch) before creating the iterator each epoch; otherwise the permutation repeats. With drop_last=False, the sampler may pad indices so all partitions have equal length, duplicating some examples. With drop_last=True, it drops the tail. During evaluation, account for duplicates or use a sampler that does not introduce them.
Per-rank seeds are useful for different augmentations and masks. Do not confuse different seeds with different weights: if everyone applies the same reduced gradient and optimizer, copies remain equal. Reproducibility also requires setting worker seeds, saving random states, and documenting nondeterministic operations. Review counter-based generators and samplers.
from torch.utils.data import DataLoader, DistributedSampler
# Una vez inicializado el grupo: rank y world_size identifican esta réplica.
sampler = DistributedSampler(dataset, num_replicas=world_size, rank=rank,
shuffle=True, seed=123, drop_last=True)
loader = DataLoader(dataset, batch_size=local_batch, sampler=sampler,
shuffle=False, num_workers=0)
for epoch in range(num_epochs):
sampler.set_epoch(epoch)
for batch in loader:
train_step(batch)
The example removes extra indices to keep partitions equal without repeating them in that epoch. This does not imply every example appears in every epoch. The permutation seed is shared; use separate per-rank and per-worker streams for random transformations. If evaluation needs an exact partition, do not combine sampler padding with a mean that counts those examples twice.
In “Local step” the fourth rank mistakenly applies its own gradient instead of the already available average. This does not simulate an incomplete collective: if one rank skips a call others await, the usual result is a wait or error, not a correct average of the others. In “Missing gradient” the bucket of our simple protocol never becomes ready and no step occurs; an implementation detecting this can resolve it with a compatible protocol across ranks.
Synchronized batch normalization computes statistics over a group of ranks rather than using local statistics. Batch normalization couples examples in a batch: splitting it and calculating local means and variances changes the function, so the earlier proof does not apply. SyncBatchNorm requires a compatible group and configuration; synchronizing statistics has a cost. Its running statistics are buffers with their own rules, not averaged gradients. For transformers, LayerNorm avoids this cross-example dependence.
Accumulation with no_sync avoids a reduction per microbatch. Include both forward and backward of the first microbatches in with ddp.no_sync():, and run the last outside the context to reduce the accumulated sum. Divide each loss by the number of microbatches only when they have equal effective weight; for unequal tokens use the global denominator. Call zero_grad before the window and step after synchronization, and ensure all ranks execute the same sequence.
# Esquema para micro-lotes de igual tamaño; ddp ya está construido.
optimizer.zero_grad(set_to_none=True)
for i, batch in enumerate(microbatches):
context = ddp.no_sync() if i < len(microbatches) - 1 else nullcontext()
with context:
loss = loss_fn(ddp(batch)) / len(microbatches)
loss.backward()
optimizer.step()
Import nullcontext from contextlib in the real program. Clipping, if used, comes after synchronization; with mixed precision unscale before clipping. Interruption or differing microbatch counts across ranks can cause indefinite waits.
Scaling and the training target
Scaling efficiency is for fixed global work; under weak scaling with fixed local batch, it can be defined as throughput at divided by times throughput at one. State which you use. Exposed latency adds to the critical path; not all communication is exposed. For an ideal -byte ring all-reduce, each rank sends bytes and the model is , with in bytes per second. Actual topology, contention, and protocol can change the result.
The second curve combines systems and optimization. In this illustrative model the number of examples needed grows with batch size; it is not a universal law or a guarantee that a particular learning rate reaches the same loss. McCandlish and colleagues empirically study how gradient-noise scale predicts the largest useful batch in several tasks. Critical size changes during training. Measuring samples per second without time and quality to a target can hide extra work.
Multiplying batch size by eight can be accompanied by a linear rule or square-root rule . These are recipes, not exact equivalences. Gradual warm-up reduces initial risk but its duration must be stated in steps or examples: with eight times more examples per step, retaining step count multiplies warm-up examples by eight. Goyal and colleagues combined linear scaling and warm-up in their ImageNet experiment; their result does not guarantee success on another task.
Lab: simulate events
This cell reproduces the first figure’s model and searches integer capacities. Each layer takes one unit; each communication takes for layers. There is one communication queue and no interference. Output is a prediction of that model, not a result from the PyTorch paper.
def simulate(cap, bw=1, layers=8, alpha=0.45):
end = 0.0
events = []
for i in range(0, layers, cap):
n = min(cap, layers - i)
start = max(i + n, end)
end = start + alpha + n / bw
events.append((i + n, start, end))
return max(layers, end), events
for cap in range(1, 9):
print(cap, round(simulate(cap)[0], 2))
print('mejor capacidad:', min(range(1, 9), key=lambda c: simulate(c)[0]))In PyTorch Distributed, the authors study combining buckets, overlap, and skipped synchronizations. In their figure 7, with 16 GPUs, ResNet50, and NCCL, they find greatest speed between 10 and 25 MB; with BERT and NCCL the best tested size is 50 MB, whereas with Gloo 5 MB wins on both models. These values depend on implementation and experimental system, not universal tuning. Our simulator shares the intermediate-optimum trend but does not reproduce their measurements. Change latency and bandwidth and check that the model optimum can move.
Local lab: four processes and three reducers
The next cell creates a temporary program and starts four independent CPU Gloo processes. Three paths start from the same model: reduction at the end, hooks with a two-parameter bucket queue, and DistributedDataParallel. Each performs one SGD step on the same partitioned batch and is compared with the monolithic reference. The example uses a static graph where every parameter receives a gradient; it does not implement missing-parameter tolerance, recovery, or GPU production. For a real model, use DDP.
import os, socket, subprocess, sys, tempfile
from pathlib import Path
program = r'''
import os, sys
import torch
import torch.distributed as dist
from torch import nn
from torch.nn.parallel import DistributedDataParallel as DDP
torch.set_num_threads(1)
rank, port = int(sys.argv[1]), sys.argv[2]
dist.init_process_group('gloo', init_method='tcp://127.0.0.1:' + port,
rank=rank, world_size=4)
torch.manual_seed(7)
def model():
return nn.Sequential(nn.Linear(3, 5), nn.Tanh(), nn.Linear(5, 1))
x = torch.arange(24, dtype=torch.float32).reshape(8, 3) / 24
y = torch.arange(8, dtype=torch.float32).reshape(8, 1) / 8
base = model()
for p in base.parameters():
dist.broadcast(p.data, src=0)
initial = {k: v.detach().clone() for k, v in base.state_dict().items()}
ref = model(); ref.load_state_dict(initial)
torch.optim.SGD(ref.parameters(), lr=0.05).zero_grad()
((ref(x) - y)**2).mean().backward()
with torch.no_grad():
for p in ref.parameters(): p -= 0.05 * p.grad
for mode in ('ingenuo', 'hooks', 'ddp'):
net = model(); net.load_state_dict(initial)
params = list(net.parameters())
ready, pending, handles = set(), [], []
reverse_params = list(reversed(params))
buckets = [reverse_params[i:i+2] for i in range(0, len(params), 2)]
next_bucket = [0]
def mark(p):
ready.add(id(p))
while next_bucket[0] < len(buckets) and all(id(q) in ready for q in buckets[next_bucket[0]]):
bucket = buckets[next_bucket[0]]
buf = torch.cat([q.grad.detach().reshape(-1) for q in bucket])
work = dist.all_reduce(buf, async_op=True)
pending.append((bucket, buf, work))
next_bucket[0] += 1
if mode == 'hooks':
handles = [p.register_post_accumulate_grad_hook(mark) for p in params]
wrapped = DDP(net) if mode == 'ddp' else net
pred = wrapped(x[rank*2:(rank+1)*2])
((pred-y[rank*2:(rank+1)*2])**2).mean().backward()
if mode == 'ingenuo':
for p in params:
dist.all_reduce(p.grad)
p.grad /= 4
if mode == 'hooks':
assert next_bucket[0] == len(buckets), 'parámetro sin gradiente'
for bucket, buf, work in pending:
work.wait()
offset = 0
for p in bucket:
count = p.numel()
p.grad.copy_(buf[offset:offset+count].view_as(p) / 4)
offset += count
for handle in handles: handle.remove()
with torch.no_grad():
for p in params: p -= 0.05 * p.grad
error = max((a-b).abs().max().item() for a,b in zip(net.parameters(), ref.parameters()))
assert error < 1e-6, (mode, rank, error)
if rank == 0: print(mode, 'coincide con lote global:', error < 1e-6, flush=True)
dist.destroy_process_group()
'''
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / 'ddp_lab.py'
script.write_text(program, encoding='utf-8')
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = str(sock.getsockname()[1])
env = dict(os.environ, PYTHONUTF8='1', OMP_NUM_THREADS='1')
processes = [subprocess.Popen([sys.executable, str(script), str(rank), port],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
encoding='utf-8', env=env) for rank in range(4)]
try:
for proc in processes:
out, err = proc.communicate(timeout=90)
if proc.returncode:
raise RuntimeError(err or out)
if out.strip(): print(out.strip())
finally:
for proc in processes:
if proc.poll() is None: proc.kill()
for proc in processes: proc.wait()npm run lab and open the connection link.The hook marks each parameter ready and only copies and launches when every bucket member is ready. The exercise below constructs a capacity-based partition rather than fixing two parameters. In production, DDP’s reducer manages buffers, order, and special cases. The experiment validates numerical equality for one CPU step; it does not measure real overlap or GPU speed. The temporary port is reserved and released before launch; another application could occupy it between those events, requiring a retry.
Diagnose divergence
DDP synchronizes parameters when constructing the wrapper under its usual configuration, but the optimizer is not automatically synchronized. Initialize the group before the wrapper, create equivalent optimizers, and load the same state when resuming. A skipped step on one rank, a manual weight change, or differing optimizer states cause divergence even if the next gradient is reduced. Different dropout masks do not themselves cause that divergence.
Compare complete parameters or maximum differences across ranks, not just a checksum: two different vectors can have the same sum. When a collective fails, check order, shapes, device, and step count on all ranks. Save checkpoint and common logs from one rank, with a barrier or completion protocol if other processes depend on the file. Include optimizer, scheduler, sampler, and RNG state for resuming. Also read process groups.
Ejercicios
Step 1 of 3. What is the local gradient?
def bucketize(sizes, cap):
...import math
print('milisegundos:', 2*7/8*124e6*2/50e9*1000)
print('porcentaje de 300 ms:', (2*7/8*124e6*2/50e9*1000)/300*100)
print('tasas:', 0.001*8, 0.001*math.sqrt(8))Replica equality depends on a common update and equal initial states. Overlap reduces the communication critical path, while batch size and optimization determine whether more throughput actually reduces time to the desired quality.