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 kk GPUs is data parallelism: give every GPU a full replica of the model and 1/k1/k 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 30×30\times 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 shape

13.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 16N16N 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).
Figure 13.5.1:

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 kk devices has four stages (Figure 13.5.2): split the minibatch into kk equal shards; compute each shard's gradient on its own device; sum the kk 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.

Figure 13.5.2:

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 kk equal-sized shards, the average of the kk 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 grads

13.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 kk).

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 (~10−710^{-7}).

13.5.3 Ring Allreduce#

A star allreduce routes all traffic through device 0, forcing the hub to send and receive (k−1)S(k-1)S bytes for a gradient of size SS. The hub's load grows with every device we add, while each of the other devices handles only SS bytes in each direction (Figure 13.5.3, left).

Figure 13.5.3:

Traffic of a star and of a ring allreduce for k=4k = 4. The star's hub sends and receives (k−1)S(k-1)S bytes; in a ring every device sends and receives 2(k−1)S/k2(k-1)S/k bytes, less than 2S2S for any kk.

Ring allreduce (Patarasuk and Yuan, 2009; Sergeev and Del Balso, 2018) removes the hub. It arranges the kk devices in a logical ring and distributes the traffic evenly among them, splitting each device's SS-byte gradient into kk chunks of S/kS/k bytes and running two phases of k−1k - 1 steps each (Figure 13.5.4):

  1. Reduce-scatter: In each of k−1k - 1 steps, every device sends one chunk to its successor and adds the chunk received from its predecessor into its local copy. After k−1k - 1 steps, each device holds the complete sum for one distinct chunk.
  2. All-gather: Over another k−1k - 1 steps, the finished chunks circulate around the ring until every device holds all kk summed chunks.

Each device sends (k−1)S/k(k-1)S/k bytes per phase, or in total

2(k−1)k Sbytes per device.(13.5.1)\frac{2(k-1)}{k}\, S \quad\textrm{bytes per device.} \tag{13.5.1}

Per-device traffic is SS at k=2k = 2 and stays strictly below 2S2S 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.

Figure 13.5.4:

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], sent

Testing ring_allreduce on random 1,024-float vectors across k∈{2,4,8,16}k \in \{2, 4, 8, 16\} devices confirms that every device receives the exact sum while sending 2(k−1)S/k2(k-1)S/k 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 2S2S, a ring executes 2(k−1)2(k-1) sequential hops, each paying per-hop start-up latency. For small messages on many GPUs, collective libraries switch to log⁡2k\log_2 k-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 α\alpha plus a time βlink\beta_{\textrm{link}} per byte sent by each device (the inverse of the allreduce bus bandwidth). Without overlap, a step on kk devices with global batch BB and cc allreduce calls takes

tstep(k)≈tcompute(B/k)+c α+2(k−1)k S βlink,(13.5.2)t_{\textrm{step}}(k) \approx t_{\textrm{compute}}(B/k) + c\,\alpha + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}, \tag{13.5.2}

where c=0c = 0 at k=1k = 1. A second device shortens the step only if tcompute(B)−tcompute(B/2)>cα+S βlinkt_{\textrm{compute}}(B) - t_{\textrm{compute}}(B/2) > c\alpha + S\,\beta_{\textrm{link}}.

13.5.4.2 Latency and Bandwidth of the Allreduce#

We measure α\alpha with a 1-float allreduce and βlink\beta_{\textrm{link}} with a 2262^{26}-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 (S=247S = 247 KB total) separately (c=10c = 10) versus concatenated into a single flat vector (c=1c = 1), which should differ by 9α9\alpha:

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 (9α9\alpha) 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 hsteph_{\textrm{step}}. 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 2hstep2 h_{\textrm{step}} (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 k hstepk\,h_{\textrm{step}} alongside the device compute time tdev(B/k)t_{\textrm{dev}}(B/k) refines (13.5.2) to

tstep(k)≈max⁡(k hstep,  tdev(B/k))+c α+2(k−1)k S βlink.(13.5.3)t_{\textrm{step}}(k) \approx \max\bigl(k\,h_{\textrm{step}},\; t_{\textrm{dev}}(B/k)\bigr) + c\,\alpha + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}. \tag{13.5.3}
Figure 13.5.5:

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 2hstep2h_{\textrm{step}} 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), acc

We now run train for five epochs at global batch size 256 on k∈{1,2}k \in \{1, 2\} 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 BB fixed as kk grows (aiming to finish the same step faster), whereas weak scaling holds the per-GPU batch bb fixed so the global batch grows as kbkb (aiming for k×k\times 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 (2 t(1)/t(2)>12\,t(1)/t(2) > 1) when

max⁡(2hstep,  tdev(b))+α+S βlink  <  2max⁡(hstep,  tdev(b)).\max\bigl(2h_{\textrm{step}},\; t_{\textrm{dev}}(b)\bigr) + \alpha + S\,\beta_{\textrm{link}} \;\lt \; 2\max\bigl(h_{\textrm{step}},\; t_{\textrm{dev}}(b)\bigr).

A second GPU never helps when tdev(b)≤hstept_{\textrm{dev}}(b) \le h_{\textrm{step}}; once tdev(b)t_{\textrm{dev}}(b) outgrows 2hstep2h_{\textrm{step}} and the exchange time, the speedup approaches 2. We test this across b∈{256,4096,32768}b \in \{256, 4096, 32768\} 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 b=256b = 256 the second GPU gives no speedup; at b=32,768b = 32{,}768 device work far exceeds 2hstep2h_{\textrm{step}} and the 247 KB gradient exchange, nearly doubling throughput as predicted.

13.5.5 Summary#

Data parallelism replicates the model on kk devices, computes gradients on 1/k1/k 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 2(k−1)S/k<2S2(k-1)S/k \lt 2S bytes per device across 2(k−1)2(k-1) hops. Our step cost model (13.5.3) combines device compute time, single-host dispatch overhead k hstepk\,h_{\textrm{step}}, per-call latency cαc\alpha, and bandwidth cost 2(k−1)Sβlink/k2(k-1)S\beta_{\textrm{link}}/k, explaining why concatenating small gradient tensors saves 9α9\alpha and why a second GPU only speeds up training once per-GPU device compute outlasts both host dispatch and communication.

13.5.6 Exercises#

  1. Data versus pipeline parallelism. Consider a stack of LL bias-free linear layers of width dd in fp32 trained on two GPUs with batch size BB. Data parallelism allreduces all weight gradients; two-stage pipeline parallelism (Figure 13.5.1) places L/2L/2 layers on each GPU and sends B×dB \times d activations forward and gradients backward across the cut.

    1. Count the bytes transferred per step in each scheme, evaluate both for L=32,d=4096,B=256L = 32, d = 4096, B = 256, and find the condition on (B,L,d)(B, L, d) for data parallelism to move fewer bytes.
    2. When the batch is split into mm pipeline micro-batches (Huang et al., 2019), derive the bubble (idle) fraction of each GPU in a two-stage pipeline and evaluate it for m=1m = 1 and m=8m = 8.
  2. Gradient normalization. Compare two data-parallel gradient recipes over kk shards of a batch of BB examples: Recipe A sums per-example losses on each device, sums gradients across devices, and divides by BB; Recipe B averages per-example losses on each device and averages the kk device gradients.

    1. Show that both yield the exact full-batch mean gradient when all shards hold B/kB/k examples.
    2. 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.
  3. Strong-scaling speedup. Model shard compute time as tcompute(s)=t0+s t1t_{\textrm{compute}}(s) = t_0 + s\,t_1 and neglect α\alpha, so by (13.5.2) at fixed global batch BB:

tstep(k)=t0+B t1k+2(k−1)k S βlink.(13.5.4)t_{\textrm{step}}(k) = t_0 + \frac{B\,t_1}{k} + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}. \tag{13.5.4}
  1. Show that the strong-scaling speedup R(k)=tstep(1)/tstep(k)>1R(k) = t_{\textrm{step}}(1) / t_{\textrm{step}}(k) > 1 holds for one k>1k > 1 if and only if it holds for all k>1k > 1, and find lim⁡k→∞R(k)\lim_{k \to \infty} R(k).
  2. For N=11.2N = 11.2M fp32 parameters, t0=2t_0 = 2 ms, t1=0.2t_1 = 0.2 ms/example, and B=256B = 256, evaluate R(2)R(2), R(4)R(4), and lim⁡k→∞R(k)\lim_{k \to \infty} R(k) at bus bandwidths of 20 GB/s and 5 GB/s, and find the minimum bus bandwidth for any speedup.
  3. Recompute R(4)R(4) and lim⁡k→∞R(k)\lim_{k \to \infty} R(k) at 5 GB/s when gradients are communicated in bf16 (SS halved).
  1. [code] Ring allreduce by hand. ●
    1. For kk devices holding SS 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 kk bidirectional links operate concurrently versus when all transfers share one single bus sequentially.
    2. Implement ring_allreduce(data) in PyTorch using chunk and explicit .to() copies, verify it against allreduce for k∈{2,3,4}k \in \{2, 3, 4\}, and benchmark both on 64M floats per device at k=2k = 2 and k=4k = 4.
  1. Latency in the allreduce. ● If one hop of nn bytes takes αhop+n βlink\alpha_{\textrm{hop}} + n\,\beta_{\textrm{link}}, a 2(k−1)2(k-1)-step ring allreduce takes
tring=2(k−1)(αhop+Sk βlink),(13.5.5)t_{\textrm{ring}} = 2(k-1)\left(\alpha_{\textrm{hop}} + \frac{S}{k}\,\beta_{\textrm{link}}\right), \tag{13.5.5}

whereas a binary-tree allreduce (sum up, broadcast down in 2log⁡2k2\log_2 k steps of SS bytes) takes

ttree=2log⁡2k(αhop+S βlink).(13.5.6)t_{\textrm{tree}} = 2\log_2 k \left(\alpha_{\textrm{hop}} + S\,\beta_{\textrm{link}}\right). \tag{13.5.6}
  1. Compare how the latency and bandwidth terms of each algorithm scale with kk. For k=8k = 8, αhop=10\alpha_{\textrm{hop}} = 10 µs, and bus bandwidth 20 GB/s, find the crossover message size SS below which the tree is faster.
  2. At k=2k = 2, express the half-performance message size S1/2S_{1/2} (where fixed latency equals transfer time) in terms of α\alpha and βlink\beta_{\textrm{link}}, evaluate it from your measurements in Section 13.5.4, and compare it with the gradient-bucket sizes of Section 13.6.

Discussions