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'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 \times 8192\) matrices runs within a few percent of the 165 TFLOP/s hardware peak, whereas a \(256 \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 \(h\) 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 collections
import re
import timeIn PyTorch, we also set the float32 matrix-multiplication precision to 'high' so that fp32 matrix products use the tf32 tensor cores:
JAX already runs fp32 matrix products on the tf32 tensor cores by default on NVIDIA GPUs.
# 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 \(\beta = 1.008 \times 10^{12}\) bytes/s (~1 TB/s). Its peak arithmetic rate \(P\) depends on the number format and unit: bf16 matrix products on the tensor cores reach \(P = 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 \(P\), on either side, as being at the roof.
Which budget runs out first depends on their ratio, the arithmetic intensity
\[ I \;=\; \frac{\textrm{FLOPs performed}}{\textrm{bytes moved}}. \]
Consider the matrix product \(\mathbf{X}\mathbf{W}\) with \(\mathbf{X} \in \mathbb{R}^{B \times D}\) and \(\mathbf{W} \in \mathbb{R}^{D \times F}\), a linear layer applied to a batch of \(B\) rows. It performs \(2BDF\) FLOPs (one multiply and one add per inner-product term) and at best reads \(\mathbf{X}\) and \(\mathbf{W}\) once and writes the output once (\(BD + DF + BF\) numbers). With \(b\) bytes per number, its intensity is
\[ \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)\) governs the intensity. When the batch size \(B\) is much smaller than the layer dimensions, intensity grows linearly with \(B\) because every weight fetched from memory is reused across all \(B\) rows.
For a 1B-parameter GPT with width \(D = F = 2048\) in bf16 (\(b = 2\)), a training minibatch of 8 sequences of 1,024 tokens has \(B = 8192\) rows, giving \(I \approx 910\) FLOP/byte by Equation 13.1.1 (limited by the width \(D\)). During single-sequence autoregressive generation, \(B = 1\) and \(I \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 \(y_i = x_i + 1\), which performs 1 FLOP per \(2b\) bytes moved (\(I = 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 \(P\) and no faster than memory supplies data at rate \(I\beta\):
\[ \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/\beta\) (Figure 13.1.1). Below \(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^*\) 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.
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 \approx 164\) FLOP/byte; for tf32 products (\(P = 82.6\) TFLOP/s), it is \(I^* \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 = n\)), \(I = n / 3\), so the roofline predicts that every product with \(n \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 \(h\) to issue a step and the GPU takes \(t_\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\):
\[ 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 \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
x = jnp.ones((1024, 1024))
step = jax.jit(lambda s, x: s + (x @ x).sum())
s = step(jnp.zeros(()), x)
float(s) # Warm up: compile the step
t0 = time.perf_counter()
for _ in range(1000):
s = step(s, x)
total = float(s) # Reads the value: a barrier every step
read_every = time.perf_counter() - t0
t0 = time.perf_counter()
for _ in range(1000):
s = step(s, x) # 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.283 s read once: 0.083 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×.
Without per-step reads, each jitted call takes ~0.1 ms of host dispatch time. Reading float(s) every step adds the device-to-host round-trip \(\sigma\) on every iteration, making the loop more than three times slower.
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 \times 4096\) bf16 product has intensity \(I \approx 1365\) FLOP/byte, well above the ridge, so the roofline predicts \(2 \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
matmul = jax.jit(jnp.dot)
a = jax.random.normal(d2l.get_key(), (4096, 4096), dtype=jnp.bfloat16)
d2l.Benchmark(lambda: matmul(a, a), desc='4096 x 4096 product')4096 x 4096 product: 0.89 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 \(B\) rows by a \(d \times d\) bf16 weight matrix with \(d = 16{,}384\) (512 MiB). By Equation 13.1.1, its intensity is approximately \(B\), crossing the ridge near \(B = 164\). Below the ridge, every call must stream 512 MiB of weights (~0.53 ms at 1.008 TB/s) regardless of \(B\); above the ridge, the \(2Bd^2\) FLOPs govern the time, scaling linearly with \(B\) (0.83 ms at \(B = 256\), 3.32 ms at \(B = 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
peak_tflops = 165.2 # RTX 4090: dense bf16 on the tensor cores
bandwidth_tbs = 1.008 # RTX 4090: GDDR6X memory
print(f'{jax.devices()[0].device_kind}: ridge point '
f'{peak_tflops / bandwidth_tbs:.0f} FLOP/byte')
d, b = 16384, 2 # Width and bytes per bf16 number
W = jax.random.normal(d2l.get_key(), (d, d), dtype=jnp.bfloat16) # 0.54 GB
for B in (1, 4, 16, 64, 128, 256, 1024):
X = jax.random.normal(d2l.get_key(), (B, d), dtype=jnp.bfloat16)
t = d2l.Benchmark(lambda: matmul(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.60 ms, 0.9 TFLOP/s
B = 4: bound 0.53 ms (memory ), measured 0.59 ms, 3.6 TFLOP/s
B = 16: bound 0.53 ms (memory ), measured 0.59 ms, 14.5 TFLOP/s
B = 64: bound 0.54 ms (memory ), measured 0.62 ms, 55.6 TFLOP/s
B = 128: bound 0.54 ms (memory ), measured 0.60 ms, 114.8 TFLOP/s
B = 256: bound 0.83 ms (compute), measured 0.82 ms, 166.9 TFLOP/s
B = 1024: bound 3.33 ms (compute), measured 3.27 ms, 168.0 TFLOP/s
One weight matrix reaches both roofs: from \(B = 1\) to \(B = 128\) the time stays flat near 0.6 ms despite \(128\times\) more arithmetic, and from \(B = 256\) upward it grows linearly with \(B\) near the compute roof. Serving 1,024 tokens at once performs \(1{,}024\times\) the arithmetic of serving one token in less than \(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 \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
x = jax.random.normal(d2l.get_key(), (8192, 8192)) # 256 MiB in fp32
for desc, f in [('add', lambda x: x + 1), ('mul', lambda x: x * 1.5),
('sin', jnp.sin), ('sigmoid', jax.nn.sigmoid)]:
f = jax.jit(f)
print(d2l.Benchmark(lambda: f(x), desc=desc))add: 0.62 ms/call
mul: 0.60 ms/call
sin: 0.60 ms/call
sigmoid: 0.59 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 outer product with x) each read two tensors and write one (6 tensors), moving 18 tensors of 256 MiB in total—\(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 kernels1 op: 0.59 ms/call
chain: 5.25 ms/call
def gelu_ish(x):
"""The tanh approximation of GELU with rounded constants: a chain of
eight elementwise operations."""
return 0.5 * x * (1 + jnp.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')) # No jit: 8 kernels1 op: 0.61 ms/call
chain: 5.30 ms/call
As predicted, the unfused chain takes \(8\times\) to \(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 / 3\) crosses 164 near \(n = 500\)? Let us sweep \(n\) 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)sizes = [256, 512, 1024, 2048, 4096, 8192]
times = []
for n in sizes:
a = jax.random.normal(d2l.get_key(), (n, n), dtype=jnp.bfloat16)
times.append(d2l.Benchmark(lambda: matmul(a, a), repeats=100).time)We plot the achieved TFLOP/s against the arithmetic intensity \(n / 3\) alongside the roofline bound Equation 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'))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 \(n\) 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
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: 119.1 us per call, 0.3 TFLOP/s
n = 512: 77.9 us per call, 3.4 TFLOP/s
n = 1024: 84.2 us per call, 25.5 TFLOP/s
n = 2048: 161.5 us per call, 106.4 TFLOP/s
n = 4096: 833.6 us per call, 164.9 TFLOP/s
n = 8192: 6404.3 us per call, 171.7 TFLOP/s
At \(n = 4096\) and \(8192\) 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 \(n^3\). From \(n = 256\) to \(1024\) the work grows \(64\times\), yet the time per call changes by less than \(2\times\).
To see whether that constant time is spent on the host or the device, we time a \(256 \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
add_one = jax.jit(lambda x: x + 1)
a = jax.random.normal(d2l.get_key(), (256, 256), dtype=jnp.bfloat16)
for desc, f in [('256 x 256 product', lambda: matmul(a, a)),
('x + 1 on 256 x 256', lambda: add_one(a))]:
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 : 58.7 us per call, device busy 4.2 us
x + 1 on 256 x 256: 61.2 us per call, device busy 1.1 us
In both cases the GPU works for only a few microseconds; the rest is the host dispatch time \(h\) (Python, framework, and driver). For a \(256 \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, 2n^3/P)\). For small \(n\), 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 \approx (hP/2)^{1/3}\).
With \(h \approx 13\) µs, the knee lies near \(n = 1{,}000\).
Single-op dispatch takes \(h \approx 50\text{--}100\) µs (paid once for an entire jitted training step), so the knee lies near \(n = 1{,}600\text{--}2{,}000\).
Combining all three floors gives our fundamental time bound for a single dispatched operation:
\[ t \;\gtrsim\; \max\left(h,\; \frac{\textrm{FLOPs}}{P},\; \frac{\textrm{bytes}}{\beta}\right). \tag{13.1.3}\]
With \(h = 10\) µs, any operation with fewer than \(hP \approx 1.6 \times 10^9\) FLOPs and fewer than \(h\beta \approx 10\) MB moved takes the time of its launch alone. Moreover, the knee \(n \approx (hP/2)^{1/3}\) grows with \(P\): 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.
| regime | symptom | standard fix |
|---|---|---|
| compute-bound | device busy; intensity above the ridge; time grows with the FLOPs | less arithmetic; a format with faster tensor cores; more devices |
| bandwidth-bound | device busy; intensity below the ridge; time grows with the bytes moved | a 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-bound | device idle between kernels; time per call independent of size | a 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 \to 4096 \to 4096 \to 10\)) on a minibatch of 1,024 examples in fp32 with tf32 matrix products (\(P = 82.6\) TFLOP/s).
13.1.4.1 Predicting the Step
Each of the two \(4096 \times 4096\) layers performs \(2 \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 \approx 340\) FLOP/byte (above the tf32 ridge of 82), each product takes \(3.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 \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 \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).timedef mlp(params, X):
for W, b in params[:-1]:
X = jax.nn.relu(X @ W + b)
W, b = params[-1]
return X @ W + b
@jax.jit
def step(params, X):
grads = jax.grad(lambda p: mlp(p, X).mean())(params)
return jax.tree.map(lambda p, g: p - 0.01 * g, params, grads)
widths = [4096, 4096, 4096, 10]
params = [(jax.random.normal(d2l.get_key(), (m, n)) / m**0.5, jnp.zeros(n))
for m, n in zip(widths[:-1], widths[1:])]
X = jax.random.normal(d2l.get_key(), (1024, 4096))
wall = d2l.Benchmark(lambda: step(params, X)).timekernel_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}
import glob
import tempfile
def kernel_times(f, steps=10):
"""Device milliseconds per call of f, for every kernel that f runs."""
kernels = collections.Counter()
with tempfile.TemporaryDirectory() as trace_dir: # Removed afterwards
with jax.profiler.trace(trace_dir):
for _ in range(steps):
out = f()
jax.block_until_ready(out)
xspace = glob.glob(f'{trace_dir}/**/*.xplane.pb', recursive=True)[0]
gpu = jax.profiler.ProfileData.from_file(
xspace).find_plane_with_name('/device:GPU:0')
for line in gpu.lines:
if line.name.startswith('Stream'): # One line per CUDA stream
for e in line.events:
kernels[e.name] += e.duration_ns / 1e6 / steps
return kernelsThe 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.
jax.profiler.trace writes the trace into its trace directory.
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]}')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
show_profile(kernel_times(lambda: step(params, X)), 1000 * wall)wall clock 2.41 ms per step, device busy 2.37 ms (99%), matrix products 97%
0.51 ms 22% gemm_fusion_dot_1
0.50 ms 21% gemm_fusion_dot
0.44 ms 19% gemm_fusion_dot_general_8
0.42 ms 18% Kernel2<cutlass_80_tensorop_s1688gemm_128x256_16x3_n
0.42 ms 18% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_16x5_t
0.06 ms 3% input_reduce_select_fusion_1
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 eightfold to ~0.07 ms each, leaving the 0.4 ms update larger than all five products combined.
XLA fuses the SGD update directly into the weight-gradient products (gemm_fusion_dot), subtracting the scaled gradient before writing the updated weight so the gradient never makes a separate round trip to memory.
13.1.5 Summary
A GPU operation is bounded by \(t \gtrsim \max(h,\, \textrm{FLOPs}/P,\, \textrm{bytes}/\beta)\), where \(h\) is host dispatch overhead, \(P\) is peak arithmetic throughput, and \(\beta\) is memory bandwidth. Arithmetic intensity \(I = \textrm{FLOPs}/\textrm{bytes}\) compares the last two: below the ridge point \(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
- The smallest dimension. The exact expression for the intensity of the product \(\mathbf{X}\mathbf{W}\) in Equation 13.1.1, before the \(B \ll D, F\) approximation, holds for all shapes. Let \(m = \min(B, D, F)\).
- Show that the intensity lies between \(2m/(3b)\) and \(2m/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.
- Apply the bound to three bf16 products: the final layer of the MLP of Section 13.1.4 (\(4096 \to 10\) on a batch of 4,096); the attention scores \(\mathbf{Q}\mathbf{K}^\top\) of one head with \(\mathbf{Q}, \mathbf{K} \in \mathbb{R}^{T \times 64}\); and a \(1 \times 1\) convolution (Section 6.4.3) from 64 to 64 channels on a batch of 128 images of \(32 \times 32\) pixels. Which dimensions would have to grow for each to reach the ridge point?
- 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?
- [code] Batch size and the ridge. Consider the product \(\mathbf{X}\mathbf{W}\) with \(\mathbf{X} \in \mathbb{R}^{B \times 8192}\) and \(\mathbf{W} \in \mathbb{R}^{8192 \times 8192}\) in bf16.
- Using the exact expression in Equation 13.1.1, find the batch size at which the product reaches the ridge point of your GPU, and compare it with the small-\(B\) approximation.
- Predict from Equation 13.1.3 the time of the product for \(B = 1\) and \(B = 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.
- [code] Hidden barriers. Each of the following lines runs once per step of a training loop, where
xandgare GPU tensors andcis a Python float:x[x > 0].sum(),print(x.shape),x.argmax(),if g.norm() > c: g *= c / g.norm(), andx * torch.tensor(0.5, device=x.device).- Decide which lines make the host wait for the device, and justify each.
- Rewrite every synchronizing line so that it computes the same result without a host barrier.
- Check your answers with
torch.cuda.set_sync_debug_mode('warn').
- Diagnosis from timings. Suppose
d2l.Benchmarkreports the following times per call for four bf16 operations on the RTX 4090 (\(P = 165\) TFLOP/s, \(\beta = 1.008\) TB/s): Operation A multiplies two \(8192 \times 8192\) matrices in 7.4 ms; Operation B applies row-wise softmax to an \(8192 \times 8192\) matrix in 0.30 ms (~5 FLOPs/element, one read and one write); Operation C multiplies two \(256 \times 256\) matrices in 10 µs; Operation D multiplies two \(1536 \times 1536\) matrices in 0.10 ms.- For each operation, compute its arithmetic intensity and the fractions of \(P\) 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?
- For each operation close to neither roof, distinguish between host dispatch latency \(h\) and insufficient thread-block tiles to occupy all streaming multiprocessors, and state what a profiler timeline would show for each.
- [code] A pipeline model of dispatch. ● Model one GPU call by three durations: host enqueue time \(h\), device execution time \(t_\textrm{dev}\), and final barrier latency \(\sigma\).
- Show that \(R\) calls enqueued back-to-back followed by one barrier take \(R \max(h, t_\textrm{dev}) + \min(h, t_\textrm{dev}) + \sigma\). What does
d2l.Benchmarkreport when \(t_\textrm{dev} < h\)? - 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 \(h\), \(t_\textrm{dev}\), and \(\sigma\).
- Run both loops for matrix sides \(256, 512, 1024, 2048, 4096\), estimate \(h\), \(\sigma\), and \(t_\textrm{dev}\), and determine above what device time per step reading a scalar every step costs less than 10%.
- Show that \(R\) calls enqueued back-to-back followed by one barrier take \(R \max(h, t_\textrm{dev}) + \min(h, t_\textrm{dev}) + \sigma\). What does
- [code] Tiles and waves. ● A GPU consists of \(n_\textrm{SM}\) streaming multiprocessors (\(n_\textrm{SM} = 128\) on the RTX 4090). Suppose a matrix-product kernel partitions an \(n \times n\) output into \(128 \times 128\) tiles, each SM computes one tile at a time at rate \(P / n_\textrm{SM}\), and tiles run in waves of at most \(n_\textrm{SM}\).
- Derive the fraction of peak throughput this model allows as a function of \(n\) and \(n_\textrm{SM}\), and compare it with your sweep measurements in Section 13.1.3.3.
- Predict and measure the fraction of peak for \(n = 2048, 2176, 2304, 2432, 2560\) (consecutive multiples of 128), and explain where the measurements depart from the simple wave model.
- Describe two ways a kernel can split an \(n = 512\) product into more work items so all SMs participate, and state the overhead each adds.
- The smallest dimension. The exact expression for the intensity of the product \(\mathbf{X}\mathbf{W}\) in Equation 13.1.1, before the \(B \ll D, F\) approximation, holds for all shapes. Let \(m = \min(B, D, F)\).
- Show that the intensity lies between \(2m/(3b)\) and \(2m/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.
- Apply the bound to three bf16 products: the final layer of the MLP of Section 13.1.4 (\(4096 \to 10\) on a batch of 4,096); the attention scores \(\mathbf{Q}\mathbf{K}^\top\) of one head with \(\mathbf{Q}, \mathbf{K} \in \mathbb{R}^{T \times 64}\); and a \(1 \times 1\) convolution (Section 6.4.3) from 64 to 64 channels on a batch of 128 images of \(32 \times 32\) pixels. Which dimensions would have to grow for each to reach the ridge point?
- 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?
- [code] Batch size and the ridge. Consider the product \(\mathbf{X}\mathbf{W}\) with \(\mathbf{X} \in \mathbb{R}^{B \times 8192}\) and \(\mathbf{W} \in \mathbb{R}^{8192 \times 8192}\) in bf16.
- Using the exact expression in Equation 13.1.1, find the batch size at which the product reaches the ridge point of your GPU, and compare it with the small-\(B\) approximation.
- Predict from Equation 13.1.3 the time of the product for \(B = 1\) and \(B = 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.
- [code] Hidden barriers. Each of the following lines runs once per step of a training loop, where
xandgare GPU arrays andcis a Python float:x[x > 0].sum(),print(x.shape),jnp.argmax(x),if jnp.linalg.norm(g) > c: g = g * c / jnp.linalg.norm(g), andx * jnp.asarray(0.5).- Decide which lines make the host wait for the device, and justify each.
- Rewrite every synchronizing line so that it computes the same result without a host barrier.
- Check your answers inside
with jax.transfer_guard_device_to_host('disallow'):.
- Diagnosis from timings. Suppose
d2l.Benchmarkreports the following times per call for four bf16 operations on the RTX 4090 (\(P = 165\) TFLOP/s, \(\beta = 1.008\) TB/s): Operation A multiplies two \(8192 \times 8192\) matrices in 7.4 ms; Operation B applies row-wise softmax to an \(8192 \times 8192\) matrix in 0.30 ms (~5 FLOPs/element, one read and one write); Operation C multiplies two \(256 \times 256\) matrices in 10 µs; Operation D multiplies two \(1536 \times 1536\) matrices in 0.10 ms.- For each operation, compute its arithmetic intensity and the fractions of \(P\) 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?
- For each operation close to neither roof, distinguish between host dispatch latency \(h\) and insufficient thread-block tiles to occupy all streaming multiprocessors, and state what a profiler timeline would show for each.
- [code] A pipeline model of dispatch. ● Model one GPU call by three durations: host enqueue time \(h\), device execution time \(t_\textrm{dev}\), and final barrier latency \(\sigma\).
- Show that \(R\) calls enqueued back-to-back followed by one barrier take \(R \max(h, t_\textrm{dev}) + \min(h, t_\textrm{dev}) + \sigma\). What does
d2l.Benchmarkreport when \(t_\textrm{dev} < h\)? - 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 \(h\), \(t_\textrm{dev}\), and \(\sigma\).
- Run both loops for matrix sides \(256, 512, 1024, 2048, 4096\), estimate \(h\), \(\sigma\), and \(t_\textrm{dev}\), and determine above what device time per step reading a scalar every step costs less than 10%.
- Show that \(R\) calls enqueued back-to-back followed by one barrier take \(R \max(h, t_\textrm{dev}) + \min(h, t_\textrm{dev}) + \sigma\). What does
- [code] Tiles and waves. ● A GPU consists of \(n_\textrm{SM}\) streaming multiprocessors (\(n_\textrm{SM} = 128\) on the RTX 4090). Suppose a matrix-product kernel partitions an \(n \times n\) output into \(128 \times 128\) tiles, each SM computes one tile at a time at rate \(P / n_\textrm{SM}\), and tiles run in waves of at most \(n_\textrm{SM}\).
- Derive the fraction of peak throughput this model allows as a function of \(n\) and \(n_\textrm{SM}\), and compare it with your sweep measurements in Section 13.1.3.3.
- Predict and measure the fraction of peak for \(n = 2048, 2176, 2304, 2432, 2560\) (consecutive multiples of 128), and explain where the measurements depart from the simple wave model.
- Describe two ways a kernel can split an \(n = 512\) product into more work items so all SMs participate, and state the overhead each adds.