13.8 Case Study: Optimizing a Transformer

Each section of this chapter has isolated one cause of a slow training step and the change that removes it: host dispatch overhead, memory traffic from small kernels, wide number formats, and single-GPU boundaries. A real training step suffers from several at once, and removing one shifts the bottleneck to the others. Here we take a single model, as a practitioner would, and ask how much faster its training step can become—and in what order the changes should be applied.

The model is the GPT of Section 11.2 with its width doubled to 512 (19 million parameters). One training step on 64 windows of 128 bytes (8,1928{,}192 tokens) performs about 6×1.9×107×8,192≈9×10116 \times 1.9 \times 10^{7} \times 8{,}192 \approx 9 \times 10^{11} FLOPs: two per parameter and token in the forward pass and four in the backward pass. On an RTX 4090 (165 TFLOP/s165\text{ TFLOP/s} in bf16), the arithmetic needs less than 6 ms6\text{ ms}. A plain fp32 step with AdamW takes about 25 ms25\text{ ms}. The number format alone accounts for about 6 ms6\text{ ms} of that 19 ms19\text{ ms} gap (tf32 tensor cores run at half the bf16 rate, requiring 11 ms11\text{ ms}); the remaining 13 ms13\text{ ms} or so is time in which the tensor cores run below peak or sit idle.

We follow the method of Section 13.1: count, predict, measure, and explain the difference. Before each change, the profile of the previous step bounds what the change can gain; after it, we compare. Each change is measured cumulatively on top of the previous ones. The section concludes by checking that the fastest step still trains the model and accounting for where its remaining time goes.

import os
import re
from torch.utils.checkpoint import checkpoint
torch.set_float32_matmul_precision('high')  # fp32 products on tf32 cores
# 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'

13.8.1 Experimental Setup#

Every change in this section is judged by the same measurement, so the model, data, and throughput benchmark stay fixed throughout.

13.8.1.1 Model and Data#

We train d2l.GPT (Section 11.2): six pre-norm blocks with eight attention heads each, rotary position embeddings, RMSNorm, SwiGLU, and an input embedding tied to the output layer. The data are 128-byte windows of WikiText-103 drawn at random offsets over the 256-byte vocabulary (d2l.WikiText103, Section 9.3).

We double the width from 256 to 512 so the matrix products sit comfortably in the compute-bound regime (Section 13.1). Multiplying an n×dn \times d activation matrix by a d×d′d \times d' weight matrix performs 2ndd′2ndd' FLOPs and moves b(nd+dd′+nd′)b(nd + dd' + nd') bytes (bb bytes per element). For n=8,192n = 8{,}192 tokens at width d=512d = 512, the block projections reach 125–185 FLOP/byte125\text{--}185\text{ FLOP/byte} in tf32 (b=4b = 4) and 250–370 FLOP/byte250\text{--}370\text{ FLOP/byte} in bf16 (b=2b = 2), well above the RTX 4090 ridge points (82 FLOP/byte82\text{ FLOP/byte} for tf32 and 164 FLOP/byte164\text{ FLOP/byte} for bf16). A faster number format therefore shortens these products directly. At width 256 they straddle the ridge point (Exercise 6).

The 270 MB training corpus fits in GPU memory as a flat byte array. The next cell places it on the GPU, defines windows to sample minibatches directly on the device without host transfers, and builds the model.

device = d2l.try_gpu()
data = d2l.WikiText103(batch_size=64, num_steps=128)
corpus = torch.tensor(data.train, device=device)  # One byte per token

def windows(corpus, batch_size, num_steps=128):
    """Endless minibatches of windows at random offsets, each position with
    the next byte as its target."""
    offsets = torch.arange(num_steps + 1, device=corpus.device)
    while True:
        starts = torch.randint(len(corpus) - num_steps, (batch_size, 1),
                               device=corpus.device)
        W = corpus[starts + offsets].long()
        yield W[:, :-1], W[:, 1:]

model = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
num_params = d2l.num_params(model)
print(f'{num_params / 1e6:.1f}M parameters, '
      f'{len(corpus) / 1e6:.0f}M training bytes on the GPU')
19.0M parameters, 270M training bytes on the GPU

At 16 bytes per parameter (weight, gradient, and two Adam moments), the 19M-parameter training state occupies only 0.3 GiB0.3\text{ GiB}, requiring neither gradient accumulation nor sharding (Section 13.4, Section 13.7). Keeping the corpus on the GPU also isolates the training step from the input pipeline (Section 13.2).

13.8.1.2 Throughput Measurement#

We measure end-to-end training throughput in tokens per second, including minibatch sampling, forward and backward passes, and the optimizer update:

settingvalue
hardware1 of 4 RTX 4090 GPUs (2 and 4 for data parallelism)
modeld2l.GPT: 6 blocks, width 512, 8 heads, byte vocabulary, context 128
datarandom 128-byte windows of WikiText-103 drawn on the GPU every step
optimizerAdamW (lr=10−3\text{lr} = 10^{-3}, weight decay 0.010.01)
precisionfp32 with tf32 matrix products until bf16 is introduced
timingd2l.Benchmark: 20 warm-up steps, then 3 windows of 50 steps between device syncs
resultmedian tokens/s across the 3 windows, ratio to previous kept config, and relative window spread

tokens_per_second applies these rules via d2l.Benchmark (Section 13.1). record stores each result and prints its speedup over the previous kept configuration along with the relative spread across the three measurement windows (range/median\text{range} / \text{median}). Configurations passed with kept=False are stored as branches that subsequent configurations do not build upon.

def tokens_per_second(step, batches, warmup=20, repeats=50, num_windows=3):
    """Median training throughput of `step` on minibatches drawn from
    `batches`, over `num_windows` timed windows of `repeats` steps each, and
    the spread of the windows (largest minus smallest) relative to it."""
    X, _ = next(batches)
    speeds = [math.prod(X.shape) / d2l.Benchmark(
                  lambda: step(*next(batches)), warmup if i == 0 else 0,
                  repeats).time for i in range(num_windows)]
    return np.median(speeds), np.ptp(speeds) / np.median(speeds)

results, branches = {}, {}
def record(name, measured, kept=True):
    """Store a measured throughput and print it with its ratio to the last
    kept configuration and the spread of its windows; a configuration that
    is not kept is stored in `branches`."""
    speed, spread = measured
    previous = list(results.values())[-1] if results else speed
    (results if kept else branches)[name] = speed
    print(f'{name}: {speed:,.0f} tokens/s ({speed / previous:.2f}x), '
          f'windows within {spread:.1%}')

Steps that perform substantial host work are sensitive to background host activity and show a wider window spread than compiled or graph-captured steps. Because day-to-day host load varies more than consecutive windows in a single run, we read speedup ratios to one decimal place and trust small gains of a few percent only when the profile predicts them.

13.8.2 A Single GPU#

We first optimize the training step on a single GPU, one change at a time, starting from the baseline implementation of Section 11.2.

13.8.2.1 Baseline#

The baseline is the standard training step of Section 11.2 with AdamW: forward pass, cross-entropy loss, backward pass, and parameter update.

The step runs eagerly: Python and autograd dispatch each forward and backward operation as individual kernel launches, while AdamW (fused=True) updates all parameters and moments in a few fused kernels. make_step packages the training step; its forward and bf16 arguments support the modifications in the subsections ahead.

def make_step(model, forward=None, bf16=False, warmup=0):
    """An AdamW training step of `model` on a minibatch (X, Y); `forward`
    replaces the model's forward pass, `bf16` turns on autocast, and a
    `warmup` > 0 raises the learning rate linearly to 1e-3 over as many
    steps."""
    forward = model if forward is None else forward
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3,
                                  weight_decay=0.01, fused=True)
    if warmup:
        schedule = torch.optim.lr_scheduler.LambdaLR(
            optimizer, lambda i: min(1, (i + 1) / warmup))
    def step(X, Y):
        with torch.autocast('cuda', torch.bfloat16, enabled=bf16):
            loss = F.cross_entropy(forward(X).flatten(0, 1), Y.flatten())
        optimizer.zero_grad(set_to_none=True)
        loss.backward()
        optimizer.step()
        if warmup:
            schedule.step()
        return loss
    return step

step = make_step(model)
record('baseline', tokens_per_second(step, windows(corpus, 64)))
baseline: 317,736 tokens/s (1.00x), windows within 1.9%

As expected, the baseline windows spread roughly ten times more widely than later configurations because of per-step host work. To see where the step spends its time, profile records five steps with d2l.kernel_times, displays the breakdown with d2l.show_profile (Section 13.1.4) (total device kernel time versus wall-clock step time, the share taken by matrix products including fused attention kernels, and the top kernels), and saves the profile for our final accounting.

profiles = {}
def profile(step, batches):
    """Kernel profile of `step`, the configuration recorded last, on
    minibatches drawn from `batches`: printed against the throughput that
    `record` measured, and stored in `profiles` under the same name."""
    name, speed = list(results.items())[-1]
    X, _ = next(batches)
    kernels = d2l.kernel_times(lambda: step(*next(batches)), steps=5)
    d2l.show_profile(kernels, 1e3 * math.prod(X.shape) / speed, rows=4)
    profiles[name] = kernels

profile(step, windows(corpus, 64))
wall clock 25.78 ms per step, device busy 24.44 ms (95%), matrix products 64%
  3.28 ms  13%  Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
  3.08 ms  13%  Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
  2.84 ms  12%  Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
  2.41 ms  10%  vectorized_elementwise_kernel<4, BinaryFunctor<float

The device runs kernels for nearly the entire step, with matrix products taking about two-thirds of the time. Because the host mostly keeps up, the step is bottlenecked by device work.

The remaining third outside the matrix products is fragmented across many short kernels (SwiGLU, rotary embeddings, residual additions, and RMSNorm), each reading and writing device memory and thus limited by memory bandwidth (Section 13.3.2).

13.8.2.2 Host Overhead and Small Kernels#

Two remedies target the time spent outside matrix products, and the profile bounds what each can gain. The bound is Amdahl's law (Amdahl, 1967): if a change speeds up a fraction ff of the step by a factor ss, the step as a whole speeds up by 1/(1−f+f/s)1/(1 - f + f/s), which stays below 1/(1−f)1/(1 - f) however large ss becomes. Applied to the two remedies:

  1. Reducing host overhead targets idle gaps where the device waits for the host (Section 13.1); its speedup is bounded by the idle fraction of the step.
  2. Kernel fusion merges chains of bandwidth-bound elementwise kernels so intermediate arrays stay on chip; its speedup is bounded by the non-matmul device time.

Our baseline is in the second regime: the GPU is idle for only a few percent of the step, while non-matmul kernels consume 8.8 ms8.8\text{ ms} out of 24.5 ms24.5\text{ ms} of device time. Even if compilation eliminated all non-matmul kernels and idle gaps, the step would shrink to the 15.6 ms15.6\text{ ms} of matrix products—at most a 1.6×1.6\times speedup. torch.compile (Section 13.3) fuses elementwise operations across the forward and backward passes while leaving matrix products and the fused optimizer update intact. Passing mode='reduce-overhead' and dynamic=False also captures static-shape CUDA graphs (Section 13.3.4), eliminating the few percent of host idle time now and preventing host dispatch from becoming a bottleneck as device execution shrinks later. First, we verify that the compiled model matches the eager logits.

compiled = torch.compile(model, dynamic=False, mode='reduce-overhead')
X, _ = next(windows(corpus, 64))
high = model(X)
error = ((compiled(X) - high).norm() / high.norm()).item()
print(f'relative difference of the compiled logits: {error:.1e}')
assert error < 1e-4
step = make_step(model, compiled)
record('+ compile', tokens_per_second(step, windows(corpus, 64)))
relative difference of the compiled logits: 1.5e-05
+ compile: 368,688 tokens/s (1.16x), windows within 0.0%

The compiled logits match to four significant digits (minor differences arise from reordered fp32 rounding inside fused kernels amplified by tf32 matrix products). Throughput rises by over 10%, well within the 1.6×1.6\times upper bound.

A second profile shows how the step changed:

profile(step, windows(corpus, 64))
wall clock 22.22 ms per step, device busy 22.27 ms (100%), matrix products 71%
  4.01 ms  18%  Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
  3.05 ms  14%  Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
  2.83 ms  13%  Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
  1.44 ms   6%  fmha_cutlassB_f32_aligned_64x64_k64_sm80

The device remains busy for nearly the entire step, and matrix products now account for roughly two-thirds or more of device time.

Device time per step dropped from 24.5 ms24.5\text{ ms} to 22.3 ms22.3\text{ ms} and inter-kernel gaps vanished: Inductor fusion shaved 2.2 ms2.2\text{ ms} (a quarter of non-matmul time), while CUDA graph replay closed about 1 ms1\text{ ms} of host launch gaps.

13.8.2.3 Reduced Precision#

With the GPU busy and matrix products dominating device time, the next step is to speed up the matrix products. Switching from tf32 to bf16 doubles RTX 4090 tensor-core peak throughput to 165 TFLOP/s165\text{ TFLOP/s} and halves the memory footprint of bf16 activations (Section 13.4). If matrix products take a fraction f∈[2/3,0.7]f \in [2/3, 0.7] of the step and only they double in speed, the step shrinks to 1−f/21 - f/2 of its time—a speedup of about 1.5×1.5\times (rising toward 2×2\times if non-matmul kernels also move half as many bytes).

We apply the mixed-precision recipe of Section 13.4.2: matrix products (including attention) and intermediate elementwise operations run in bf16, while master weights, gradients, Adam moments, normalizations, the loss, and the residual stream remain in fp32 (keeping the residual stream in fp32 prevents small block updates from rounding away in bf16's 8-bit significand). Because bf16 matches fp32's exponent range, no loss scaling is needed. Before timing, we verify that the bf16 forward pass matches fp32 logits to within bf16 precision (~1%).

torch.autocast applies mixed precision per operation (Section 5.5), casting matrix products and attention inputs to bf16 while keeping embeddings, normalizations, the residual stream, and the loss softmax in fp32.

X, _ = next(windows(corpus, 64))
with torch.autocast('cuda', torch.bfloat16):
    low = compiled(X).float()
high = compiled(X)
error = ((low - high).norm() / high.norm()).item()
print(f'relative difference of the bf16 logits: {error:.1e}')
assert error < 0.01
step = make_step(model, compiled, bf16=True)
record('+ bf16', tokens_per_second(step, windows(corpus, 64)))
relative difference of the bf16 logits: 2.0e-03
+ bf16: 643,350 tokens/s (1.74x), windows within 0.1%

The bf16 logits agree with fp32 to within 1%.

Throughput rises by about 1.75×1.75\times—exceeding the 1.55×1.55\times predicted from halving the 71% matrix-product share alone because bf16 GEMMs run at higher utilization than tf32 and intermediate fused kernels move 2-byte bf16 activations instead of 4-byte floats. Note that F.scaled_dot_product_attention has already been using a fused FlashAttention kernel since the baseline.

13.8.2.4 Larger Minibatches#

Increasing the minibatch size amortizes fixed per-step costs over more tokens. Because the device is already busy throughout the step, only device work that scales with parameter count rather than token count can be amortized:

  • AdamW reads weights, gradients, and two moments, and writes weights and two moments (28 bytes/param28\text{ bytes/param} in fp32).
  • Mixed precision casts fp32 master weights to bf16 in the forward pass and bf16 weight gradients back to fp32 in the backward pass (12 bytes/param12\text{ bytes/param}).

Together, these move 40 bytes/param40\text{ bytes/param}, or 0.76 GB/step0.76\text{ GB/step}. At 1.0 TB/s1.0\text{ TB/s} of memory bandwidth, this fixed work takes about 0.75 ms0.75\text{ ms}—roughly 1/161/16 of a 12–13 ms12\text{--}13\text{ ms} bf16 step at batch size 64. Growing the minibatch 8×8\times from 64 to 512 windows (65,53665{,}536 tokens) amortizes 7/87/8 of this fixed cost, predicting around a 5% throughput gain.

Even a modest single-GPU gain is worthwhile because data parallelism scales well only when the per-GPU step time is much longer than the gradient allreduce (Section 13.8.3). Keep in mind, however, that larger batches reduce sample efficiency once the batch size exceeds the critical batch size (Section 9.8, Exercise 5). Because activation memory grows linearly with batch size, we also record peak memory beyond weights and optimizer state (Section 13.4.1.4).

torch.cuda.reset_peak_memory_stats()
start = torch.cuda.memory_allocated()
record('+ batch 512', tokens_per_second(step, windows(corpus, 512)))
memory = (torch.cuda.max_memory_allocated() - start) / 2**30
print(f'memory beyond weights and optimizer state: {memory:.1f} GiB')
+ batch 512: 653,141 tokens/s (1.02x), windows within 0.0%
memory beyond weights and optimizer state: 8.6 GiB

At batch size 512, activation memory uses about a third of the GPU's 24 GiB24\text{ GiB}, and throughput increases by a few percent (Exercise 2 separates the fixed per-step cost from the per-token cost across batch sizes). A third profile shows the breakdown at batch size 512:

profile(step, windows(corpus, 512))
wall clock 100.34 ms per step, device busy 100.33 ms (100%), matrix products 57%
 11.62 ms  12%  ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_stages_3
 10.78 ms  11%  ampere_bf16_s16816gemm_bf16_128x64_ldg8_f2f_tn
  7.45 ms   7%  Kernel2<cutlass_80_tensorop_bf16_s16816gemm_relu_bf1
  5.62 ms   6%  triton_poi_fused__unsafe_view_mm_mul_silu_silu_backw

The device is busy for the entire step: matrix products (including fused attention) take just under 60% of the time, while fused bandwidth-bound kernels for RMSNorm, SwiGLU, rotary embeddings, and fp32/bf16 casts take the rest.

13.8.2.5 Activation Checkpointing#

Activation checkpointing (Section 13.4.3) saves memory by storing only each block's input during the forward pass and recomputing its internal activations during the backward pass. Because batch size 512 uses only a third of GPU memory, checkpointing is unnecessary here and can only slow the step down. We can predict the slowdown in two ways:

  1. By FLOP count: recomputing the forward pass raises per-token block arithmetic from 66 to 8 FLOPs/param8\text{ FLOPs/param}, predicting 6/8=0.756/8 = 0.75 of the uncheckpointed throughput.
  2. By timing the forward pass: below, we time a standalone forward pass tfwdt_{\text{fwd}} at batch size 512 and compute 1/(1+tfwd/tstep)1 / (1 + t_{\text{fwd}} / t_{\text{step}}).
X512, _ = next(windows(corpus, 512))  # One minibatch of the last step
with torch.no_grad(), torch.autocast('cuda', torch.bfloat16):
    t_forward = d2l.Benchmark(lambda: compiled(X512)).time

Comparing t_forward against the full step duration t_step at batch size 512 predicts the fraction of throughput 1 / (1 + t_forward / t_step) retained when every block's forward pass is repeated:

t_step = 512 * 128 / results['+ batch 512']  # Seconds per step
print(f'forward pass {1e3 * t_forward:.1f} ms of a {1e3 * t_step:.1f} ms '
      f'step: repeating it keeps at least {1 / (1 + t_forward / t_step):.2f} '
      f'of the throughput')
forward pass 30.8 ms of a 100.3 ms step: repeating it keeps at least 0.77 of the throughput

Both estimates agree: the forward pass takes about a third of the step, so repeating it should retain at least three-quarters of the throughput (slightly more because embeddings and the output projection are not checkpointed). We now wrap each block in Checkpointed, verify logit equality, and measure both throughput (kept=False) and activation memory.

Checkpointed calls torch.utils.checkpoint.checkpoint.

class Checkpointed(nn.Module):
    """A module that keeps only its input for the backward pass."""
    def __init__(self, module):
        super().__init__()
        self.module = module

    def forward(self, X, **kwargs):
        return checkpoint(self.module, X, use_reentrant=False, **kwargs)

remat = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
remat.load_state_dict(model.state_dict())
remat.blks = nn.ModuleList(Checkpointed(blk) for blk in remat.blks)
assert torch.allclose(remat(X), model(X), atol=1e-6)
step = make_step(remat, torch.compile(remat, dynamic=False,
                                      mode='reduce-overhead'), bf16=True)
with torch.no_grad(), torch.autocast('cuda', torch.bfloat16):
    forward = d2l.kernel_times(lambda: compiled(X512), steps=5)  # Alone
torch.cuda.reset_peak_memory_stats()
start = torch.cuda.memory_allocated()
batches = windows(corpus, 512)
record('+ checkpointing', tokens_per_second(step, batches), kept=False)
memory = (torch.cuda.max_memory_allocated() - start) / 2**30
print(f'memory beyond weights and optimizer state: {memory:.1f} GiB')

def split(kernels):
    """Device ms per step of the matrix products and of all other kernels."""
    products = sum(ms for name, ms in kernels.items()
                   if re.search(d2l.PRODUCT_KERNELS, name, re.I))
    return np.array([products, sum(kernels.values()) - products])

alone = split(forward)
added = (split(d2l.kernel_times(lambda: step(*next(batches)), steps=5))
         - split(profiles['+ batch 512']))
print(f'forward pass alone:  products {alone[0]:4.1f} ms, other kernels '
      f'{alone[1]:4.1f} ms\nadded to the step:   products {added[0]:4.1f} ms, '
      f'other kernels {added[1]:4.1f} ms')
+ checkpointing: 556,390 tokens/s (0.85x), windows within 0.0%
memory beyond weights and optimizer state: 3.2 GiB
forward pass alone:  products 17.4 ms, other kernels 13.4 ms
added to the step:   products 14.5 ms, other kernels  3.1 ms

Checkpointing cuts activation memory by roughly two-thirds while retaining more throughput than the standalone forward-pass time predicted.

Throughput drops to 0.85×0.85\times (above the 0.77×0.77\times bound). As the kernel split reveals, recomputing the block matrix products adds 14 ms14\text{ ms} (close to the 17 ms17\text{ ms} of all forward products including the output projection), whereas recomputing the non-matmul kernels adds only 3 ms3\text{ ms} instead of 13 ms13\text{ ms}: Inductor fuses the recomputed elementwise operations directly into the backward kernels that consume them, making their recomputation nearly free in memory traffic.

Checkpointing is essential when a model or batch size would otherwise exceed device memory, but here memory is plentiful, so we leave it out of the configurations that follow.

13.8.3 Data Parallelism#

Our fastest single-GPU step leaves three of the machine's four RTX 4090s idle. Before running on multiple GPUs, we use the cost model of Section 13.5.4 to predict the data-parallel speedup.

13.8.3.1 Predicted Speedup#

In data parallelism (Section 13.5), each of kk GPUs holds a replica of the model, computes gradients on its own minibatch, and sums gradients via an allreduce of size SS bytes in cc buckets:

tcompute(B/k)+c α+2(k−1)k S βlink.t_{\textrm{compute}}(B/k) + c\,\alpha + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}.

On our PCIe machine without peer-to-peer access, GPU transfers stage through host memory at a bus bandwidth of roughly 2.4 GB/s2.4\text{ GB/s} (Section 13.6), or βlink≈0.42 ns/byte\beta_{\textrm{link}} \approx 0.42\text{ ns/byte}. Under weak scaling (fixed per-GPU batch size), per-bucket latency c αc\,\alpha is under a millisecond and negligible next to tens of milliseconds of step time, simplifying the step time without overlap to:

tstep(k)≈tstep(1)+tallreduce(k),(13.8.1)t_{\textrm{step}}(k) \approx t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k), \tag{13.8.1}

for a throughput multiplier of k tstep(1)/(tstep(1)+tallreduce(k))k\, t_{\textrm{step}}(1) / (t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k)). Adding a second GPU increases throughput only if tallreduce(2)<tstep(1)t_{\textrm{allreduce}}(2) \lt t_{\textrm{step}}(1).

For our 19M-parameter GPT, fp32 gradients occupy S=76 MBS = 76\text{ MB}, giving tallreduce(2)≈Sβlink≈31 mst_{\textrm{allreduce}}(2) \approx S\beta_{\textrm{link}} \approx 31\text{ ms} on two GPUs and tallreduce(4)≈1.5 Sβlink≈47 mst_{\textrm{allreduce}}(4) \approx 1.5\,S\beta_{\textrm{link}} \approx 47\text{ ms} on four:

  • Compiled fp32 at batch 64 per GPU (tstep(1)≈22 mst_{\textrm{step}}(1) \approx 22\text{ ms}): the allreduce takes longer than the step itself. Equation (13.8.1) predicts a slowdown on 2 GPUs (∼0.85×\sim 0.85\times) and only ∼1.3×\sim 1.3\times on 4 GPUs.
  • Compiled bf16 at batch 512 per GPU (tstep(1)≈90–100 mst_{\textrm{step}}(1) \approx 90\text{--}100\text{ ms}): the step is much longer than the allreduce, predicting ∼1.5×\sim 1.5\times on 2 GPUs and 2.6–2.7×2.6\text{--}2.7\times on 4 GPUs.

Because frameworks overlap gradient allreduce buckets with the backward pass (Figure 13.6.1), (13.8.1) is usually a lower bound on speedup, and the margin above it measures how much communication was hidden behind backward computation. It is not a guaranteed one: NCCL's copy kernels compete with the backward pass for the same GPU (Section 13.6.2), and this contention can eat the margin.

13.8.3.2 Measured Speedup#

data_parallel(k, bf16, batch_size) measures training throughput on kk GPUs alongside the standalone allreduce time for a 76 MB76\text{ MB} gradient buffer on the same GPUs.

DistributedDataParallel runs one process per GPU via d2l.torchrun (Section 13.6), overlapping bucketed allreduces with the backward pass. It compiles without CUDA graphs (device execution is long enough to hide host dispatch) and benchmarks k=1k = 1 under identical conditions.

DDP_GPT = r'''
import json, sys, torch
from torch.nn.parallel import DistributedDataParallel as DDP
from d2l import torch as d2l

rank, k, device = d2l.init_distributed()
bf16, batch_size = sys.argv[1] == 'bf16', int(sys.argv[2])
torch.set_float32_matmul_precision('high')
torch._inductor.config.compile_threads = 1  # k processes compile at once
data = d2l.WikiText103(batch_size, 128)
corpus = torch.tensor(data.train, device=device)
model = DDP(d2l.GPT(len(data.vocab), num_hiddens=512).to(device))
step = d2l.make_step(model, torch.compile(model, dynamic=False), bf16)
batches = d2l.windows(corpus, batch_size)
seconds = d2l.Benchmark(lambda: step(*next(batches)), 20, 50).time
grads = torch.zeros(d2l.num_params(model), device=device)
allreduce = d2l.Benchmark(lambda: torch.distributed.all_reduce(grads),
                          repeats=10).time
if rank == 0:
    print(json.dumps({'speed': k * batch_size * 128 / seconds,
                      'allreduce': allreduce}))
torch.distributed.destroy_process_group()
'''

# The CUDA graphs of the compiled steps above hold memory on GPU 0, which
# the process of rank 0 needs: reset the compiler and return the memory
torch.compiler.reset()
torch.cuda.empty_cache()

def data_parallel(k, bf16, batch_size):
    """Tokens per second on k GPUs, and seconds per allreduce of all
    gradients."""
    r = d2l.torchrun(DDP_GPT, k, 'bf16' if bf16 else 'fp32', batch_size)[0]
    return r['speed'], r['allreduce']

We now run data_parallel for both the short fp32 step (batch_size=64) and the long bf16 step (batch_size=512) across k∈{1,2,4}k \in \{1, 2, 4\} GPUs, comparing the no-overlap prediction (13.8.1) against the measured speedup:

for bf16, batch_size in ((False, 64), (True, 512)):
    tokens = batch_size * 128  # Per GPU and step
    one, _ = data_parallel(1, bf16, batch_size)
    print(f'{"bf16" if bf16 else "fp32"}, batch {batch_size} per GPU: '
          f'{one:,.0f} tokens/s on one GPU')
    for k in (2, 4):
        if k <= d2l.num_gpus():
            speed, allreduce = data_parallel(k, bf16, batch_size)
            predicted = k * tokens / (tokens / one + allreduce)
            print(f'  {k} GPUs: allreduce {1e3 * allreduce:3.0f} ms, '
                  f'speedup predicted {predicted / one:.2f}x, '
                  f'measured {speed / one:.2f}x')
fp32, batch 64 per GPU: 364,947 tokens/s on one GPU
  2 GPUs: allreduce  31 ms, speedup predicted 0.83x, measured 0.91x
  4 GPUs: allreduce  48 ms, speedup predicted 1.27x, measured 1.36x
bf16, batch 512 per GPU: 662,971 tokens/s on one GPU
  2 GPUs: allreduce  31 ms, speedup predicted 1.52x, measured 1.63x
  4 GPUs: allreduce  48 ms, speedup predicted 2.69x, measured 2.92x

The standalone allreduce takes 31 ms31\text{ ms} on 2 GPUs and 48 ms48\text{ ms} on 4 GPUs, matching our link-rate estimate within a millisecond. Both predictions of opposite sign hold: at batch 64, 2 GPUs are slower than 1 GPU and 4 GPUs gain less than 1.5×1.5\times; at batch 512 in bf16, 4 GPUs reach roughly 3×3\times single-GPU throughput (the largest speedup of any single change in this section), with communication overlap pushing the measured speedup above the no-overlap floor (13.8.1). (On an NVLink machine with 900 GB/s900\text{ GB/s} per direction, a 76 MB76\text{ MB} allreduce takes a fraction of a millisecond and scales nearly linearly even at batch 64.)

13.8.4 Results#

We now summarize all single-GPU optimizations side by side, verify that the final step still trains the model properly, and account for where its remaining time goes.

13.8.4.1 Cumulative Comparison#

The table below lists the single-GPU configurations in order. Each step ratio is measured relative to the row above it, total is the cumulative speedup over the baseline, and checkpointing appears below the line as an unkept branch. TFLOP/s converts throughput to arithmetic rate at 6 FLOPs6\text{ FLOPs} per parameter and token, and MFU divides by the RTX 4090's 165.2 TFLOP/s165.2\text{ TFLOP/s} bf16 peak (model FLOPs utilization, Chowdhery et al. (2022); Exercise 1 adds the attention-score FLOPs).

flops = 6 * num_params  # Per token, without the attention scores
peak = {'tf32': 82.6e12, 'bf16': 165.2e12}  # FLOP/s of the RTX 4090
print(f'{"configuration":18}{"tokens/s":>10}{"step":>7}{"total":>7}'
      f'{"TFLOP/s":>9}{"MFU":>6}')
first = previous = next(iter(results.values()))
for name, speed in results.items():
    print(f'{name:18}{speed:10,.0f}{speed / previous:6.2f}x'
          f'{speed / first:6.2f}x{speed * flops / 1e12:9.1f}'
          f'{speed * flops / peak["bf16"]:6.0%}')
    previous = speed
print('-' * 57)
for name, speed in branches.items():  # Measured on top of the last row
    print(f'{name:18}{speed:10,.0f}{speed / previous:6.2f}x{"":7}'
          f'{speed * flops / 1e12:9.1f}{speed * flops / peak["bf16"]:6.0%}'
          '  (not kept)')
configuration       tokens/s   step  total  TFLOP/s   MFU
baseline             317,736  1.00x  1.00x     36.2   22%
+ compile            368,688  1.16x  1.16x     42.1   25%
+ bf16               643,350  1.74x  2.02x     73.4   44%
+ batch 512          653,141  1.02x  2.06x     74.5   45%
---------------------------------------------------------
+ checkpointing      556,390  0.85x            63.5   38%  (not kept)

Cumulatively, the single-GPU optimizations double training throughput, reaching roughly 50% of the RTX 4090's bf16 peak. Nearly all of the gain comes from speeding up the matrix products (bf16) and reducing memory traffic around them (kernel fusion), whereas removing host overhead and enlarging the minibatch contribute a few percent each, just as the profiles predicted.

Note that each speedup ratio depends on its position in the sequence (Exercise 7) and on the hardware balance: on a faster GPU (or with a smaller model), device execution is shorter, making host dispatch removal much more impactful.

13.8.4.2 Training Check#

Higher throughput is useless if an optimization silently breaks training. We verify correctness by training two identically initialized models (one with the baseline step and one with the final compiled bf16 step) on the same 200 minibatches of 512 windows (∼13M\sim 13\text{M} tokens), using a 50-step linear learning-rate warm-up to prevent late AdamW loss spikes (Section 11.2). We check that both models agree within 0.15 nats/byte0.15\text{ nats/byte} on the mean loss of the last 20 steps and on the validation loss (d2l.lm_perplexity, Section 9.3), and that both beat the 2.45 nats/byte2.45\text{ nats/byte} bigram baseline of Section 11.2.

learner = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
reference = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
reference.load_state_dict(learner.state_dict())  # One initialization
steps = {'baseline': make_step(reference, warmup=50),
         'final': make_step(learner, torch.compile(
             learner, dynamic=False, mode='reduce-overhead'), bf16=True,
             warmup=50)}
batches = windows(corpus, 512)
minibatches = [next(batches) for _ in range(200)]  # The same for both
losses = {name: torch.stack([step(X, Y).detach()
                             for X, Y in minibatches]).tolist()
          for name, step in steps.items()}
validation = {name: math.log(d2l.lm_perplexity(net, data.val_dataloader()))
              for name, net in (('baseline', reference), ('final', learner))}

We now compare the training loss trajectories at steps 1, 50, 100, and 200 alongside the final 20-step mean (late) and validation log-perplexity (validation), asserting that both runs beat the 2.45 nats/byte2.45\text{ nats/byte} bigram threshold and agree within 0.15 nats/byte0.15\text{ nats/byte}:

checkpoints = (1, 50, 100, 200)
late = {name: np.mean(curve[-20:]) for name, curve in losses.items()}
print(f'{"loss at step":14}' + ''.join(f'{i:>7}' for i in checkpoints)
      + f'{"mean of last 20":>17}{"validation":>12}')
for name, curve in losses.items():
    print(f'{name:14}' + ''.join(f'{curve[i - 1]:7.2f}' for i in checkpoints)
          + f'{late[name]:17.2f}{validation[name]:12.2f}')
    assert validation[name] < 2.45  # Better than the bigram model
for values in (late, validation):  # The final step trains like the baseline
    assert abs(values['baseline'] - values['final']) < 0.15
loss at step        1     50    100    200  mean of last 20  validation
baseline         5.66   2.52   2.03   1.49             1.52        1.47
final            5.66   2.51   2.06   1.50             1.53        1.47

Both curves start at log⁡256≈5.55\log 256 \approx 5.55, track each other closely across all 200 steps, and reach nearly identical validation losses well below the bigram threshold. Notice, however, that 200 steps at batch size 512 (13M13\text{M} tokens) end at a higher loss than 1,000 cosine-decayed steps at batch size 64 (8M8\text{M} tokens) in Section 11.2: raw token throughput is not identical to time-to-target-loss (Exercise 5).

13.8.4.3 Account of the Final Step#

Finally, account normalizes the baseline and final profiles to milliseconds per 8,1928{,}192 tokens, comparing total wall-clock time against ideal peak arithmetic time, actual matrix-product kernel time, and non-matmul kernel time.

def account(kernels, tokens, speed):
    """Milliseconds per 8,192 tokens of a step of `tokens` tokens that runs
    at `speed` tokens/s: the step, its matrix products, and all its other
    kernels."""
    per_step = 8192 / tokens  # Steps per 8,192 tokens
    products = per_step * sum(  # Kernel names as in d2l.show_profile
        ms for name, ms in kernels.items()
        if re.search(d2l.PRODUCT_KERNELS, name, re.I))
    other = per_step * sum(kernels.values()) - products
    return 1e3 * 8192 / speed, products, other

print(f'{"ms per 8,192 tokens":24}{"step":>6}{"at peak":>9}'
      f'{"products":>10}{"other":>7}')
for name, tokens, fmt in (('baseline', 64 * 128, 'tf32'),
                          ('+ batch 512', 512 * 128, 'bf16')):
    wall, products, other = account(profiles[name], tokens, results[name])
    arithmetic = 1e3 * 8192 * flops / peak[fmt]  # At the peak of the format
    print(f'{name + " (" + fmt + ")":24}{wall:6.1f}{arithmetic:9.1f}'
          f'{products:10.1f}{other:7.1f}')
ms per 8,192 tokens       step  at peak  products  other
baseline (tf32)           25.8     11.3      15.6    8.8
+ batch 512 (bf16)        12.5      5.7       7.1    5.4

Per 8,1928{,}192 tokens, the final step spends about 7 ms7\text{ ms} in matrix products (running at over 80% of the 5.7 ms5.7\text{ ms} bf16 ideal) and 5 ms5\text{ ms} in bandwidth-bound kernels between them—a classic roofline split where contractions perform over 99% of the FLOPs but take roughly 60% of the time (Ivanov et al., 2021). Because neither faster arithmetic alone (e.g., fp8) nor eliminating non-matmul memory traffic alone can halve a step split 7 ms7\text{ ms} to 5 ms5\text{ ms}, another 2×2\times speedup would require both.

13.8.5 Summary#

A kernel profile classifies a training step's bottleneck and bounds the gain of each candidate optimization before it is applied: reducing host dispatch saves at most the device idle time, kernel fusion saves at most the non-matmul device time, and doubling tensor-core precision throughput gives a speedup between 1/(1−f/2)1/(1 - f/2) and 22 when matrix products occupy a fraction ff of the step. Because removing one bottleneck shifts the remaining shares of the step, optimizations must be verified for numerical equivalence and measured cumulatively. On a single RTX 4090, our 19M-parameter GPT step doubled in speed to reach 45–50% MFU, driven almost entirely by bf16 matrix products and kernel fusion, leaving a final step split roughly 60/40 between near-peak matrix contractions and bandwidth-bound kernels. Finally, the data-parallel cost model tstep(1)+tallreduce(k)t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k) predicted both the slowdown on two GPUs for the short fp32 step (22 ms22\text{ ms} step versus a 31 ms31\text{ ms} PCIe allreduce) and the roughly 3×3\times speedup on four GPUs for the batch-512 bf16 step (90–100 ms90\text{--}100\text{ ms} step versus a 48 ms48\text{ ms} allreduce).

13.8.6 Exercises#

  1. [code] Model FLOPs utilization. The GPT of Section 13.8.1 has L=6L = 6 blocks of width d=512d = 512 and context length T=128T = 128. Up to SwiGLU rounding, each block holds 12d212d^2 weights in its matrix products, and training costs about 6 FLOPs6\text{ FLOPs} per weight and token.

    1. The attention score product QK⊤\mathbf{Q}\mathbf{K}^\top and value aggregation are weightless matrix products. Count their training FLOPs per token and block (taking the backward pass as twice the forward pass and including masked entries). Show that their ratio to the weight FLOPs is T/(6d)T/(6d), and evaluate this ratio for T=128T = 128 and T=1,024T = 1{,}024.
    2. Recompute the TFLOP/s and MFU columns of the cumulative table with attention FLOPs included, along with the fraction of each configuration's native format peak (165 TFLOP/s165\text{ TFLOP/s} in bf16, 83 TFLOP/s83\text{ TFLOP/s} in tf32).
    3. Name two configurations or kernels in Section 13.8.2 where theoretical model FLOPs differ from hardware-executed FLOPs, and state the direction of each difference.
  2. [code] Fixed cost of a step. Model the bf16 step time at batch size BB windows as t(B)=a+bBt(B) = a + bB, with fixed per-step cost aa and per-window cost bb.

    1. Measure the step time at B=32,64,128,256,512B = 32, 64, 128, 256, 512, fit aa and bb by least squares, and report the fraction of the B=64B = 64 step accounted for by aa.
    2. The text estimated AdamW updates and fp32/bf16 weight casts at ∼0.75 ms/step\sim 0.75\text{ ms/step}. What fraction of aa does this explain? Identify other BB-independent work and check against a profile at B=32B = 32.
    3. Use your linear fit to predict throughput at B=1,024B = 1{,}024 and B=2,048B = 2{,}048, check whether they fit in 24 GiB24\text{ GiB} of GPU memory, and measure those that do.
  3. [code] Cost of recomputation. Activation checkpointing in Section 13.8.2 beat both the FLOP-count estimate and the standalone forward-pass timing estimate.

    1. Profile the standalone forward pass and the checkpointed step with d2l.kernel_times. Match the kernels added by checkpointing against the standalone forward kernels: which reappear unchanged, and which are fused into backward kernels?
    2. Time the forward pass of the six blocks alone (excluding embeddings and the output layer) and recompute the throughput lower bound.
    3. Checkpoint only every second block: predict the throughput and memory from your measurements before running, then measure and compare.
  4. [code] Causality gate. Suppose a defective attention kernel silently ignores the causal mask.

    1. Explain why the training loss, validation window loss, and the 2.45 nats/byte2.45\text{ nats/byte} bigram threshold in Section 13.8.4 would all fail to flag this defect if both baseline and learner used the defective kernel.
    2. Write a test that perturbs the final input token of every sequence in a minibatch and verifies that logits at all earlier positions remain unchanged within numerical tolerance. Run it on learner and on a copy whose attention omits the causal mask.
  5. Throughput versus time to target. The model of Section 9.8 estimates that training at batch size bb requires E(b)=Emin⁡(1+b/bnoise)E(b) = E_{\min}(1 + b / b_{\textrm{noise}}) training examples to reach a target loss, where bnoiseb_{\textrm{noise}} is the gradient noise scale.

    1. Let ρ>1\rho > 1 be the throughput ratio of batch 512 to batch 64. Show that batch 512 reaches the target loss in less wall-clock time if and only if
bnoise>512−64ρρ−1,(13.8.2)b_{\textrm{noise}} > \frac{512 - 64\rho}{\rho - 1}, \tag{13.8.2}

and evaluate this threshold for ρ=1.2\rho = 1.2, ρ=1.7\rho = 1.7, and the measured ρ\rho from Section 13.8.4.

  1. Classify each change in Section 13.8.2, weak-scaling data parallelism, and switching to Muon (Section 9.6) by whether it alters E(b)E(b), token throughput, or both.
  1. [code] Width 256. At num_hiddens=256, d2l.GPT matches the architecture trained in Section 11.2.

    1. For the 8,192×2568{,}192 \times 256 by 256×256256 \times 256 output projection Wo\mathbf{W}_o, compute the arithmetic intensity in 4-byte tf32 and 2-byte bf16, place both on the RTX 4090 roofline (Figure 13.1.1), and predict the bf16 speedup for this product.
    2. Run the baseline and the first two optimizations of Section 13.8.2 at num_hiddens=256, profile them with profile and account, and compare the measured matrix-product speedup with your roofline prediction.
  2. [code] Order of the changes. Each speedup ratio in the cumulative table depends on the optimizations applied before it.

    1. Using the baseline profile and the bound in Section 13.8.2.3, predict the speedup of applying bf16 directly to the uncompiled baseline.
    2. Measure that speedup and compare it with your prediction and with the + bf16 row in the cumulative table. Then apply compilation (the table's second row) on top of bf16 and explain how both ratios shifted using the kernel profiles.

Discussions