13.5 Multi-GPU from First Principles
Every training run so far has used one GPU, even though our build workstation holds four. The simplest way to use all GPUs is data parallelism: give every GPU a full replica of the model and of each minibatch, sum the resulting gradients across GPUs with an allreduce, and apply the same parameter update on every card.
On our workstation, inter-GPU communication travels over PCIe 4.0 staged through host DRAM (Section 13.2.4.2), capping each link at a nominal 32 GB/s—roughly slower than a card's 1 TB/s on-board memory. A second GPU can shorten a step only if the computation it takes over lasts longer than the gradient exchange (and host dispatch overhead) it adds. In this section we build data parallelism by hand, derive the ring allreduce algorithm used by collective communication libraries, and construct a cost model that predicts multi-GPU step times from individually measured constants. We test our model on LeNet on Fashion-MNIST, whose tiny steps expose fixed host and communication overheads starkly.
import os
import time
# Detach PyTorch's profiler from the GPU when a profile ends; without this,
# every kernel launch after the first profile stays about 30% slower
os.environ['TEARDOWN_CUPTI'] = '1'In PyTorch, we also enable tf32 matrix multiplications and cuDNN convolution autotuning so that fixed-shape kernels run at their steady-state speed:
torch.set_float32_matmul_precision('high')
torch.backends.cudnn.benchmark = True # Time convolution algorithms per shape13.5.1 Three Ways to Split#
A model and its minibatch can be partitioned across devices in three basic ways (Figure 13.5.1):
- Data parallelism replicates the model on every device, splits the minibatch across devices, and sums gradients once per step. It works for any model that fits on a single GPU, though every device still holds all bytes of fp32 Adam training state (Section 13.4).
- Pipeline parallelism splits the layer stack across devices, passing activations forward and gradients backward at stage boundaries (Exercise 1).
- Tensor parallelism splits individual weight matrices across devices (like AlexNet across two 3 GB GPUs in 2012 (Krizhevsky et al., 2012)), communicating several times per layer (Exercise 3 in Section 13.7).
Three ways to split a model across two devices, with the cells of each device in its own color: replicate the model and split the batch (data parallel); split the layer stack (pipeline parallel); split every layer's width (tensor parallel).
13.5.2 Data Parallelism by Hand#
One data-parallel step on devices has four stages (Figure 13.5.2): split the minibatch into equal shards; compute each shard's gradient on its own device; sum the gradients via an allreduce so every device holds the sum; and apply the identical parameter update on every device. Because all replicas start from identical parameters and apply identical updates, they remain synchronized without ever re-copying weights.
One data-parallel step on two GPUs. Split the minibatch, run identical forward and backward passes on each replica, sum the gradients with an allreduce, then apply the identical update everywhere.
13.5.2.1 The Model and the Data#
We write LeNet (Section 6.6, with ReLU activations and He initialization) as a function of an explicit list of parameter tensors so every cross-device copy is visible. Its 61,706 fp32 parameters occupy 247 KB, and the 60,000 Fashion-MNIST training images occupy 188 MB—small enough to keep a copy of the dataset on each GPU so host data loading never enters our timings.
def new_params():
"""LeNet's parameters on the CPU: He-initialized weights, zero biases."""
params = []
for shape in [(6, 1, 5, 5), (16, 6, 5, 5), (120, 400), (84, 120),
(10, 84)]:
fan_in = math.prod(shape[1:])
params += [torch.randn(shape) * math.sqrt(2 / fan_in),
torch.zeros(shape[0])]
return params
def lenet(params, X):
W1, b1, W2, b2, W3, b3, W4, b4, W5, b5 = params
H = F.avg_pool2d(F.relu(F.conv2d(X, W1, b1, padding=2)), 2)
H = F.avg_pool2d(F.relu(F.conv2d(H, W2, b2)), 2).flatten(1)
H = F.relu(F.linear(H, W3, b3))
H = F.relu(F.linear(H, W4, b4))
return F.linear(H, W5, b5)
def to_device(split, device):
"""A whole Fashion-MNIST split on `device`: images in [0, 1], labels."""
return split.data.to(device).unsqueeze(1) / 255, split.targets.to(device)We verify that at least two GPUs are available, replicate the Fashion-MNIST
training split onto both devices (train_data), and draw a single shared
parameter initialization base for all experiments below:
assert d2l.num_gpus() >= 2, 'This section needs two GPUs'
data = d2l.FashionMNIST()
devices = [d2l.try_gpu(i) for i in range(2)]
train_data = [to_device(data.train, d) for d in devices] # A copy each
test_data = to_device(data.val, devices[0])
base = new_params() # One initialization for every run below
print(f'{sum(p.numel() for p in base)} parameters in {len(base)} tensors; '
f'images {tuple(train_data[0][0].shape)} on each of 2 devices')61706 parameters in 10 tensors; images (60000, 1, 28, 28) on each of 2 devices
13.5.2.2 Broadcast and Allreduce#
Broadcast copies initial parameters to every device once; allreduce sums one tensor per device and leaves the total on every device.
We write a simple star allreduce (device 0 gathers and sums all tensors, then copies the sum back).
def broadcast(params, device):
"""A copy of every tensor in `params` on `device`, ready for autograd."""
return [p.to(device, copy=True).requires_grad_() for p in params]
def allreduce(data):
"""Sum the tensors in `data`, one per device, onto every device."""
for i in range(1, len(data)): # Star: collect and add on device 0 ...
data[0] += data[i].to(data[0].device)
for i in range(1, len(data)): # ... then copy the sum back
data[i].copy_(data[0])We can test allreduce by placing [1.0, 1.0] on device 0 and [2.0, 2.0] on
device 1 and checking that both devices receive the elementwise sum
[3.0, 3.0]:
x = [torch.full((1, 2), i + 1.0, device=d) for i, d in enumerate(devices)]
print('before:', [x_j.tolist() for x_j in x])
allreduce(x)
print('after: ', [x_j.tolist() for x_j in x])before: [[[1.0, 1.0]], [[2.0, 2.0]]]
after: [[[3.0, 3.0]], [[3.0, 3.0]]]
13.5.2.3 The Data-Parallel Step#
With equal-sized shards, the average of the per-shard mean-loss
gradients equals the full-minibatch gradient (Exercise
2). Because every allreduce call incurs a fixed
latency regardless of message size, we concatenate LeNet's 10 gradient tensors
into a single flat vector and perform one allreduce per step. Passing
communicate=False skips the allreduce so we can time pure device computation.
def shard_grads(params, data, idx):
"""Gradient of the mean loss on each device's share of the minibatch
`idx` (example indices), as one flat vector per device."""
grads = []
for ps, (X, y), i in zip(params, data, idx.chunk(len(params))):
i = i.to(X.device, non_blocking=True) # Don't wait for the device
F.cross_entropy(lenet(ps, X[i]), y[i]).backward()
grads.append(torch.cat([p.grad.flatten() for p in ps]))
for p in ps:
p.grad = None # The next backward starts from zero
return grads
def train_step(params, data, idx, lr, communicate=True):
"""One data-parallel SGD step on the minibatch `idx`; without
communication, every device steps on its own shard's gradient."""
grads = shard_grads(params, data, idx)
if communicate:
allreduce(grads) # One message per device and step
with torch.no_grad():
for ps, g in zip(params, grads):
for p, g_p in zip(ps, g.split([p.numel() for p in ps])):
p -= lr / len(params) * g_p.view_as(p) # Mean of k grads13.5.2.4 A One-Step Check#
Before timing anything, we verify that one data-parallel step on two GPUs produces the same parameter update as one step on a single GPU over the same 256 examples (using strict fp32 arithmetic so convolution algorithm differences under tf32 do not mask bugs such as forgetting to divide by ).
idx = torch.randperm(len(data.train))[:256]
updates = []
torch.set_float32_matmul_precision('highest') # True fp32 in matmuls ...
with torch.backends.cudnn.flags(enabled=True, allow_tf32=False): # ... convs
for k in (1, 2):
params = [broadcast(base, d) for d in devices[:k]]
train_step(params, train_data[:k], idx, lr=0.2)
updates.append([p.detach().cpu() - b
for p, b in zip(params[0], base)])
torch.set_float32_matmul_precision('high')
largest = max(u.abs().max() for u in updates[0])
diff = max((u1 - u2).abs().max() for u1, u2 in zip(*updates))
print(f'largest update {largest:.1e}, largest difference {diff:.1e}')largest update 2.4e-02, largest difference 3.0e-08
The single-GPU and two-GPU updates agree to fp32 rounding error (~).
13.5.3 Ring Allreduce#
A star allreduce routes all traffic through device 0, forcing the hub to send and receive bytes for a gradient of size . The hub's load grows with every device we add, while each of the other devices handles only bytes in each direction (Figure 13.5.3, left).
Traffic of a star and of a ring allreduce for . The star's hub sends and receives bytes; in a ring every device sends and receives bytes, less than for any .
Ring allreduce (Patarasuk and Yuan, 2009; Sergeev and Del Balso, 2018) removes the hub. It arranges the devices in a logical ring and distributes the traffic evenly among them, splitting each device's -byte gradient into chunks of bytes and running two phases of steps each (Figure 13.5.4):
- Reduce-scatter: In each of steps, every device sends one chunk to its successor and adds the chunk received from its predecessor into its local copy. After steps, each device holds the complete sum for one distinct chunk.
- All-gather: Over another steps, the finished chunks circulate around the ring until every device holds all summed chunks.
Each device sends bytes per phase, or in total
Per-device traffic is at and stays strictly below no matter how many devices join the ring. Moreover, the two phases are useful independently: sharded training (Section 13.7) uses reduce-scatter to partition summed gradients and all-gather to assemble sharded weights.
Ring allreduce on four GPUs, computed step by step. Reduce-scatter accumulates one chunk per device around the ring; all-gather then distributes the finished chunks. Each cell counts how many of the four contributions a chunk holds, so a chunk holding 4 is complete. An outlined cell is the chunk that a GPU received in that step, and the ring in the last panel shows which GPU sends to which.
We implement the two-phase ring in NumPy, tracking both the accumulated chunks
on each device and the total bytes sent per device:
def ring_allreduce(xs):
"""Ring allreduce of the vectors xs, one per device; returns every
device's result and the bytes that each device sent."""
k = len(xs)
chunks = [np.array_split(x.copy(), k) for x in xs] # chunks[j][c]
sent = 0
for s in range(k - 1): # Reduce-scatter: add the received chunk
msgs = [chunks[j][(j - s) % k].copy() for j in range(k)]
for j, msg in enumerate(msgs):
chunks[(j + 1) % k][(j - s) % k] += msg
sent += msgs[0].nbytes
for s in range(k - 1): # All-gather: replace by the received chunk
msgs = [chunks[j][(j + 1 - s) % k].copy() for j in range(k)]
for j, msg in enumerate(msgs):
chunks[(j + 1) % k][(j + 1 - s) % k] = msg
sent += msgs[0].nbytes
return [np.concatenate(c) for c in chunks], sentTesting ring_allreduce on random 1,024-float vectors across
devices confirms that every device receives the exact
sum while sending bytes:
rng = np.random.default_rng()
for k in (2, 4, 8, 16):
xs = [rng.standard_normal(1024, dtype=np.float32) for _ in range(k)]
results, sent = ring_allreduce(xs)
correct = all(np.allclose(r, sum(xs), atol=1e-5) for r in results)
print(f'k = {k:2d}: every device holds the sum: {correct}; '
f'sent per device: {sent / xs[0].nbytes:.2f} S')k = 2: every device holds the sum: True; sent per device: 1.00 S
k = 4: every device holds the sum: True; sent per device: 1.50 S
k = 8: every device holds the sum: True; sent per device: 1.75 S
k = 16: every device holds the sum: True; sent per device: 1.88 S
While per-device bytes stay bounded by , a ring executes sequential hops, each paying per-hop start-up latency. For small messages on many GPUs, collective libraries switch to -depth tree algorithms (Exercise 5).
13.5.4 Communication Cost and Scaling#
13.5.4.1 A Cost Model for One Step#
Using the latency–bandwidth model (Hockney, 1994; Thakur et al., 2005), each allreduce call pays a fixed start-up latency plus a time per byte sent by each device (the inverse of the allreduce bus bandwidth). Without overlap, a step on devices with global batch and allreduce calls takes
where at . A second device shortens the step only if .
13.5.4.2 Latency and Bandwidth of the Allreduce#
We measure with a 1-float allreduce and with a -float (268 MB) allreduce on two GPUs:
def allreduce_time(n, devices, calls):
"""Seconds per allreduce of n floats per device."""
x = [torch.zeros(n, device=d) for d in devices]
return d2l.Benchmark(lambda: allreduce(x), warmup=10 * calls,
repeats=3 * calls, devices=devices).time
alpha = allreduce_time(1, devices, calls=100) # Our star: two copies in turn
n = 2**26 # 64M floats ...
S = 4 * n # ... 268 MB (256 MiB) per device
beta_link = (allreduce_time(n, devices, calls=3) - alpha) / S # s per byte
print(f'alpha = {1e6 * alpha:.0f} us, beta_link = {1e9 * beta_link:.2f} '
f'ns/byte (bus bandwidth {1e-9 / beta_link:.1f} GB/s)')alpha = 56 us, beta_link = 0.11 ns/byte (bus bandwidth 9.5 GB/s)
To test whether (13.5.2) predicts the benefit of gradient fusion, we allreduce LeNet's 10 gradient tensors ( KB total) separately () versus concatenated into a single flat vector (), which should differ by :
grads = [[torch.zeros_like(p, device=d) for p in base] for d in devices]
flat = [torch.cat([g.flatten() for g in G]) for G in grads]
def separately():
for g in zip(*grads): # One allreduce per tensor
allreduce(list(g))
n_bytes, c = flat[0].nbytes, len(base)
for name, f, calls in (('separately', separately, c),
('at once', lambda: allreduce(flat), 1)):
t = d2l.Benchmark(f, warmup=1000, repeats=300, devices=devices).time
print(f'{name:10s}: {1e6 * t:4.0f} us measured, '
f'{1e6 * (calls * alpha + n_bytes * beta_link):4.0f} us predicted')separately: 572 us measured, 587 us predicted
at once : 81 us measured, 82 us predicted
For a 247 KB gradient, nine extra message envelopes () cost more than all the bytes inside them—which is why production data-parallel libraries pack small gradients into large buckets before communicating (Section 13.6).
13.5.4.3 LeNet on One and Two GPUs#
Before running LeNet on two GPUs, let us profile its local work on one GPU for a minibatch of 256 examples:
params = [broadcast(base, devices[0])]
step = lambda: train_step(params, train_data[:1], idx, 0.2, communicate=False)
t = d2l.Benchmark(step, warmup=500, repeats=150, devices=devices[:1]).time
d2l.show_profile(d2l.kernel_times(step, steps=100), 1e3 * t, rows=4)wall clock 2.91 ms per step, device busy 0.30 ms (10%), matrix products 43%
0.05 ms 16% Kernel<cutlass_tensorop_s1688dgrad_optimized_tf32_12
0.04 ms 12% implicit_convolve_sgemm<float, float, 128, 5, 5, 3,
0.03 ms 10% wgrad_alg0_engine<float, 128, 5, 5, 3, 3, 3, false,
0.03 ms 9% avg_pool2d_backward_out_cuda_frame<float, float, int
The GPU is idle for most of the step: LeNet at batch size 256 is overhead-bound, so its step time equals the host dispatch time . Consequently, halving the batch from 256 to 128 on one GPU barely changes the step time, whereas driving two GPUs from one host thread takes roughly (Figure 13.5.5):
params, t_local = [broadcast(base, d) for d in devices], {}
for k, b in ((1, 256), (1, 128), (2, 128)):
t_local[k, b] = d2l.Benchmark(
lambda: train_step(params[:k], train_data[:k], idx[:k * b], 0.2,
communicate=False),
warmup=500, repeats=150, devices=devices[:k]).time
print(f'{k} GPU(s), {b} examples each: {1e3 * t_local[k, b]:.2f} ms')1 GPU(s), 256 examples each: 2.91 ms
1 GPU(s), 128 examples each: 2.80 ms
2 GPU(s), 128 examples each: 5.60 ms
Incorporating the single-host dispatch floor alongside the device compute time refines (13.5.2) to
A host-bound step on two GPUs, drawn as one host that issues the work of GPU 0 and then that of GPU 1. Each GPU idles while the host serves the other, so a step whose kernels are short takes about of host time plus the exchange.
To test both predictions end to end, we write a training loop train that runs
one epoch per pre-generated example permutation in orders and returns the
average step time (excluding the first epoch) and validation accuracy:
def train(params, train_data, test_data, orders, batch_size=256, lr=0.2):
"""Data-parallel SGD on the devices that hold `params` and `train_data`,
one epoch per example order; returns seconds per step, test accuracy."""
devices = [X.device for X, _ in train_data]
times = []
for order in orders:
t0 = time.perf_counter()
for idx in order.split(batch_size):
train_step(params, train_data, idx, lr)
for d in devices: # Wait until every device has finished
torch.cuda.synchronize(d)
times.append((time.perf_counter() - t0)
/ math.ceil(len(order) / batch_size))
X, y = test_data
with torch.no_grad():
acc = (lenet(params[0], X).argmax(1) == y).float().mean().item()
return sum(times[1:]) / (len(times) - 1), accWe now run train for five epochs at global batch size 256 on
GPUs and compare the measured two-GPU step time t_step[2] against both the
naive prediction (13.5.2) and the single-launcher model
(13.5.3):
orders, t_step = [torch.randperm(len(data.train)) for _ in range(5)], {}
for k in (1, 2):
params = [broadcast(base, d) for d in devices[:k]]
t_step[k], acc = train(params, train_data[:k], test_data, orders)
print(f'{k} GPU(s): {1e3 * t_step[k]:.2f} ms per step, '
f'test accuracy {acc:.2f}')
exchange = alpha + n_bytes * beta_link # One allreduce of the gradient
print(f'2 GPUs predicted: {1e3 * (t_local[1, 128] + exchange):.2f} ms per '
f'step by eq_dp_cost, {1e3 * (2 * t_step[1] + exchange):.2f} ms with '
f'one launcher')1 GPU(s): 2.88 ms per step, test accuracy 0.87
2 GPU(s): 5.69 ms per step, test accuracy 0.87
2 GPUs predicted: 2.88 ms per step by eq_dp_cost, 5.85 ms with one launcher
Both runs reach the same test accuracy, and (13.5.3) accurately predicts the two-GPU slowdown: at batch 256, LeNet's gradient exchange is tiny (~0.1 ms), and the bottleneck is feeding two GPUs from a single host launcher.
13.5.4.4 Strong and Weak Scaling, and Larger Minibatches#
Multi-GPU benchmarks follow one of two conventions: strong scaling holds the global batch fixed as grows (aiming to finish the same step faster), whereas weak scaling holds the per-GPU batch fixed so the global batch grows as (aiming for throughput in examples/s, though larger global batches alter optimization dynamics, Section 9.8). Strong scaling is the regime of Amdahl's law (Amdahl, 1967): the part of the step that does not parallelize, here the host launcher and the gradient exchange, caps the speedup however many GPUs we add. Weak scaling is the regime of Gustafson's law (Gustafson, 1988): when the work grows with the number of processors, the serial part shrinks relative to it, and throughput can keep growing.
By (13.5.3), a second GPU improves weak-scaling throughput () when
A second GPU never helps when ; once outgrows and the exchange time, the speedup approaches 2. We test this across examples per GPU:
for b in (256, 4096, 32768): # Examples per GPU
batch = torch.randint(len(data.train), (2 * b,)) # With replacement
steps = [lambda k=k: train_step(params[:k], train_data[:k],
batch[:k * b], 0.2) for k in (1, 2)]
times = [[], []] # Three timed windows per k,
for w in range(3): # taken in turn for k = 1 and 2
for k in (1, 2):
params = [broadcast(base, d) for d in devices] # Equal replicas
times[k - 1].append(d2l.Benchmark(
steps[k - 1], warmup=10 if w == 0 else 0,
repeats=max(20, 2**18 // b), devices=devices[:k]).time)
t = np.median(times, axis=1)
t_dev = sum(d2l.kernel_times(steps[0]).values()) / 1e3
if b == 256: # The host sets this step's time (profile above)
h_step = t[0]
predicted = 2 * t[0] / (max(2 * h_step, t_dev) + exchange)
speedups = 2 * np.array(times[0]) / np.array(times[1])
print(f'b = {b:5d}: 1 GPU {1e3 * t[0]:6.2f} ms (device busy '
f'{1e3 * t_dev:5.2f} ms), 2 GPUs {1e3 * t[1]:6.2f} ms\n'
f' speedup {predicted:.2f} predicted, '
f'{2 * t[0] / t[1]:.2f} measured '
f'(windows {speedups.min():.2f} to {speedups.max():.2f})')b = 256: 1 GPU 2.83 ms (device busy 0.30 ms), 2 GPUs 5.83 ms
speedup 0.99 predicted, 0.97 measured (windows 0.92 to 0.98)
b = 4096: 1 GPU 3.01 ms (device busy 3.00 ms), 2 GPUs 6.11 ms
speedup 1.05 predicted, 0.99 measured (windows 0.98 to 0.99)
b = 32768: 1 GPU 25.26 ms (device busy 25.35 ms), 2 GPUs 25.53 ms
speedup 1.99 predicted, 1.98 measured (windows 1.98 to 1.98)
At the second GPU gives no speedup; at device work far exceeds and the 247 KB gradient exchange, nearly doubling throughput as predicted.
13.5.5 Summary#
Data parallelism replicates the model on devices, computes gradients on of the minibatch per device, and sums gradients via an allreduce before updating. Ring allreduce decomposes the sum into a reduce-scatter followed by an all-gather, sending bytes per device across hops. Our step cost model (13.5.3) combines device compute time, single-host dispatch overhead , per-call latency , and bandwidth cost , explaining why concatenating small gradient tensors saves and why a second GPU only speeds up training once per-GPU device compute outlasts both host dispatch and communication.
13.5.6 Exercises#
-
Data versus pipeline parallelism. Consider a stack of bias-free linear layers of width in fp32 trained on two GPUs with batch size . Data parallelism allreduces all weight gradients; two-stage pipeline parallelism (Figure 13.5.1) places layers on each GPU and sends activations forward and gradients backward across the cut.
- Count the bytes transferred per step in each scheme, evaluate both for , and find the condition on for data parallelism to move fewer bytes.
- When the batch is split into pipeline micro-batches (Huang et al., 2019), derive the bubble (idle) fraction of each GPU in a two-stage pipeline and evaluate it for and .
-
Gradient normalization. Compare two data-parallel gradient recipes over shards of a batch of examples: Recipe A sums per-example losses on each device, sums gradients across devices, and divides by ; Recipe B averages per-example losses on each device and averages the device gradients.
- Show that both yield the exact full-batch mean gradient when all shards hold examples.
- For a language model averaging loss over tokens, suppose two shards hold 3,000 and 1,000 tokens. Find the relative weight Recipe B assigns to a token in each shard, and modify Recipe B so it is exact for unequal token counts.
-
Strong-scaling speedup. Model shard compute time as and neglect , so by (13.5.2) at fixed global batch :
- Show that the strong-scaling speedup holds for one if and only if it holds for all , and find .
- For M fp32 parameters, ms, ms/example, and , evaluate , , and at bus bandwidths of 20 GB/s and 5 GB/s, and find the minimum bus bandwidth for any speedup.
- Recompute and at 5 GB/s when gradients are communicated in bf16 ( halved).
- [code] Ring allreduce by hand. ●
- For devices holding bytes each, compare the total bytes moved and the bytes sent/received by the busiest device for star versus ring allreduce. Predict the ratio of their times when all bidirectional links operate concurrently versus when all transfers share one single bus sequentially.
- Implement
ring_allreduce(data)in PyTorch usingchunkand explicit.to()copies, verify it againstallreducefor , and benchmark both on 64M floats per device at and .
- Latency in the allreduce. ● If one hop of bytes takes , a -step ring allreduce takes
whereas a binary-tree allreduce (sum up, broadcast down in steps of bytes) takes
- Compare how the latency and bandwidth terms of each algorithm scale with . For , µs, and bus bandwidth 20 GB/s, find the crossover message size below which the tree is faster.
- At , express the half-performance message size (where fixed latency equals transfer time) in terms of and , evaluate it from your measurements in Section 13.5.4, and compare it with the gradient-bucket sizes of Section 13.6.