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 \(k\) GPUs is data parallelism: give every GPU a full replica of the model and \(1/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\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'
import time
from functools import partial
from jax.flatten_util import ravel_pytree
from jax.sharding import NamedSharding, PartitionSpec as P

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 \(16N\) 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 \(k\) devices has four stages (Figure 13.5.2): split the minibatch into \(k\) equal shards; compute each shard’s gradient on its own device; sum the \(k\) 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)
def new_params(key):
    """LeNet's parameters: He-initialized weights, zero biases."""
    shapes = [(5, 5, 1, 6), (5, 5, 6, 16), (400, 120), (120, 84), (84, 10)]
    params = []
    for key, shape in zip(jax.random.split(key, len(shapes)), shapes):
        fan_in = math.prod(shape[:-1])
        params += [jax.random.normal(key, shape) * math.sqrt(2 / fan_in),
                   jnp.zeros(shape[-1])]
    return params

def lenet(params, X):
    W1, b1, W2, b2, W3, b3, W4, b4, W5, b5 = params
    conv = lambda X, W, padding: jax.lax.conv_general_dilated(
        X, W, (1, 1), padding, dimension_numbers=('NHWC', 'HWIO', 'NHWC'))
    pool = lambda X: nnx.avg_pool(X, (2, 2), strides=(2, 2))
    H = pool(jax.nn.relu(conv(X, W1, ((2, 2), (2, 2))) + b1))
    H = pool(jax.nn.relu(conv(H, W2, 'VALID') + b2)).reshape(X.shape[0], -1)
    H = jax.nn.relu(H @ W3 + b3)
    H = jax.nn.relu(H @ W4 + b4)
    return H @ W5 + b5

def to_device(split, sharding):
    """A whole Fashion-MNIST split placed by `sharding`: images in [0, 1],
    labels."""
    X, y = split
    return jax.device_put((X[..., None] / np.float32(255),
                           y.astype(np.int32)), sharding)

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
assert jax.device_count() >= 2, 'This section needs two GPUs'
data = d2l.FashionMNIST()
meshes = [jax.make_mesh((k,), ('data',), devices=jax.devices()[:k])
          for k in (1, 2)]
train_data = [to_device(data.train, NamedSharding(mesh, P()))
              for mesh in meshes]  # A copy on every device of each mesh
test_data = (data.val[0][..., None] / np.float32(255),
             data.val[1].astype(np.int32))
base = new_params(d2l.get_key())  # One initialization for every run
print(f'{sum(p.size for p in base)} parameters in {len(base)} tensors; '
      f'images {train_data[1][0].shape} on each of 2 devices')
61706 parameters in 10 tensors; images (60000, 28, 28, 1) on each of 2 devices

In JAX, multi-device arrays are placed on a named device mesh via NamedSharding and PartitionSpec (P('data') shards the leading axis across the 'data' mesh axis; P() replicates the full array on every device).

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

We use jax.shard_map with jax.lax.psum (which delegates to NCCL).

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])
def broadcast(params, mesh):
    """A copy of every array in `params` on every device of `mesh`."""
    return jax.device_put(params, NamedSharding(mesh, P()))

@partial(jax.jit, static_argnames='mesh')
def allreduce(x, mesh):
    """Sum the rows of `x` (row j on device j); every device gets the sum."""
    return jax.shard_map(lambda x_j: jax.lax.psum(x_j, 'data'), mesh=mesh,
                         in_specs=P('data'), out_specs=P('data'))(x)

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]]]
x = jax.device_put(jnp.array([[1.0, 1.0], [2.0, 2.0]]),
                   NamedSharding(meshes[1], P('data')))
print('before:', x.tolist())
print('after: ', allreduce(x, meshes[1]).tolist())
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 \(k\) equal-sized shards, the average of the \(k\) 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
def shard_grad(params, X, y, i):
    """Inside shard_map: the gradient of the mean loss on this device's
    share `i` of the minibatch, as one flat vector."""
    def loss(p):
        return optax.softmax_cross_entropy_with_integer_labels(
            lenet(p, X[i]), y[i]).mean()
    own = jax.lax.pcast(params, 'data', to='varying')  # This device's copy
    return ravel_pytree(jax.grad(loss)(own))[0]

@partial(jax.jit, static_argnames=('mesh', 'communicate'))
def train_step(params, data, idx, lr, mesh, communicate=True):
    """One data-parallel SGD step on the minibatch `idx`; without
    communication, every device steps on its own shard's gradient."""
    unravel = ravel_pytree(params)[1]
    def step(params, X, y, i):
        g = shard_grad(params, X, y, i)
        if communicate:
            g = jax.lax.psum(g, 'data')              # Allreduce
        k = jax.lax.axis_size('data')
        return jax.tree.map(lambda p, g_p: p - lr / k * g_p, params,
                            unravel(g))
    out = P() if communicate else P('data')  # Copies differ without the sum
    return jax.shard_map(step, mesh=mesh, in_specs=(P(), P(), P(), P('data')),
                         out_specs=out)(params, *data, idx)

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 \(k\)).

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
idx = np.random.default_rng().permutation(len(data.train[1]))[:256]
updates = []
with jax.default_matmul_precision('highest'):  # True fp32
    for mesh, data_k in zip(meshes, train_data):
        i = jax.device_put(idx, NamedSharding(mesh, P('data')))
        params = train_step(broadcast(base, mesh), data_k, i, 0.2, mesh)
        updates.append([np.asarray(p) - np.asarray(b)
                        for p, b in zip(params, base)])
largest = max(np.abs(u).max() for u in updates[0])
diff = max(np.abs(u1 - u2).max() for u1, u2 in zip(*updates))
print(f'largest update {largest:.1e}, largest difference {diff:.1e}')
largest update 1.9e-02, largest difference 3.0e-08

The single-GPU and two-GPU updates agree to fp32 rounding error (~\(10^{-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\) bytes for a gradient of size \(S\). The hub’s load grows with every device we add, while each of the other devices handles only \(S\) bytes in each direction (Figure 13.5.3, left).

Figure 13.5.3: Traffic of a star and of a ring allreduce for \(k = 4\). The star’s hub sends and receives \((k-1)S\) bytes; in a ring every device sends and receives \(2(k-1)S/k\) bytes, less than \(2S\) for any \(k\).

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

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

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

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

Per-device traffic is \(S\) at \(k = 2\) and stays strictly below \(2S\) 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
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 \in \{2, 4, 8, 16\}\) devices confirms that every device receives the exact sum while sending \(2(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
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 \(2S\), a ring executes \(2(k-1)\) sequential hops, each paying per-hop start-up latency. For small messages on many GPUs, collective libraries switch to \(\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 \(\beta_{\textrm{link}}\) per byte sent by each device (the inverse of the allreduce bus bandwidth). Without overlap, a step on \(k\) devices with global batch \(B\) and \(c\) allreduce calls takes

\[ 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 = 0\) at \(k = 1\). A second device shortens the step only if \(t_{\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 \(\beta_{\textrm{link}}\) with a \(2^{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)
def allreduce_time(n, mesh, calls):
    """Seconds per allreduce of n floats per device."""
    x = jnp.zeros((mesh.size, n), device=NamedSharding(mesh, P('data')))
    return d2l.Benchmark(lambda: allreduce(x, mesh), repeats=calls).time

def program_time(m, mesh, calls=300):
    """Seconds per call of one compiled program that makes m allreduces of
    one float, each on the result of the one before."""
    def chain(x):
        for _ in range(m):               # Each allreduce waits for the last
            x = jax.lax.pmean(x, 'data')
        return x
    f = jax.jit(jax.shard_map(chain, mesh=mesh, in_specs=P('data'),
                              out_specs=P('data')))
    x = jnp.zeros((mesh.size, 1), device=NamedSharding(mesh, P('data')))
    return d2l.Benchmark(lambda: f(x), warmup=10, repeats=calls).time

# The training step's psum runs inside a program that is dispatched anyway,
# so alpha is what each further allreduce adds to one program
alpha = (program_time(10, meshes[1]) - program_time(1, meshes[1])) / 9
n = 2**26                                # 64M floats ...
S = 4 * n                                # ... 268 MB (256 MiB) per device
# Both calls dispatch a program of their own; their difference is the bytes
beta_link = (allreduce_time(n, meshes[1], calls=3)
             - allreduce_time(1, meshes[1], calls=100)) / 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 = 25 us, beta_link = 0.41 ns/byte (bus bandwidth 2.4 GB/s)

To test whether Equation 13.5.2 predicts the benefit of gradient fusion, we allreduce LeNet’s 10 gradient tensors (\(S = 247\) KB total) separately (\(c = 10\)) versus concatenated into a single flat vector (\(c = 1\)), which should differ by \(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
mesh = meshes[1]
sizes = [p.size for p in base]
flat = jnp.zeros((mesh.size, sum(sizes)), device=NamedSharding(mesh, P('data')))
n_bytes, c = flat.nbytes // mesh.size, len(base)  # Bytes per device

def separately(g):
    """One psum per gradient tensor, each after the one before; without the
    barrier, XLA would merge the ten into one allreduce."""
    out = []
    for g_i in jnp.split(g, np.cumsum(sizes)[:-1], axis=1):
        if out:
            g_i, _ = jax.lax.optimization_barrier((g_i, out[-1]))
        out.append(jax.lax.psum(g_i, 'data'))
    return jnp.concatenate(out, axis=1)

t = {}
for name, f in (('separately', separately),
                ('at once', lambda g: jax.lax.psum(g, 'data'))):
    f = jax.jit(jax.shard_map(f, mesh=mesh, in_specs=P('data'),
                              out_specs=P('data')))
    t[name] = d2l.Benchmark(lambda: f(flat), warmup=10, repeats=300).time
    print(f'{name:10s}: {1e6 * t[name]:4.0f} us measured')
# Both programs are dispatched once and move the same bytes
print(f'difference: {1e6 * (t["separately"] - t["at once"]):4.0f} us '
      f'measured, {1e6 * (c - 1) * alpha:4.0f} us predicted by {c - 1} alpha')
separately:  524 us measured
at once   :  287 us measured
difference:  236 us measured,  221 us predicted by 9 alpha

For a 247 KB gradient, nine extra message envelopes (\(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
mesh, params = meshes[0], broadcast(base, meshes[0])
i = jax.device_put(idx, NamedSharding(mesh, P('data')))
step = lambda: train_step(params, train_data[0], i, 0.2, mesh,
                          communicate=False)
t = d2l.Benchmark(step, repeats=500).time
d2l.show_profile(d2l.kernel_times(step, steps=100), 1e3 * t, rows=4)
wall clock 0.40 ms per step, device busy 0.17 ms (42%), matrix products 30%
  0.02 ms  12%  _5x_cudnn_ampere_scudnn_128x32_relu_small_nn_v1
  0.02 ms  11%  dgrad2d_alg1_1<float, 0, 6, 7, 5, 4, 5, false, true>
  0.02 ms  10%  implicit_convolve_sgemm<float, float, 128, 5, 5, 3, 
  0.01 ms   8%  fft2d_r2c_32x32<float, false, 0u, false>

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 \(h_{\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 \(2 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
t_local = {}
for k, b in ((1, 256), (1, 128), (2, 128)):
    mesh, data_k = meshes[k - 1], train_data[k - 1]
    params = broadcast(base, mesh)
    i = jax.device_put(idx[:k * b], NamedSharding(mesh, P('data')))
    t_local[k, b] = d2l.Benchmark(lambda: train_step(
        params, data_k, i, 0.2, mesh, communicate=False), repeats=500).time
    print(f'{k} GPU(s), {b} examples each: {1e3 * t_local[k, b]:.2f} ms')
1 GPU(s), 256 examples each: 0.37 ms
1 GPU(s), 128 examples each: 0.40 ms
2 GPU(s), 128 examples each: 0.76 ms

Incorporating the single-host dispatch floor \(k\,h_{\textrm{step}}\) alongside the device compute time \(t_{\textrm{dev}}(B/k)\) refines Equation 13.5.2 to

\[ 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 \(2h_{\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
def train(params, train_data, test_data, mesh, orders, batch_size=256,
          lr=0.2):
    """Data-parallel SGD on the devices of `mesh`, one epoch per example
    order; returns seconds per step, test accuracy."""
    times = []
    for order in orders:
        starts = range(0, len(order), batch_size)
        batches = jax.device_put(  # The epoch's minibatches, in one call
            [order[s:s + batch_size] for s in starts],
            NamedSharding(mesh, P('data')))
        t0 = time.perf_counter()
        for idx in batches:
            params = train_step(params, train_data, idx, lr, mesh)
        jax.block_until_ready(params)
        times.append((time.perf_counter() - t0) / len(batches))
    X, y = test_data
    acc = float((jax.jit(lenet)(params, X).argmax(1) == y).mean())
    return sum(times[1:]) / (len(times) - 1), acc

We now run train for five epochs at global batch size 256 on \(k \in \{1, 2\}\) GPUs and compare the measured two-GPU step time t_step[2] against both the naive prediction Equation 13.5.2 and the single-launcher model Equation 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
rng = np.random.default_rng()
orders, t_step = [rng.permutation(len(data.train[1])) for _ in range(5)], {}
for k, mesh, data_k in zip((1, 2), meshes, train_data):
    t_step[k], acc = train(broadcast(base, mesh), data_k, test_data, mesh,
                           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): 0.37 ms per step, test accuracy 0.86
2 GPU(s): 0.89 ms per step, test accuracy 0.86
2 GPUs predicted: 0.52 ms per step by eq_dp_cost, 0.88 ms with one launcher

Both runs reach the same test accuracy, and Equation 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 \(B\) fixed as \(k\) grows (aiming to finish the same step faster), whereas weak scaling holds the per-GPU batch \(b\) fixed so the global batch grows as \(kb\) (aiming for \(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 Equation 13.5.3, a second GPU improves weak-scaling throughput (\(2\,t(1)/t(2) > 1\)) when

\[ \max\bigl(2h_{\textrm{step}},\; t_{\textrm{dev}}(b)\bigr) + \alpha + S\,\beta_{\textrm{link}} \;<\; 2\max\bigl(h_{\textrm{step}},\; t_{\textrm{dev}}(b)\bigr). \]

A second GPU never helps when \(t_{\textrm{dev}}(b) \le h_{\textrm{step}}\); once \(t_{\textrm{dev}}(b)\) outgrows \(2h_{\textrm{step}}\) and the exchange time, the speedup approaches 2. We test this across \(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)
rng = np.random.default_rng()
for b in (256, 4096, 32768):                # Examples per GPU
    batch = rng.integers(len(data.train[1]), size=2 * b)  # With replacement
    steps = []
    for k, mesh, data_k in zip((1, 2), meshes, train_data):
        params = broadcast(base, mesh)
        i = jax.device_put(batch[:k * b], NamedSharding(mesh, P('data')))
        steps.append(partial(train_step, params, data_k, i, 0.2, mesh))
    times = [[], []]                        # Three timed windows per k,
    for w in range(3):                      # taken in turn for k = 1 and 2
        for j, step in enumerate(steps):
            times[j].append(d2l.Benchmark(
                step, warmup=10 if w == 0 else 0,
                repeats=max(20, 2**18 // b)).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   0.41 ms (device busy  0.16 ms), 2 GPUs   0.97 ms
           speedup 0.87 predicted, 0.84 measured (windows 0.83 to 0.87)
b =  4096: 1 GPU   1.75 ms (device busy  1.74 ms), 2 GPUs   1.99 ms
           speedup 1.89 predicted, 1.76 measured (windows 1.72 to 1.80)
b = 32768: 1 GPU  14.29 ms (device busy 14.26 ms), 2 GPUs  14.50 ms
           speedup 1.99 predicted, 1.97 measured (windows 1.96 to 1.97)

At \(b = 256\) the second GPU gives no speedup; at \(b = 32{,}768\) device work far exceeds \(2h_{\textrm{step}}\) and the 247 KB gradient exchange, nearly doubling throughput as predicted.

13.5.5 Summary

Data parallelism replicates the model on \(k\) devices, computes gradients on \(1/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 < 2S\) bytes per device across \(2(k-1)\) hops. Our step cost model Equation 13.5.3 combines device compute time, single-host dispatch overhead \(k\,h_{\textrm{step}}\), per-call latency \(c\alpha\), and bandwidth cost \(2(k-1)S\beta_{\textrm{link}}/k\), explaining why concatenating small gradient tensors saves \(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 \(L\) bias-free linear layers of width \(d\) in fp32 trained on two GPUs with batch size \(B\). Data parallelism allreduces all weight gradients; two-stage pipeline parallelism (Figure 13.5.1) places \(L/2\) layers on each GPU and sends \(B \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 = 256\), and find the condition on \((B, L, d)\) for data parallelism to move fewer bytes.
    2. When the batch is split into \(m\) 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 = 1\) and \(m = 8\).
  2. Gradient normalization. Compare two data-parallel gradient recipes over \(k\) shards of a batch of \(B\) examples: Recipe A sums per-example losses on each device, sums gradients across devices, and divides by \(B\); Recipe B averages per-example losses on each device and averages the \(k\) device gradients.
    1. Show that both yield the exact full-batch mean gradient when all shards hold \(B/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 \(t_{\textrm{compute}}(s) = t_0 + s\,t_1\) and neglect \(\alpha\), so by Equation 13.5.2 at fixed global batch \(B\): \[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) = t_{\textrm{step}}(1) / t_{\textrm{step}}(k) > 1\) holds for one \(k > 1\) if and only if it holds for all \(k > 1\), and find \(\lim_{k \to \infty} R(k)\).
    2. For \(N = 11.2\)M fp32 parameters, \(t_0 = 2\) ms, \(t_1 = 0.2\) ms/example, and \(B = 256\), evaluate \(R(2)\), \(R(4)\), and \(\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)\) and \(\lim_{k \to \infty} R(k)\) at 5 GB/s when gradients are communicated in bf16 (\(S\) halved).
  4. [code] Ring allreduce by hand. ●
    1. For \(k\) devices holding \(S\) 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 \(k\) 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 \in \{2, 3, 4\}\), and benchmark both on 64M floats per device at \(k = 2\) and \(k = 4\).
  5. Latency in the allreduce. ● If one hop of \(n\) bytes takes \(\alpha_{\textrm{hop}} + n\,\beta_{\textrm{link}}\), a \(2(k-1)\)-step ring allreduce takes \[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 \(2\log_2 k\) steps of \(S\) bytes) takes \[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 \(k\). For \(k = 8\), \(\alpha_{\textrm{hop}} = 10\) µs, and bus bandwidth 20 GB/s, find the crossover message size \(S\) below which the tree is faster.
    2. At \(k = 2\), express the half-performance message size \(S_{1/2}\) (where fixed latency equals transfer time) in terms of \(\alpha\) and \(\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.
  1. Data versus pipeline parallelism. Consider a stack of \(L\) bias-free linear layers of width \(d\) in fp32 trained on two GPUs with batch size \(B\). Data parallelism allreduces all weight gradients; two-stage pipeline parallelism (Figure 13.5.1) places \(L/2\) layers on each GPU and sends \(B \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 = 256\), and find the condition on \((B, L, d)\) for data parallelism to move fewer bytes.
    2. When the batch is split into \(m\) 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 = 1\) and \(m = 8\).
  2. Gradient normalization. Compare two data-parallel gradient recipes over \(k\) shards of a batch of \(B\) examples: Recipe A sums per-example losses on each device, sums gradients across devices, and divides by \(B\); Recipe B averages per-example losses on each device and averages the \(k\) device gradients.
    1. Show that both yield the exact full-batch mean gradient when all shards hold \(B/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 \(t_{\textrm{compute}}(s) = t_0 + s\,t_1\) and neglect \(\alpha\), so by Equation 13.5.2 at fixed global batch \(B\): \[t_{\textrm{step}}(k) = t_0 + \frac{B\,t_1}{k} + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}.\]
    1. Show that the strong-scaling speedup \(R(k) = t_{\textrm{step}}(1) / t_{\textrm{step}}(k) > 1\) holds for one \(k > 1\) if and only if it holds for all \(k > 1\), and find \(\lim_{k \to \infty} R(k)\).
    2. For \(N = 11.2\)M fp32 parameters, \(t_0 = 2\) ms, \(t_1 = 0.2\) ms/example, and \(B = 256\), evaluate \(R(2)\), \(R(4)\), and \(\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)\) and \(\lim_{k \to \infty} R(k)\) at 5 GB/s when gradients are communicated in bf16 (\(S\) halved).
  4. [code] Ring allreduce by hand. ●
    1. For \(k\) devices holding \(S\) 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 \(k\) bidirectional links operate concurrently versus when all transfers share one single bus sequentially.
    2. Implement ring_allreduce inside jax.shard_map using jax.lax.ppermute and jax.lax.axis_index, verify it against jax.lax.psum for \(k \in \{2, 4\}\), and benchmark it on 64M floats per device.
  5. Latency in the allreduce. ● If one hop of \(n\) bytes takes \(\alpha_{\textrm{hop}} + n\,\beta_{\textrm{link}}\), a \(2(k-1)\)-step ring allreduce takes \[t_{\textrm{ring}} = 2(k-1)\left(\alpha_{\textrm{hop}} + \frac{S}{k}\,\beta_{\textrm{link}}\right),\] whereas a binary-tree allreduce (sum up, broadcast down in \(2\log_2 k\) steps of \(S\) bytes) takes \[t_{\textrm{tree}} = 2\log_2 k \left(\alpha_{\textrm{hop}} + S\,\beta_{\textrm{link}}\right).\]
    1. Compare how the latency and bandwidth terms of each algorithm scale with \(k\). For \(k = 8\), \(\alpha_{\textrm{hop}} = 10\) µs, and bus bandwidth 20 GB/s, find the crossover message size \(S\) below which the tree is faster.
    2. At \(k = 2\), express the half-performance message size \(S_{1/2}\) (where fixed latency equals transfer time) in terms of \(\alpha\) and \(\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