13.6 Data Parallelism in Practice
In Section 13.5, our hand-written data-parallel loop slowed LeNet down on two GPUs for two reasons: a single Python thread dispatched kernels to both GPUs sequentially, and the allreduce waited until the entire backward pass had finished even though the last layers' gradients were ready much earlier.
Production data-parallel tools eliminate both bottlenecks: they either run one host process per GPU or compile a single sharded program across all GPUs, and they group gradients into buckets whose allreduces start as soon as each bucket fills during the backward pass. To test how much of the gradient exchange can be hidden behind backward compute, we move from LeNet to ResNet-18 on Fashion-MNIST images (2.2G multiply-adds per image, ~300 training FLOPs per byte of its 45 MB gradient, keeping one RTX 4090 busy for ~100 ms per 256-image step). We verify what the parallel step computes via a one-step check and measure weak and strong scaling across one, two, and four GPUs against our cost model.
import json
import os
import random
import sys13.6.1 Production Data Parallelism#
13.6.1.1 The Execution Model#
Every modern framework drives GPUs using one of two single program, multiple data (SPMD) designs:
- Multi-process ( copies + collective library): A launcher starts independent Python processes—one per GPU, each with its own rank in and its own CPU thread—that synchronize gradients through NCCL. Any Python code can run inside each process.
- Compiler-partitioned single program: The user writes a single-device step and annotates the sharding of its inputs on a device mesh; the compiler partitions the computation and inserts and schedules the collective operations automatically (Xu et al., 2021).
PyTorch uses the multi-process design: torchrun launches processes and
DistributedDataParallel (DDP) wraps the model. Because a notebook is a
single process, our helper torchrun writes a self-contained script to a
temporary file, runs torchrun --standalone --nproc-per-node=k, and parses
the JSON output of each rank.
import glob
import subprocess
import tempfile
def torchrun(script, nproc, *args, env=None):
"""Run Python source in nproc processes; return their JSON lines."""
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, 'script.py')
with open(path, 'w') as f:
f.write(script)
launcher = os.path.join(os.path.dirname(sys.executable), 'torchrun')
# Each process prints to a file of its own (--redirects 1), so that
# the lines of different processes cannot interleave
run = subprocess.run(
[launcher, '--standalone', f'--nproc-per-node={nproc}',
'--log-dir', tmp, '--redirects', '1', path, *map(str, args)],
capture_output=True, text=True, env={**os.environ, **(env or {})})
if run.returncode != 0:
raise RuntimeError(run.stderr[-3000:])
logs = sorted(glob.glob(f'{tmp}/*/attempt_0/*/stdout.log'),
key=lambda log: int(log.split(os.sep)[-2])) # By rank
return [json.loads(line) for log in logs for line in open(log)
if line.startswith('{')]
def init_distributed():
"""Join the process group of torchrun; return the rank, the number of
processes, and the GPU of this process."""
device = torch.device('cuda', int(os.environ['LOCAL_RANK']))
torch.cuda.set_device(device)
torch.distributed.init_process_group('nccl', device_id=device)
return (torch.distributed.get_rank(), torch.distributed.get_world_size(),
device)13.6.1.2 Overlapping Communication with the Backward Pass#
Production frameworks pack gradients into buckets of a few tens of megabytes in reverse layer order (the order in which backpropagation produces them) and launch each bucket's asynchronous allreduce as soon as its last gradient is ready (Li et al., 2020) (Figure 13.6.1).
Top: the allreduce waits for the whole backward pass. Bottom: the gradients are grouped into buckets, and each bucket's allreduce starts as soon as the backward pass has produced it. Only the last bucket runs after the backward pass has ended, and the earlier ones are hidden only if each allreduce finishes while the backward pass is still running.
Bucket size trades off per-call latency against overlap: tiny buckets pay many times, while a single giant bucket cannot start until the backward pass finishes. Under the ideal bucket model of overlap—assuming inter-GPU links are fast enough to finish each bucket before the next fills and that communication does not slow down concurrent backward kernels—every bucket except the last is hidden behind the backward pass.
DDP closes the first bucket at 1 MiB and subsequent buckets at 25 MiB
(bucket_cap_mb). For ResNet-18's 45 MB of gradients, DDP forms three buckets
of ~9, 26, and 9 MB (the final 9 MB bucket holds the early layers, computed
last).
13.6.1.3 The Training Step#
We define the small-image ResNet-18 of Section 7.4 (#@saved for
Chapter 20) and count its gradient bytes (45 MB in fp32):
def resnet18(num_classes, in_channels=1):
"""ResNet-18 for small images: a 3x3 stem without max-pooling, He
initialization."""
def stage(num_channels, first=False):
return [d2l.Residual(num_channels, use_1x1conv=not first,
strides=1 if first else 2),
d2l.Residual(num_channels)]
net = nn.Sequential(
# No stem bias: the batch normalization after the conv removes it
nn.Conv2d(in_channels, 64, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(64), nn.ReLU(),
*stage(64, first=True), *stage(128), *stage(256), *stage(512),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(512, num_classes))
with torch.no_grad(): # Create the lazy parameters of the blocks
net.eval()(torch.zeros(1, in_channels, 32, 32))
for m in net.modules(): # He initialization, zero biases
if isinstance(m, (nn.Conv2d, nn.Linear)):
nn.init.kaiming_normal_(m.weight, nonlinearity='relu')
if m.bias is not None:
nn.init.zeros_(m.bias)
return net.train()Next, we load Fashion-MNIST and compute ResNet-18's parameter count
num_params and fp32 gradient volume S:
We also compute the reverse-order 1 MiB and 25 MiB gradient buckets that DDP
packs before launching allreduces.
d2l.FashionMNIST() # Download once, before any process runs
net = resnet18(10)
num_params = d2l.num_params(net)
S = 4 * num_params # Gradient bytes in fp32
# DDP's buckets: the gradients in the order in which the backward pass
# produces them, the reverse of the parameters', the first bucket closed
# at 1 MiB and every later one at 25 MiB
buckets, size = [], 0
for p in reversed(list(net.parameters())):
size += 4 * p.numel()
if size >= (25 if buckets else 1) * 2**20:
buckets, size = buckets + [size], 0
buckets += [size] if size else []
last_bucket = buckets[-1] # Bytes of the bucket sent last
print(f'{num_params / 1e6:.1f}M parameters, S = {S / 1e6:.0f} MB in buckets '
f'of {", ".join(f"{b / 1e6:.1f}" for b in buckets)} MB')11.2M parameters, S = 45 MB in buckets of 9.5, 26.5, 8.7 MB
We now define the data-parallel training step on Fashion-MNIST images:
TRAIN_DDP wraps resnet18 in DDP and times train_step across processes
(with optional model.no_sync() and kernel profiling).
TRAIN_DDP = r'''
import contextlib, json, sys, torch
import torch.distributed as dist
from torch.nn import functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from d2l import torch as d2l
rank, k, device = d2l.init_distributed()
torch.backends.cudnn.benchmark = True # Tune convolutions for fixed shapes
# b examples per GPU and step; sync=0 skips the gradient allreduce, and
# profile=1 also reports the device time per step of NCCL and other kernels
b, num_steps, seed, sync, profile = map(int, sys.argv[1:])
torch.manual_seed(seed) # The same permutations everywhere
data = d2l.FashionMNIST().train # A copy on every GPU, at 64 x 64
X = F.interpolate(data.data.to(device)[:, None] / 255, 64, mode='bilinear')
y = data.targets.to(device)
model = DDP(d2l.resnet18(10).to(device), device_ids=[device])
opt = torch.optim.SGD(model.parameters(), lr=0.1)
def minibatches():
"""This process's b examples of every global minibatch of k * b."""
while True:
perm = torch.randperm(len(y), device=device)
for s in range(len(y) // (k * b)):
yield perm[(s * k + rank) * b:][:b]
def train_step(i):
opt.zero_grad(set_to_none=True)
# Under no_sync, which must enclose the forward pass as well, each GPU
# keeps its own gradient
with model.no_sync() if not sync else contextlib.nullcontext():
F.cross_entropy(model(X[i]), y[i]).backward()
opt.step()
batches = minibatches()
t = d2l.Benchmark(lambda: train_step(next(batches)), warmup=10,
repeats=num_steps).time
result = {'rank': rank, 'step_time': t}
if profile:
kernels = d2l.kernel_times(lambda: train_step(next(batches)))
result['comm'] = sum(ms for name, ms in kernels.items() if 'nccl' in name)
result['compute'] = sum(kernels.values()) - result['comm']
print(json.dumps(result))
dist.destroy_process_group()
'''13.6.1.4 A One-Step Check#
Unlike LeNet, ResNet-18 contains batch normalization (Section 7.3), which normalizes each channel by its minibatch mean and variance. When a minibatch of 256 examples is split across two GPUs, does each GPU normalize by its own 128-example shard statistics (matching gradient accumulation over two 128-example micro-batches on one GPU), or do the GPUs synchronize global 256-example statistics across cards? Let us test the two-GPU update against both single-GPU references.
CHECK_DDP = r'''
import copy, json, sys, torch
import torch.distributed as dist
from torch.nn import functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from d2l import torch as d2l
rank, k, device = d2l.init_distributed()
torch.backends.cudnn.allow_tf32 = False # Full fp32 convolutions
torch.manual_seed(int(sys.argv[1])) # The same model and data everywhere
X = torch.rand(256, 1, 64, 64, device=device)
y = torch.randint(0, 10, (256,), device=device)
model = d2l.resnet18(10).to(device)
ref = copy.deepcopy(model) # An unwrapped copy for one GPU
def update(net, shards):
"""Parameter change of one SGD step on the mean loss over the shards."""
before = [p.detach().clone() for p in net.parameters()]
for X_j, y_j in shards:
(F.cross_entropy(net(X_j), y_j) / len(shards)).backward()
with torch.no_grad():
for p, b in zip(net.parameters(), before):
p -= 0.1 * p.grad
return [p.detach() - b for p, b in zip(net.parameters(), before)]
ddp = update(DDP(model, device_ids=[device]),
[(X.chunk(k)[rank], y.chunk(k)[rank])])
if rank == 0:
gap = lambda u: max((a - b).abs().max().item() for a, b in zip(ddp, u))
halves = update(copy.deepcopy(ref), list(zip(X.chunk(k), y.chunk(k))))
print(json.dumps({'largest': max(u.abs().max().item() for u in ddp),
'full': gap(update(ref, [(X, y)])),
'halves': gap(halves)}))
dist.destroy_process_group()
'''
if d2l.num_gpus() >= 2:
r = d2l.torchrun(CHECK_DDP, 2, random.getrandbits(32))[0]
print(f"largest update {r['largest']:.1e}\n"
f"largest difference from one GPU on all 256: {r['full']:.1e}\n"
f"largest difference from one GPU on two accumulated halves: "
f"{r['halves']:.1e}")largest update 1.7e-02
largest difference from one GPU on all 256: 1.0e-03
largest difference from one GPU on two accumulated halves: 1.2e-07
By default, PyTorch DDP normalizes each GPU's shard with local per-shard
statistics—matching the two accumulated halves to ~ while differing
from full-batch statistics by several percent (converting to
nn.SyncBatchNorm synchronizes global statistics at the cost of extra
collectives; Exercise 4).
13.6.2 Scaling on Four GPUs#
We now measure weak scaling (256 examples per GPU) and strong scaling (512 examples globally) across GPUs.
def step_time(k, b, num_steps=50):
"""Seconds per DDP step on k GPUs with b examples per GPU."""
ranks = d2l.torchrun(TRAIN_DDP, k, b, num_steps, random.getrandbits(32),
1, 0) # Allreduce the gradients, no profile
return max(r['step_time'] for r in ranks)First we measure on a bare 256 MB allreduce through NCCL and compare two predictions for the exposed communication time under weak scaling:
- No overlap: the entire ring allreduce of MB is exposed ().
- Full bucket overlap: only the final bucket/buffer () is exposed after the backward pass ends.
ALLREDUCE = r'''
import json, torch
import torch.distributed as dist
from d2l import torch as d2l
_, _, device = d2l.init_distributed()
x = torch.zeros(2**26, device=device) # 64M floats: 256 MB
t = d2l.Benchmark(lambda: dist.all_reduce(x), repeats=10).time
print(json.dumps({'beta_link': t / x.nbytes})) # Each GPU sends S at k = 2
dist.destroy_process_group()
'''
def allreduce_beta(env=None):
"""beta_link of a bare 256 MB allreduce on two GPUs: the seconds
per byte that each GPU sends."""
return max(r['beta_link'] for r in d2l.torchrun(ALLREDUCE, 2, env=env))Calling allreduce_beta() yields the measured link cost beta_link, from
which we compute exposed[k] for GPUs under both the
un-overlapped () and full-overlap (last_bucket)
models:
if d2l.num_gpus() >= 2:
beta_link = allreduce_beta()
print(f'bus bandwidth = {1e-9 / beta_link:.2f} GB/s '
f'(beta_link = {1e9 * beta_link:.2f} ns/byte)')
exposed = {} # Predicted exposed seconds per step
for k in (2, 4):
ring = 2 * (k - 1) / k # Bytes that each GPU sends, per byte of S
exposed[k] = (ring * S * beta_link, ring * last_bucket * beta_link)
print(f'k={k}: exposed {1e3 * exposed[k][0]:.0f} ms without overlap '
f'({ring:.1f} S beta_link), {1e3 * exposed[k][1]:.0f} ms with '
f'full overlap (last bucket)')bus bandwidth = 2.44 GB/s (beta_link = 0.41 ns/byte)
k=2: exposed 18 ms without overlap (1.0 S beta_link), 4 ms with full overlap (last bucket)
k=4: exposed 27 ms without overlap (1.5 S beta_link), 5 ms with full overlap (last bucket)
We now benchmark weak scaling at 256 examples per GPU (step_time(k, 256))
across GPUs and compare the measured throughput, scaling
efficiency, and exposed overhead weak[k] - weak[1] against both predictions:
ks = [k for k in (1, 2, 4) if k <= d2l.num_gpus()]
weak = {k: step_time(k, 256) for k in ks}
for k in ks:
print(f'{k} GPU(s): {k * 256 / weak[k]:5.0f} examples/s, speedup '
f'{k * weak[1] / weak[k]:.2f}, efficiency {weak[1] / weak[k]:.0%}')
if k > 1: # Predicted: the one-GPU step plus the exposed communication
none, full = (weak[1] / (weak[1] + e) for e in exposed[k])
print(f'{"":10s}predicted {none:.0%} without overlap, {full:.0%} '
f'with full overlap; exposed {1e3 * (weak[k] - weak[1]):.0f} ms')1 GPU(s): 2285 examples/s, speedup 1.00, efficiency 100%
2 GPU(s): 4039 examples/s, speedup 1.77, efficiency 88%
predicted 86% without overlap, 97% with full overlap; exposed 15 ms
4 GPU(s): 7573 examples/s, speedup 3.31, efficiency 83%
predicted 80% without overlap, 95% with full overlap; exposed 23 ms
At ~2.4 GB/s bus bandwidth, an un-overlapped allreduce of 45 MB takes ~18 ms on two GPUs and ~28 ms on four. In our weak-scaling measurements, four GPUs achieve the throughput of one GPU (77–83% scaling efficiency)—matching the no-overlap prediction closely and falling well short of the full-overlap bucket prediction.
Under strong scaling (fixed global batch of 512 examples, so each of the GPUs processes examples while communication volume stays fixed), efficiency drops further at :
strong = {k: step_time(k, 512 // k) for k in ks}
for k in ks:
print(f'{k} GPU(s), {512 // k} examples each: speedup '
f'{strong[1] / strong[k]:.2f}, efficiency '
f'{strong[1] / strong[k] / k:.0%}')
d2l.plot(ks, [ks, [k * weak[1] / weak[k] for k in ks],
[strong[1] / strong[k] for k in ks]], 'GPUs', 'speedup',
legend=['linear', 'weak (256 per GPU)', 'strong (512 in all)'],
fmts=('k:', '-o', '--s'))1 GPU(s), 512 examples each: speedup 1.00, efficiency 100%
2 GPU(s), 256 examples each: speedup 1.78, efficiency 89%
4 GPU(s), 128 examples each: speedup 2.81, efficiency 70%
13.6.2.1 Assumptions of the Bucket Model#
Why did overlap hide so little of the communication? The bucket model assumes that (1) each bucket's allreduce starts during the backward pass, (2) NCCL runs at its bare benchmark rate, and (3) backward compute kernels do not slow down when NCCL runs alongside them. Profiling GPU 0 across three configurations—1 GPU, 2 GPUs without communication, and 2 GPUs with communication—tests all three assumptions:
def profile_step(k, b, communicate=True):
"""Seconds per DDP step on k GPUs with b examples per GPU, and device
milliseconds per step on GPU 0 of computation and of NCCL's kernels;
without communication, every GPU steps on its own shard's gradient."""
ranks = d2l.torchrun(TRAIN_DDP, k, b, 50, random.getrandbits(32),
int(communicate), 1)
return (max(r['step_time'] for r in ranks), ranks[0]['compute'],
ranks[0]['comm'])Running profile_step at examples per GPU across the three
configurations—one GPU, two GPUs without gradient synchronization, and two GPUs
with allreduce—separates wall-clock step time into device compute and NCCL
kernel time:
if d2l.num_gpus() >= 2:
for k, communicate in ((1, True), (2, False), (2, True)):
t, compute, comm = profile_step(k, 256, communicate)
name = f'{k} GPU' + ('s' if k > 1 else '') + (
'' if communicate else ' without communication')
print(f'{name + ":":30s}{1e3 * t:6.1f} ms per step; GPU 0 computes '
f'{compute:6.1f} ms, communicates {comm:5.1f} ms')1 GPU: 112.1 ms per step; GPU 0 computes 111.9 ms, communicates 0.0 ms
2 GPUs without communication: 111.9 ms per step; GPU 0 computes 111.5 ms, communicates 0.0 ms
2 GPUs: 126.8 ms per step; GPU 0 computes 124.6 ms, communicates 20.0 ms
Two GPUs without communication step at the exact same speed as one GPU, and NCCL's kernels run for 20–22 ms (matching the 18 ms bare benchmark). What fails is the third assumption: when NCCL runs concurrently with the backward pass, the compute kernels themselves slow down by 8–13 ms. On GPUs without peer-to-peer access, NCCL copies data through host memory using its own GPU SM kernels, which occupy streaming multiprocessors and memory bandwidth that the backward pass would otherwise use.
An undocumented NCCL flag (NCCL_SHM_USE_CUDA_MEMCPY=1, present in
NCCL 2.28–2.30) can offload those host-memory copies to the GPU's DMA copy
engines in bare microbenchmarks:
The same flag deadlocks DDP when its allreduces overlap with backward compute.
if d2l.num_gpus() >= 2:
# An undocumented parameter of NCCL's transport through host memory. It
# exists in NCCL 2.28.9 (bundled with PyTorch 2.11) and 2.30.4 (with
# jaxlib 0.12); the library of NCCL 2.31.2 no longer contains it
beta_ce = allreduce_beta({'NCCL_SHM_USE_CUDA_MEMCPY': '1'})
print(f'bus bandwidth {1e-9 / beta_link:.2f} GB/s by default, '
f'{1e-9 / beta_ce:.2f} GB/s with the copy engines '
f'({beta_link / beta_ce:.1f}x)')bus bandwidth 2.44 GB/s by default, 11.53 GB/s with the copy engines (4.7x)
On data-center GPUs connected by NVLink (450–900 GB/s per direction, Section 13.2.4.2), ResNet-18's 45 MB allreduce takes well under a millisecond and achieves near-linear scaling. Even with ideal scaling, however, data parallelism still replicates all bytes of parameter and optimizer state on every card; Section 13.7 partitions that state across GPUs.
13.6.3 Summary#
Production data parallelism drives GPUs either via independent processes synchronized through NCCL or via a single compiler-partitioned program, grouping gradients into buckets of 25–30 MiB to overlap allreduces with the backward pass. A one-step check against single-GPU references reveals whether batch normalization uses per-shard statistics or global statistics via extra collectives. On our four RTX 4090s (communicating through host memory at 2.4 GB/s bus bandwidth), four GPUs deliver single-GPU throughput under weak scaling, and kernel profiling shows that SM contention from host-staged NCCL kernels claws back most of the time saved by overlapping communication with backward computation.
13.6.4 Exercises#
- [code] Splitting the data. In
TRAIN_DDP, rank takes the slice starting at in step from a shared random permutation.- Remove
rankfrom this offset so every process takes the same examples. Predict howstep_timeat and the averaged gradient behave, and verify by printing a minibatch checksum on each rank. - Restore the offset but give each rank a different random seed. Which property of the minibatch split is lost?
- Propose a lightweight runtime assertion that catches identical data shards across ranks on the first step.
- Remove
- Weak-scaling extrapolation. Suppose a step on GPUs takes single-GPU time plus exposed communication proportional to the ring traffic .
- Express the weak-scaling efficiency in terms of a single constant, calibrate it on the measured , and compare its prediction for with the measured value in Section 13.6.2.
- With gradient accumulation over micro-batches of 256 examples per GPU (communicating only on the last micro-batch), find the smallest that raises to 95%, and state how the global batch size changes.
- [code] Bucket size. ● Model bucket overlap (Figure 13.6.1)
by assuming a backward pass of duration releases equal buckets at
times (), and each bucket's allreduce takes
sequentially, where .
- Show that the exposed communication after the backward pass finishes is
and find the optimal when versus .
- Sweep
bucket_cap_mbinDDPfrom 1 MB to 100 MB at and compare the measured exposed communication against the model.
- [code] Synchronized batch normalization. ● The one-step check of
Section 13.6.1 showed that DDP normalizes each shard with
local statistics by default.
- Convert
modelinCHECK_DDPwithnn.SyncBatchNorm.convert_sync_batchnormbefore wrapping inDDPand repeat the check. Which single-GPU reference does it match now? - Count the extra collectives per step added by
SyncBatchNorm, measurestep_timeat and , and explain why their time exceeds their byte volume times .
- Convert