13.1 The Performance Model

Every network we have trained so far spends most of its arithmetic in matrix products, and we have implicitly assumed that a GPU computes them near its peak rate. That assumption is often wrong. On the RTX 4090 that runs this book's notebooks, a bf16 product of two 8192×81928192 \times 8192 matrices runs within a few percent of the 165 TFLOP/s hardware peak, whereas a 256×256256 \times 256 product reaches less than two percent of it—same operation, same chip, timed properly. A training step is a sequence of many operations, some of them small. When most of them run at a fraction of peak, a faster GPU or a second card changes little because the time goes to waiting rather than computing.

Every operation on a GPU is limited by one of three resources: the arithmetic units, the memory bandwidth that feeds them, or the fixed host cost of issuing the operation from Python. Two paper counts—the FLOPs an operation performs and the bytes it moves—decide between the first two. Adding one measured constant, the host time hh to issue a call, lets us predict the third as well. Our method throughout the chapter is to count FLOPs and bytes, predict the time, measure it, and explain the difference.

import os
import re
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 set the float32 matrix-multiplication precision to 'high' so that fp32 matrix products use the tf32 tensor cores:

# Run fp32 matrix products on the tf32 tensor cores (PyTorch's default is
# full fp32). The bf16 products below are unaffected.
torch.set_float32_matmul_precision('high')

13.1.1 Arithmetic Intensity and the Roofline#

Before timing anything, we can predict from an operation's shapes which resource limits it. We used this idea briefly in Section 11.3.2.1 to explain why prefill processes tokens much faster than autoregressive decoding; here we develop it in full.

13.1.1.1 Counting FLOPs and Bytes#

Every tensor operation makes two demands on a GPU: it performs arithmetic, counted in floating-point operations (FLOPs, one addition or multiplication each), and it moves bytes between the GPU's main memory and its on-chip processors.

The GPU has a separate budget for each. The main memory of the RTX 4090 delivers at most β=1.008×1012\beta = 1.008 \times 10^{12} bytes/s (~1 TB/s). Its peak arithmetic rate PP depends on the number format and unit: bf16 matrix products on the tensor cores reach P=165×1012P = 165 \times 10^{12} FLOP/s, while tf32 matrix products and standard fp32 arithmetic run at half that rate (82.6 TFLOP/s) at the rated 2.52 GHz boost clock. The rated clock is a nominal value: a card runs a few percent faster or slower depending on its temperature and power draw. We therefore treat a measured rate within about 5% of PP, on either side, as being at the roof.

Which budget runs out first depends on their ratio, the arithmetic intensity

I  =  FLOPs performedbytes moved.I \;=\; \frac{\textrm{FLOPs performed}}{\textrm{bytes moved}}.

Consider the matrix product XW\mathbf{X}\mathbf{W} with X∈RB×D\mathbf{X} \in \mathbb{R}^{B \times D} and W∈RD×F\mathbf{W} \in \mathbb{R}^{D \times F}, a linear layer applied to a batch of BB rows. It performs 2BDF2BDF FLOPs (one multiply and one add per inner-product term) and at best reads X\mathbf{X} and W\mathbf{W} once and writes the output once (BD+DF+BFBD + DF + BF numbers). With bb bytes per number, its intensity is

2BDFb (BD+DF+BF)  =  2b(1F+1B+1D)−1  ≈  2Bbfor B≪D,F.(13.1.1)\begin{aligned} \frac{2BDF}{b\,(BD + DF + BF)} &\;=\; \frac{2}{b}\left(\frac{1}{F} + \frac{1}{B} + \frac{1}{D}\right)^{-1} \\ &\;\approx\; \frac{2B}{b} \quad \textrm{for } B \ll D, F. \end{aligned} \tag{13.1.1}

The middle expression shows that the smallest of (B,D,F)(B, D, F) governs the intensity. When the batch size BB is much smaller than the layer dimensions, intensity grows linearly with BB because every weight fetched from memory is reused across all BB rows.

For a 1B-parameter GPT with width D=F=2048D = F = 2048 in bf16 (b=2b = 2), a training minibatch of 8 sequences of 1,024 tokens has B=8192B = 8192 rows, giving I≈910I \approx 910 FLOP/byte by (13.1.1) (limited by the width DD). During single-sequence autoregressive generation, B=1B = 1 and I≈1I \approx 1 FLOP/byte. The same layer spans nearly three orders of magnitude in intensity between training and decoding. At the bottom end lies an elementwise operation such as yi=xi+1y_i = x_i + 1, which performs 1 FLOP per 2b2b bytes moved (I=0.25I = 0.25 FLOP/byte in bf16), regardless of tensor size.

13.1.1.2 The Roofline Model#

The roofline model (Williams et al., 2009) turns intensity into an upper bound on throughput: an operation runs no faster than the compute roof PP and no faster than memory supplies data at rate IβI\beta:

performance  ≤  min⁡(P,  Iβ).(13.1.2)\textrm{performance} \;\leq\; \min(P,\; I \beta). \tag{13.1.2}

On log–log axes, the bound is a sloped bandwidth line meeting a flat compute roof at the ridge point I∗=P/βI^* = P/\beta (Figure 13.1.1). Below I∗I^* an operation is bandwidth-bound: memory cannot keep the arithmetic units fed, so extra arithmetic on data already on chip is free. Above I∗I^* it is compute-bound: the arithmetic units are saturated, and moving fewer bytes does not speed it up. Throughout this chapter, β\beta denotes main-memory (DRAM) bandwidth; operands small enough to reside in the 72 MB on-chip L2 cache can exceed this roof.

Figure 13.1.1:

The roofline of the RTX 4090. Attainable throughput is the smaller of the compute roof PP and the arithmetic intensity times the memory bandwidth β\beta. The points mark the examples of the text: x+1x + 1 in bf16, a linear layer of width 2048 applied to one token, and the same layer applied to a minibatch of 8,192 tokens. The ridge point lies near 164 FLOP/byte.

13.1.1.3 The Ridge Point#

For bf16 tensor-core products on the RTX 4090, the ridge point is I∗=165.2/1.008≈164I^* = 165.2 / 1.008 \approx 164 FLOP/byte; for tf32 products (P=82.6P = 82.6 TFLOP/s), it is I∗≈82I^* \approx 82 FLOP/byte. Modern data-center GPUs have even higher ridge points (around 280–300 FLOP/byte) because tensor-core FLOP/s has grown faster than HBM bandwidth. Only large matrix products clear these thresholds; elementwise ops, normalizations, and single-token decoding all sit far below the ridge.

For a square bf16 matrix product (B=D=F=nB = D = F = n), I=n/3I = n / 3, so the roofline predicts that every product with n≳500n \gtrsim 500 is compute-bound. Testing that prediction requires accurate GPU timing.

13.1.2 Timing GPU Code#

Because GPU dispatch is asynchronous (Section 5.7.2.1), Python queues kernels and moves on immediately. Reading a wall clock around a kernel call without synchronization measures how long Python took to enqueue the work, not how long the GPU took to execute it. Accurate timing warms up the device, synchronizes before starting and stopping the clock, and averages over many repeats, as d2l.Benchmark does.

13.1.2.1 Synchronization Points#

Python blocks on the GPU only when it requests a value residing on the device: converting a tensor to a Python scalar or NumPy array, printing it, branching on it (if loss < 0.1:), or running an operation whose output shape depends on tensor values (such as boolean masking x[x > 0]).

If the host takes time hh to issue a step and the GPU takes tdevt_\textrm{dev} to execute it, an unsynchronized loop overlaps host dispatch with device execution, whereas reading a scalar every step serializes them and adds a device-to-host round-trip latency σ\sigma:

tonce  ≈  max⁡(h, tdev),tevery  ≲  h+tdev+σ.t_\textrm{once} \;\approx\; \max(h,\, t_\textrm{dev}), \qquad t_\textrm{every} \;\lesssim\; h + t_\textrm{dev} + \sigma.

We compare two 1,000-step loops that multiply a 1024×10241024 \times 1024 matrix by itself and accumulate the sum on the GPU: one converts the running total to a Python float every step, and the other reads it once at the end.

x = torch.ones(1024, 1024, device=d2l.try_gpu())
s = torch.zeros((), device=x.device)
s += (x @ x).sum()
float(s)                          # Warm up: load the kernels

torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(1000):
    s += (x @ x).sum()
    total = float(s)              # Reads the value: a barrier every step
read_every = time.perf_counter() - t0

torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(1000):
    s += (x @ x).sum()            # Stays on the device: no barrier
total = float(s)                  # One read at the end
read_once = time.perf_counter() - t0
print(f'read every step: {read_every:.3f} s   read once: {read_once:.3f} s')
read every step: 0.063 s   read once: 0.040 s

Without per-step reads, the three calls per step take ~40 µs of host dispatch time (longer than the ~26 µs of tf32 device work), so the GPU runs behind the host. Reading float(s) every step forces host and device to take turns, slowing the loop by ~1.6×.

Training loops should therefore accumulate metrics on the device and read them only at logging intervals.

13.1.2.2 A Benchmark Helper#

From here on we time operations with d2l.Benchmark, which runs warm-up calls to absorb compilation and kernel-loading overhead, then times repeats calls between two device barriers. As a first check, a 4096×40964096 \times 4096 bf16 product has intensity I≈1365I \approx 1365 FLOP/byte, well above the ridge, so the roofline predicts 2⋅40963/P≈0.832 \cdot 4096^3 / P \approx 0.83 ms.

a = torch.randn(4096, 4096, device=d2l.try_gpu(), dtype=torch.bfloat16)
d2l.Benchmark(lambda: torch.mm(a, a), desc='4096 x 4096 product')
4096 x 4096 product: 0.90 ms/call

The measured time is within about 10% of the 0.83 ms prediction.

13.1.3 Three Regimes#

The wall-clock time of a GPU program divides into compute-bound kernels, bandwidth-bound kernels, and idle gaps where the device waits for the host (He, 2022). Three experiments isolate each regime.

13.1.3.1 The Bandwidth Roof and the Compute Roof#

First, we multiply an activation matrix of BB rows by a d×dd \times d bf16 weight matrix with d=16,384d = 16{,}384 (512 MiB). By (13.1.1), its intensity is approximately BB, crossing the ridge near B=164B = 164. Below the ridge, every call must stream 512 MiB of weights (~0.53 ms at 1.008 TB/s) regardless of BB; above the ridge, the 2Bd22Bd^2 FLOPs govern the time, scaling linearly with BB (0.83 ms at B=256B = 256, 3.32 ms at B=1024B = 1024).

peak_tflops = 165.2    # RTX 4090: dense bf16 on the tensor cores
bandwidth_tbs = 1.008  # RTX 4090: GDDR6X memory
print(f'{torch.cuda.get_device_name()}: ridge point '
      f'{peak_tflops / bandwidth_tbs:.0f} FLOP/byte')
d, b = 16384, 2  # Width and bytes per bf16 number
W = torch.randn(d, d, dtype=torch.bfloat16, device=d2l.try_gpu())  # 0.54 GB
for B in (1, 4, 16, 64, 128, 256, 1024):
    X = torch.randn(B, d, dtype=torch.bfloat16, device=W.device)
    t = d2l.Benchmark(lambda: X @ W).time
    flops, nbytes = 2 * B * d * d, b * (B * d + d * d + B * d)
    t_mem, t_comp = nbytes / bandwidth_tbs / 1e12, flops / peak_tflops / 1e12
    roof = 'memory' if t_mem > t_comp else 'compute'
    print(f'B = {B:4d}: bound {1e3 * max(t_mem, t_comp):4.2f} ms ({roof:7s}), '
          f'measured {1e3 * t:4.2f} ms, {flops / t / 1e12:5.1f} TFLOP/s')
NVIDIA GeForce RTX 4090: ridge point 164 FLOP/byte
B =    1: bound 0.53 ms (memory ), measured 0.57 ms,   0.9 TFLOP/s
B =    4: bound 0.53 ms (memory ), measured 0.57 ms,   3.7 TFLOP/s
B =   16: bound 0.53 ms (memory ), measured 0.57 ms,  15.0 TFLOP/s
B =   64: bound 0.54 ms (memory ), measured 0.58 ms,  58.9 TFLOP/s
B =  128: bound 0.54 ms (memory ), measured 0.64 ms, 106.9 TFLOP/s
B =  256: bound 0.83 ms (compute), measured 0.90 ms, 152.2 TFLOP/s
B = 1024: bound 3.33 ms (compute), measured 3.34 ms, 164.6 TFLOP/s

One weight matrix reaches both roofs: from B=1B = 1 to B=128B = 128 the time stays flat near 0.6 ms despite 128×128\times more arithmetic, and from B=256B = 256 upward it grows linearly with BB near the compute roof. Serving 1,024 tokens at once performs 1,024×1{,}024\times the arithmetic of serving one token in less than 6×6\times the time.

13.1.3.2 Elementwise Operations#

Next, we stay far below the ridge and vary the arithmetic per element on an 8192×81928192 \times 8192 fp32 tensor (256 MiB): addition, multiplication, sine, and sigmoid. Each reads 256 MiB and writes 256 MiB (512 MiB total, or 0.53 ms at 1.008 TB/s).

x = torch.randn(8192, 8192, device=d2l.try_gpu())  # 256 MiB in fp32
for desc, f in [('add', lambda x: x + 1), ('mul', lambda x: x * 1.5),
                ('sin', torch.sin), ('sigmoid', torch.sigmoid)]:
    print(d2l.Benchmark(lambda: f(x), desc=desc))
add: 0.59 ms/call
mul: 0.59 ms/call
sin: 0.59 ms/call
sigmoid: 0.58 ms/call

All four take ~0.6 ms, achieving ~0.9 TB/s of effective memory bandwidth: because memory traffic sets the time, transcendental arithmetic (sin, sigmoid) costs no more time than x + 1.

In eager execution, chaining elementwise operations compounds this memory traffic. The tanh approximation to GELU below (gelu_ish) chains 8 elementwise operations. Six unary operations each read and write one tensor (12 tensors), and two binary operations (x + 0.04 * x**3 and the final multiplication by 0.5 * x) each read two tensors and write one (6 tensors), moving 18 tensors of 256 MiB in total—9×9\times the bytes of a single addition.

def gelu_ish(x):
    """The tanh approximation of GELU with rounded constants: a chain of
    eight elementwise operations."""
    return 0.5 * x * (1 + torch.tanh(0.8 * (x + 0.04 * x**3)))

print(d2l.Benchmark(lambda: x + 1, desc='1 op'))
print(d2l.Benchmark(lambda: gelu_ish(x), desc='chain'))  # Eager: 8 kernels
1 op: 0.59 ms/call
chain: 5.25 ms/call

As predicted, the unfused chain takes 8×8\times to 9×9\times as long as x + 1. Kernel fusion (Section 13.3) merges the chain into a single kernel that reads x once and writes the output once.

13.1.3.3 Matrix Products across Sizes#

Does a square bf16 product reach the compute roof as soon as I=n/3I = n / 3 crosses 164 near n=500n = 500? Let us sweep nn from 256 to 8,192.

sizes = [256, 512, 1024, 2048, 4096, 8192]
times = []
for n in sizes:
    a = torch.randn(n, n, device=d2l.try_gpu(), dtype=torch.bfloat16)
    times.append(d2l.Benchmark(lambda: torch.mm(a, a), repeats=100).time)

We plot the achieved TFLOP/s against the arithmetic intensity n/3n / 3 alongside the roofline bound (13.1.2).

measured = [2 * n**3 / t / 1e12 for n, t in zip(sizes, times)]
intensity = [n / 3 for n in sizes]  # FLOP/byte of a square bf16 product
ridge = peak_tflops / bandwidth_tbs
roof_x = [intensity[0], ridge, intensity[-1]]
roof_y = [min(peak_tflops, bandwidth_tbs * i) for i in roof_x]
d2l.plot([roof_x, intensity], [roof_y, measured],
         'arithmetic intensity (FLOP/byte)', 'TFLOP/s',
         legend=['roofline bound', 'measured'],
         xscale='log', yscale='log', fmts=('-', 'o'))

Printing the exact per-call latency t (in microseconds) and throughput tf for each matrix size n makes the flat-time floor at small nn explicit:

for n, t, tf in zip(sizes, times, measured):
    print(f'n = {n:4d}: {1e6 * t:7.1f} us per call, {tf:5.1f} TFLOP/s')
n =  256:    12.7 us per call,   2.6 TFLOP/s
n =  512:    13.7 us per call,  19.5 TFLOP/s
n = 1024:    16.0 us per call, 134.3 TFLOP/s
n = 2048:   102.8 us per call, 167.1 TFLOP/s
n = 4096:   873.6 us per call, 157.3 TFLOP/s
n = 8192:  6690.3 us per call, 164.3 TFLOP/s

At n=4096n = 4096 and 81928192 the product runs at the 165 TFLOP/s roof, to within the 5% by which the clock varies. At small sizes, however, the points lie far below the roofline and climb with a log–log slope of 3—the signature of a constant time per call while work scales as n3n^3. From n=256n = 256 to 10241024 the work grows 64×64\times, yet the time per call changes by less than 2×2\times.

To see whether that constant time is spent on the host or the device, we time a 256×256256 \times 256 product alongside x + 1 of the same shape, and use the profiler helper d2l.kernel_times (which we construct below in Section 13.1.4) to measure how long the GPU itself is busy per call.

a = torch.randn(256, 256, device=d2l.try_gpu(), dtype=torch.bfloat16)
for desc, f in [('256 x 256 product', lambda: torch.mm(a, a)),
                ('x + 1 on 256 x 256', lambda: a + 1)]:
    wall = d2l.Benchmark(f, repeats=100).time
    busy = sum(d2l.kernel_times(f, steps=100).values()) / 1e3  # Seconds
    print(f'{desc:18s}: {1e6 * wall:5.1f} us per call, '
          f'device busy {1e6 * busy:4.1f} us')
256 x 256 product :  21.0 us per call, device busy  3.2 us
x + 1 on 256 x 256:  10.9 us per call, device busy  1.0 us

In both cases the GPU works for only a few microseconds; the rest is the host dispatch time hh (Python, framework, and driver). For a 256×256256 \times 256 matrix multiplication, the most expensive part of the operation is the line of Python that asks for it. When calls are queued back-to-back, host and device overlap and each call takes max⁡(h,2n3/P)\max(h, 2n^3/P). For small nn, the device finishes before the host issues the next call, placing the program in the overhead-bound regime. The knee where compute overtakes dispatch lies at n≈(hP/2)1/3n \approx (hP/2)^{1/3}.

With h≈13h \approx 13 µs, the knee lies near n=1,000n = 1{,}000.

Combining all three floors gives our fundamental time bound for a single dispatched operation:

t  ≳  max⁡(h,  FLOPsP,  bytesβ).(13.1.3)t \;\gtrsim\; \max\left(h,\; \frac{\textrm{FLOPs}}{P},\; \frac{\textrm{bytes}}{\beta}\right). \tag{13.1.3}

With h=10h = 10 µs, any operation with fewer than hP≈1.6×109hP \approx 1.6 \times 10^9 FLOPs and fewer than hβ≈10h\beta \approx 10 MB moved takes the time of its launch alone. Moreover, the knee n≈(hP/2)1/3n \approx (hP/2)^{1/3} grows with PP: faster GPUs require larger operations to avoid becoming overhead-bound.

13.1.3.4 Diagnosis and Fixes#

In a full training step the three regimes mix, and the dominant share names the step's regime (Figure 13.1.2). Table 13.1.1 summarizes the symptom and standard remedies for each regime.

Figure 13.1.2:

The three regimes, schematically. Where the time of a step goes, among compute-bound kernels, bandwidth-bound kernels, and idle gaps, determines which fix applies; each bar names one typical fix.

Table 13.1.1. Symptoms and standard fixes of the three regimes.
regimesymptomstandard fix
compute-bounddevice busy; intensity above the ridge; time grows with the FLOPsless arithmetic; a format with faster tensor cores; more devices
bandwidth-bounddevice busy; intensity below the ridge; time grows with the bytes moveda larger batch, which raises the intensity of the products; a narrower format; fusion; recomputation instead of storage; algorithms that reuse data on the chip
overhead-bounddevice idle between kernels; time per call independent of sizea larger batch, which means fewer calls per example; capturing the whole program and replaying it without Python

13.1.4 Profiling a Training Step#

A profiler records the duration of every GPU kernel so we can compare busy device time against wall-clock time and break down device time by kernel type. Before profiling, let us predict the time of one SGD step of an MLP (4096→4096→4096→104096 \to 4096 \to 4096 \to 10) on a minibatch of 1,024 examples in fp32 with tf32 matrix products (P=82.6P = 82.6 TFLOP/s).

13.1.4.1 Predicting the Step#

Each of the two 4096×40964096 \times 4096 layers performs 2⋅1024⋅40962≈3.44×10102 \cdot 1024 \cdot 4096^2 \approx 3.44 \times 10^{10} FLOPs per forward product. A training step runs five such products (two forward, two weight-gradient, and one input-gradient for the second hidden layer). At I≈340I \approx 340 FLOP/byte (above the tf32 ridge of 82), each product takes 3.44×1010/(82.6×1012)≈0.423.44 \times 10^{10} / (82.6 \times 10^{12}) \approx 0.42 ms. The SGD update reads each of the 33.6M fp32 weights and its gradient and writes the new weight (12×33.6×106≈0.4012 \times 33.6 \times 10^6 \approx 0.40 GB), taking ~0.40 ms at 1 TB/s. Neglecting the small final layer and ReLUs, the step should take

5×0.42 ms+0.40 ms  ≈  2.5 ms.5 \times 0.42 \textrm{ ms} + 0.40 \textrm{ ms} \;\approx\; 2.5 \textrm{ ms}.
net = nn.Sequential(nn.Linear(4096, 4096), nn.ReLU(),
                    nn.Linear(4096, 4096), nn.ReLU(),
                    nn.Linear(4096, 10)).to(d2l.try_gpu())
X = torch.randn(1024, 4096, device=d2l.try_gpu())
opt = torch.optim.SGD(net.parameters(), lr=0.01)

def step():
    opt.zero_grad()
    net(X).mean().backward()
    opt.step()

wall = d2l.Benchmark(step).time

kernel_times runs a function steps times under the framework profiler and returns the average device milliseconds per call for every kernel launched.

def kernel_times(f, steps=10):
    """Device milliseconds per call of f, for every kernel that f runs."""
    with torch.profiler.profile(
            activities=[torch.profiler.ProfilerActivity.CUDA],
            acc_events=True) as prof:
        for _ in range(steps):
            f()
        torch.cuda.synchronize()
    return {e.key: e.device_time_total / 1e3 / steps
            for e in prof.key_averages()
            if e.device_type == torch.autograd.DeviceType.CUDA}

The framework profiler can also export a timeline trace, viewable at https://ui.perfetto.dev.

prof.export_chrome_trace writes the trace of the profile in kernel_times.

13.1.4.2 Reading the Profile#

show_profile compares busy device time against wall-clock step time, computes the share spent in matrix-product kernels, and lists the top kernels.

PRODUCT_KERNELS = 'gemm|xmma|cutlass|matmul|sdpa'
# Kernel names that mark a matrix product: cuBLAS and CUTLASS kernels (gemm,
# xmma, cutlass, which also names PyTorch's fused attention), XLA's fused
# products (gemm_fusion_dot), and matmul or sdpa kernels

def show_profile(kernels, step_ms, rows=6):
    """Busy device time against the wall-clock time step_ms of a step, the
    share of the matrix products, and the kernels with the most time."""
    busy = sum(kernels.values())
    products = sum(ms for name, ms in kernels.items()
                   if re.search(PRODUCT_KERNELS, name, re.I))
    print(f'wall clock {step_ms:.2f} ms per step, device busy {busy:.2f} ms '
          f'({busy / step_ms:.0%}), matrix products {products / busy:.0%}')
    for name, ms in sorted(kernels.items(), key=lambda kv: -kv[1])[:rows]:
        name = re.sub(r'^void |\(anonymous namespace\)::|\w+::|\(.*', '', name)
        print(f'{ms:6.2f} ms {ms / busy:4.0%}  {name[:52]}')

We now apply show_profile to the kernel timings of our three-layer MLP step (kernel_times(step)) and compare busy device time against the measured wall-clock duration 1000 * wall:

show_profile(kernel_times(step), 1000 * wall)
wall clock 2.67 ms per step, device busy 2.65 ms (99%), matrix products 80%
  0.85 ms  32%  Kernel2<cutlass_80_tensorop_s1688gemm_256x128_16x3_n
  0.82 ms  31%  Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
  0.42 ms  16%  multi_tensor_apply_kernel<TensorListMetadata<2>, Bin
  0.40 ms  15%  Kernel2<cutlass_80_tensorop_s1688gemm_128x256_16x3_n
  0.06 ms   2%  vectorized_elementwise_kernel<4, BinaryFunctor<float
  0.02 ms   1%  vectorized_elementwise_kernel<4, launch_clamp_scalar

The measured step comes within ~10% of the predicted 2.5 ms, with the GPU busy for nearly the entire step. Matrix products (gemm kernels) account for over three quarters of the device time.

The three gemm lines aggregate the five large matrix products, and multi_tensor_apply_kernel is the batched SGD update at the predicted 0.4 ms.

Notice that an unfused optimizer update takes a fixed time independent of batch size: at batch size 128, the five products shrink to ~0.07 ms each (they turn bandwidth-bound), leaving the 0.4 ms update larger than all five products combined.

13.1.5 Summary#

A GPU operation is bounded by t≳max⁡(h, FLOPs/P, bytes/β)t \gtrsim \max(h,\, \textrm{FLOPs}/P,\, \textrm{bytes}/\beta), where hh is host dispatch overhead, PP is peak arithmetic throughput, and β\beta is memory bandwidth. Arithmetic intensity I=FLOPs/bytesI = \textrm{FLOPs}/\textrm{bytes} compares the last two: below the ridge point I∗=P/βI^* = P/\beta (~164 FLOP/byte for bf16 on the RTX 4090), an operation is bandwidth-bound; above it, compute-bound. For a linear layer, intensity scales with batch size from ~1 FLOP/byte during single-token decoding to hundreds of FLOP/byte during training. Accurate benchmarking requires device synchronization outside loops and warm-up runs (d2l.Benchmark), while d2l.kernel_times and d2l.show_profile verify paper predictions kernel by kernel.

13.1.6 Exercises#

  1. The smallest dimension. The exact expression for the intensity of the product XW\mathbf{X}\mathbf{W} in (13.1.1), before the B≪D,FB \ll D, F approximation, holds for all shapes. Let m=min⁡(B,D,F)m = \min(B, D, F).

    1. Show that the intensity lies between 2m/(3b)2m/(3b) and 2m/b2m/b. Conclude that in bf16, on a GPU with ridge point 164 FLOP/byte, every matrix product with a dimension below 164 is bandwidth-bound in the roofline model.
    2. Apply the bound to three bf16 products: the final layer of the MLP of Section 13.1.4 (4096→104096 \to 10 on a batch of 4,096); the attention scores QK⊤\mathbf{Q}\mathbf{K}^\top of one head with Q,K∈RT×64\mathbf{Q}, \mathbf{K} \in \mathbb{R}^{T \times 64}; and a 1×11 \times 1 convolution (Section 6.4.3) from 64 to 64 channels on a batch of 128 images of 32×3232 \times 32 pixels. Which dimensions would have to grow for each to reach the ridge point?
    3. A multi-head attention layer computes the scores of all its heads in one batched kernel. Does batching the heads change the intensity of the scores?
  2. [code] Batch size and the ridge. Consider the product XW\mathbf{X}\mathbf{W} with X∈RB×8192\mathbf{X} \in \mathbb{R}^{B \times 8192} and W∈R8192×8192\mathbf{W} \in \mathbb{R}^{8192 \times 8192} in bf16.

    1. Using the exact expression in (13.1.1), find the batch size at which the product reaches the ridge point of your GPU, and compare it with the small-BB approximation.
    2. Predict from (13.1.3) the time of the product for B=1B = 1 and B=64B = 64 concurrent decoding sequences, measure both with d2l.Benchmark, and determine up to what batch size serving more sequences costs almost no extra time per step.
  1. [code] Hidden barriers. Each of the following lines runs once per step of a training loop, where x and g are GPU tensors and c is a Python float: x[x > 0].sum(), print(x.shape), x.argmax(), if g.norm() > c: g *= c / g.norm(), and x * torch.tensor(0.5, device=x.device).
    1. Decide which lines make the host wait for the device, and justify each.
    2. Rewrite every synchronizing line so that it computes the same result without a host barrier.
    3. Check your answers with torch.cuda.set_sync_debug_mode('warn').
  1. Diagnosis from timings. Suppose d2l.Benchmark reports the following times per call for four bf16 operations on the RTX 4090 (P=165P = 165 TFLOP/s, β=1.008\beta = 1.008 TB/s): Operation A multiplies two 8192×81928192 \times 8192 matrices in 7.4 ms; Operation B applies row-wise softmax to an 8192×81928192 \times 8192 matrix in 0.30 ms (~5 FLOPs/element, one read and one write); Operation C multiplies two 256×256256 \times 256 matrices in 10 µs; Operation D multiplies two 1536×15361536 \times 1536 matrices in 0.10 ms.

    1. For each operation, compute its arithmetic intensity and the fractions of PP and β\beta it achieves. Classify each operation by its intensity relative to the ridge point and by the roof it approaches. Where do the two classifications disagree?
    2. For each operation close to neither roof, distinguish between host dispatch latency hh and insufficient thread-block tiles to occupy all streaming multiprocessors, and state what a profiler timeline would show for each.
  2. [code] A pipeline model of dispatch. ● Model one GPU call by three durations: host enqueue time hh, device execution time tdevt_\textrm{dev}, and final barrier latency σ\sigma.

    1. Show that RR calls enqueued back-to-back followed by one barrier take Rmax⁡(h,tdev)+min⁡(h,tdev)+σR \max(h, t_\textrm{dev}) + \min(h, t_\textrm{dev}) + \sigma. What does d2l.Benchmark report when tdev<ht_\textrm{dev} \lt h?
    2. For the loops of Section 13.1.2, derive the ratio of the per-step-read loop time to the single-read loop time in terms of hh, tdevt_\textrm{dev}, and σ\sigma.
    3. Run both loops for matrix sides 256,512,1024,2048,4096256, 512, 1024, 2048, 4096, estimate hh, σ\sigma, and tdevt_\textrm{dev}, and determine above what device time per step reading a scalar every step costs less than 10%.
  3. [code] Tiles and waves. ● A GPU consists of nSMn_\textrm{SM} streaming multiprocessors (nSM=128n_\textrm{SM} = 128 on the RTX 4090). Suppose a matrix-product kernel partitions an n×nn \times n output into 128×128128 \times 128 tiles, each SM computes one tile at a time at rate P/nSMP / n_\textrm{SM}, and tiles run in waves of at most nSMn_\textrm{SM}.

    1. Derive the fraction of peak throughput this model allows as a function of nn and nSMn_\textrm{SM}, and compare it with your sweep measurements in Section 13.1.3.3.
    2. Predict and measure the fraction of peak for n=2048,2176,2304,2432,2560n = 2048, 2176, 2304, 2432, 2560 (consecutive multiples of 128), and explain where the measurements depart from the simple wave model.
    3. Describe two ways a kernel can split an n=512n = 512 product into more work items so all SMs participate, and state the overhead each adds.

Discussions