Matrix Multiplication and GPU Execution
What a matrix multiplication costs, why one token uses about two per cent of a GPU, and how to time a GPU without fooling yourself.
Moving the Building Our First Inference Engine engine from one CPU thread to a GPU made it 14.2 times faster. Thirty-two greedy GPT-2 tokens took a median of 6.41 seconds on the CPU and 0.453 seconds on the GPU, over five runs each, and the generated token ids agreed.
That sounds like a lot until you compare the hardware. On this machine, a large fp32 matrix product reached about 7.4 TFLOP/s on the GPU in the best observed runs, while one CPU thread reached about 53 GFLOP/s: a ratio of roughly 140. So why did the engine only get 14 times faster?
Two measurements in this chapter are candidate explanations, though neither was taken on the engine’s own shapes:
- One token barely uses the GPU’s arithmetic. The output projection for a single token ran at about 151 GFLOP/s, around 2% of the large-matrix rate. Its weight matrix is huge relative to the arithmetic done with it, so the time plausibly goes on reading weights, not multiplying. (This is the cached, one-row case. The uncached engine processes about 17–48 positions per step, so this bullet does not describe it directly.)
- Small operations cost a fixed toll. A tiny GPU operation took about 35 microseconds per Python/PyTorch call, even though its arithmetic was negligible.
So there are at least two regimes besides raw arithmetic: moving bytes, and issuing many small operations. (These measurements show both regimes exist; they do not, on their own, divide the engine’s total latency between them.)
This chapter builds a cost model for matrix multiplication, tests it against the shapes a transformer actually uses, and shows how GPU timing can be wrong by orders of magnitude. Throughout, keep four kinds of number apart: measured elapsed time, throughput derived from it, estimated bytes moved, and hypotheses about the bottleneck.
Where this sits
The Transformer as a Computation counted the forward pass’s matrix multiplications; Autoregressive Generation showed the cost of reprocessing the whole prefix; Building Our First Inference Engine measured a baseline engine. Operation counts alone cannot predict latency. This chapter adds what they leave out: operand size, memory locality, data movement, parallelism and dispatch overhead. Those explain why the best way to run a prompt-sized multiplication is not the best way to run one decode token.
The Inference Lab gains a GPU measurement harness: timing with CUDA events and explicit synchronisation, a repeated-call mode, a warm-up workload, probes for arithmetic and copy throughput, and a roofline calculation.
The machine. An NVIDIA GeForce RTX 2060 with about 12 GiB of memory (compute capability 7.5), under Windows 11 with the WDDM display driver, also driving the desktop and a browser. Software: PyTorch 2.6.0+cu124, CUDA runtime 12.4, NVIDIA driver 591.44. This is a shared consumer GPU and one software stack, not a universal baseline; the GPU-computing and serving volumes can reuse the method but must measure their own hardware.
What a matrix multiplication costs
Counting arithmetic. Multiplying an \(M \times K\) matrix by a \(K \times N\) matrix produces \(MN\) outputs, each a dot product of length \(K\). Counting a multiply-add as two floating-point operations gives the standard approximation:
| Layer | \(K\) | \(N\) | Weight elements |
|---|---|---|---|
| Query, key, value projection | 768 | 2,304 | 1.77 M |
| Attention output projection | 768 | 768 | 0.59 M |
| Feed-forward up | 768 | 3,072 | 2.36 M |
| Feed-forward down | 3,072 | 768 | 2.36 M |
| Output projection (logits) | 768 | 50,257 | 38.6 M |
(This excludes biases, the \(QK^\top\) and attention-value products, activations and layer normalisation, which also take time.)
The key asymmetry. The size of a weight matrix does not depend on \(M\), but the arithmetic does. A 500-position prefill multiplies a \(500 \times K\) matrix by the weights. A cached decode step multiplies a \(1 \times K\) row by the same weights: the same weights to read, one five-hundredth of the arithmetic to do with them.
A warning before going further. The uncached engine of Chapters 5–7 does not run decode at \(M=1\). It reprocesses the whole growing prefix, so its \(M\) grows with context. The \(M=1\) analysis below applies to cached decode, not to that engine.
Arithmetic intensity
Arithmetic intensity is arithmetic per byte moved, in FLOPs per byte. A simple, optimistic traffic model assumes each input is read once and the output written once. With \(b\) bytes per element:
The roofline
Let \(P\) be an arithmetic ceiling in FLOP/s and \(B\) a bandwidth ceiling in bytes/s, both for the same device, precision and memory level. A kernel with intensity \(I\) cannot run faster than:
The roofline is an upper bound, conditional on the ceilings and the traffic model. A kernel below the roof might be limited by occupancy, instruction dependencies, launch overhead, poor tiling or host submission, or the byte estimate might simply be wrong. So treat it as a diagnostic question: which measurement would tell these explanations apart?
Timing a GPU without fooling yourself
The trap. CUDA work is asynchronous. A Python call such as a @ b usually just queues the work and returns before the GPU has finished. Time only the call, and you measure how long it took to queue.
The demonstration. A 4,096 × 4,096 fp32 product (about 137.4 billion FLOPs), timed three ways:
| Method | Median time | Implied rate |
|---|---|---|
| Time the call only | 0.18 ms | 757,000 GFLOP/s |
Time until cuda.synchronize() returns |
23.3 ms | 5,909 GFLOP/s |
| CUDA events around the call | 23.6 ms | 5,816 GFLOP/s |
The first row implies about 757 TFLOP/s, a hundred times beyond what this card can do in fp32. That is not a fast kernel; it is a measurement-boundary error. The other two methods agree to within a few per cent: the product takes about 23–24 ms.
(The book’s first GPU benchmark did synchronise, but it reported the fastest of only five runs of a 512³ product. That sampling rule was too weak to support a stable comparison.)
CUDA events timestamp progress on the GPU’s own stream and are usually the clearest way to measure a device-side interval. They still need a defined start and end, a warm-up, and a final synchronisation before the time is read. And if the CPU cannot submit small operations fast enough, an event-bracketed sequence can include idle gaps on the GPU. So the Lab reports per-call queue throughput separately from request latency and from CPU enqueue time.
Four conditions for a trustworthy number
- Define the boundary. Dispatch time, event-bracketed GPU work, a model call including host-to-device copies, and an end-to-end request are four different things. Never report them under one label.
- Synchronise or use CUDA events. A timer that stops before the GPU finishes does not measure the operation.
- Warm up, and report the state. Kernel loading, memory allocation, algorithm selection, clocks, power and temperature can all change over the first calls. A three-second warm-up workload reduced variation in this session but did not lock the clocks.
- Repeat, and report the spread. Record device, driver, runtime and framework versions, precision, shapes, thread count, warm-up, timing method, and the samples or quantiles. For tiny operations, measure single-call latency and repeated-call throughput separately; they answer different questions.
This GPU was also driving a display, and it showed. Very short event timings fell into two clusters for the same operation, about 4 microseconds and about 60–100 microseconds, and clocks varied under load. Repeated-call timing kept the queue busy and reduced some of the spread, but it did not remove contention. Separate process runs differed by up to about 40% for some sizes. Facts like these belong next to the benchmark, not in a footnote that disappears when someone copies one number.
What this machine can do
To draw a roofline we need ceilings. These are observed rates from selected microbenchmarks, not hardware specifications:
| Probe | Best or representative observed rate |
|---|---|
| Large device-to-device copy, counted as read plus write | 278 GB/s median (280 GB/s best in the dedicated probe) |
| Thin fp32 output projection, bytes from the one-read/one-write model divided by time | 303 GB/s effective modelled traffic rate |
| Large fp32 square matmul, across the recorded size sweep | approximately 6.4–7.4 TFLOP/s |
| Large fp16 square matmul, across the recorded size sweep | approximately 29.7–31.4 TFLOP/s |
The two GB/s figures mean different things. For the copy, the bytes moved are known at the API level. For the thin projection, the bytes are the optimistic estimate from the traffic model; no hardware counter was read. So “303 GB/s” does not prove that 303 GB/s crossed the memory controller.
fp16 matrix products ran about four times faster than fp32. That fits the RTX 2060 having faster reduced-precision matrix hardware, though the experiment did not inspect which instructions each kernel used.
A worked roofline. Using 303 GB/s and the best fp32 and fp16 rates (about 7.4 and 31.4 TFLOP/s) gives ridge points near 24.6 and 103.7 FLOP/byte. One caution: the 303 GB/s figure was partly derived from the same thin projection we are about to analyse, so agreement with it is not independent confirmation. Exercise 3 rebuilds the roofline with the 278 GB/s copy rate as a check.
Matrix size and the cost of a call
The question. How does throughput change with matrix size, on each device?
Square products from 32 to 8,192, medians of three separate runs where available. The CPU uses one PyTorch thread. These are throughputs derived from time, so a fast call with very little arithmetic still shows a tiny GFLOP/s.
| \(n\) | CPU, 1 thread (GFLOP/s) | GPU fp32 | GPU fp16 |
|---|---|---|---|
| 32 | 10 | 2 | 2 |
| 64 | 34 | 14 | 12 |
| 128 | 45 | 113 | 96 |
| 256 | 53 | 895 | 787 |
| 512 | 53 | 6,285 | 6,419 |
| 1,024 | 54 | 6,317 | 25,461 |
| 2,048 | 54 | 4,986 | 22,828 |
| 4,096 | – | 7,217 | 29,672 |
| 8,192 | – | 6,445 | 31,073 |
The table falls into three bands.
Smallest sizes: the CPU wins. At \(n=32\), a call took roughly 6.6 microseconds on the CPU and 38 on the GPU path. The crossover for square products here lies between 64 and 128. That is a property of this shape, software stack and timing method, not a universal threshold.
Small to medium: a fixed toll dominates. GPU time per call stayed around 36–43 microseconds from \(n=32\) all the way to \(n=512\), while the arithmetic grew enormously. In a separate loop of 2,000 Python calls:
- an 8×8 GPU matmul took a median 35.4 microseconds per call, from enqueue to completion;
- the same on one CPU thread took 4.2 microseconds;
- a 1,024-element GPU add took 19.6 microseconds.
These are measurements of the host submission path (Python, PyTorch, driver) under sustained queuing, not a universal “35-microsecond kernel launch”. Enqueue and completion averages were similar, meaning the queue was kept busy; that does not show the GPU did no work.
Large: arithmetic dominates. fp32 products from about 512 upwards often reached 6–7 TFLOP/s; fp16 needed larger sizes to reach 25–31 TFLOP/s. Calling all of these “compute-bound” would go further than the data: occupancy, dispatch and clock changes can still matter, and a roofline classification needs a sound traffic measurement.
The 2,048 row shows why medians alone are not enough. Across its three runs, fp32 ranged from 3,791 to 5,987 GFLOP/s and fp16 from 14,614 to 23,227. Clock or power changes on a shared display GPU are a plausible cause, but were not isolated. To diagnose a performance regression, you need the individual runs.
Transformer shapes
Square matrices are convenient for calibration, but GPT-2 multiplies \(M \times 768\) activations by \(768 \times N\) weights, where \(M\) is the number of positions in the current call. So I measured two real projections, MLP-up and the output projection, with \(M\) from 1 to 2,048.
The output projection in fp32
The output projection has \(K=768\) and \(N=50{,}257\): 38,597,376 weights, about 154.4 MB in fp32 and 77.2 MB in fp16 (decimal units).
| Tokens \(M\) | fp32 time (µs) | Share of fp32 peak | fp32 GB/s | Intensity (FLOP/B) |
|---|---|---|---|---|
| 1 | 510 | 2.0% | 303 | 0.5 |
| 8 | 595 | 13.9% | 262 | 4.0 |
| 32 | 592 | 56.0% | 272 | 15.4 |
| 64 | 781 | 85.0% | 214 | 29.5 |
| 128 | 1,468 | 90.4% | 123 | 54.7 |
| 1,024 | 11,859 | 89.5% | 31 | 217.5 |
(The “GB/s” column divides the idealised operand and output bytes by elapsed time; it is not a hardware bandwidth reading.)
What it shows. From 1 to 32 tokens, the arithmetic grew 32-fold but time barely moved, from about 510 to 592 microseconds. At one token the projection achieved about 151 GFLOP/s, 2% of the card’s best fp32 rate. That is what you would expect if the cost is mostly making a 154 MB weight matrix available, whatever the number of tokens.
Does the roofline predict where that changes? With the ridge at 24.6 FLOP/byte and \(I\approx M/2\), the model predicts a transition near \(M\approx49\). Measured time is nearly flat through 32 positions and rises between 64 and 128: consistent with the model. But the bandwidth figure was partly derived from this same projection, so the agreement is not independent validation. Separating DRAM traffic, cache behaviour, kernel choice and host overhead would need a profiler with memory counters, or experiments that vary weight size while holding FLOPs steady.
The output projection in fp16
| Tokens \(M\) | fp16 time (µs) | Share of fp16 peak | GB/s |
|---|---|---|---|
| 1 | 271 | 0.9% | 285 |
| 8 | 558 | 3.5% | 140 |
| 32 | 394 | 20.0% | 204 |
| 128 | 593 | 53.1% | 152 |
| 1,024 | 4,436 | 56.7% | 41 |
At one token, fp16 took 271 microseconds against 510 for fp32, nearly a 1.9× reduction. Halving the weight bytes would predict something like that if the operation is bandwidth-sensitive. But switching to fp16 also changes the kernel and arithmetic path, so this is not a clean two-bytes-versus-four experiment.
Two oddities. At \(M=8\), fp16 was slower than at \(M=16\) in all three runs (about 554–605 microseconds against 344–357). A change of kernel algorithm is a plausible explanation, but the code did not inspect kernel choice. And at \(M=1{,}024\), fp16 reached about 57% of its best square-matmul rate while fp32 reached about 90% of its rate. Different shapes and hardware paths use the hardware differently; a single peak number is not something every shape is entitled to.
The MLP-up projection
The MLP-up weights (\(N=3{,}072\)) are about 9.4 MB in fp32. At \(M=1\) to 8, fp32 time was roughly 36–43 microseconds, which overlaps the small-operation toll measured earlier. Reading 9.4 MB at 278 GB/s would take about 34 microseconds, if every weight crossed the memory interface once. The two estimates overlap, so this experiment cannot split the time between dispatch, memory traffic and arithmetic. Measuring traffic directly, or using a lower-overhead launch path, would.
Layout and alignment
Layout. On 2,048-square products, multiplying by transposed views changed fp32 and fp16 times by less than about 10% either way. Explicitly making a contiguous transpose inside the timed call was about 19% slower than the fp16 contiguous baseline. (The strided-slice case used half the reduction dimension, so it did half the arithmetic; the test did not check whether PyTorch copied internally.) The practical advice: check both strides and hidden copies, and compare times only after normalising for the work actually done.
Alignment. Reduced-precision matrix hardware works in tiles with shape constraints, so dimensions can matter. Here is an fp16 sweep around 4,096:
| \(n\) | Multiple of 8 | GFLOP/s |
|---|---|---|
| 4,088 | yes | 28,196 |
| 4,090 | no | 27,919 |
| 4,092 | no | 27,256 |
| 4,095 | no | 23,108 |
| 4,096 | yes | 29,427 |
| 4,097 | no | 21,185 |
| 4,100 | no | 25,589 |
Changing the size by one, from 4,096 to 4,097, cost about 28% of throughput. But the pattern is not a simple “multiple of 8 or not”: 4,090 and 4,092 did much better than 4,095 or 4,100. A dimension that is not a multiple of eight does not necessarily force a slow path; the library may pad, choose a different tile, or handle the edge directly. (This was one run of 15 event-timed calls per size, so it cannot separate alignment from algorithm choice or clock state.)
The lesson is to benchmark the actual dimensions you will use, and document any padding. GPT-2’s 50,257-entry vocabulary is not a multiple of eight. Padding the output projection might speed it up, but the padded logits must then be masked out, or the model’s output distribution changes.
What reduced precision does to the answer
fp16 is four times faster on this card, but speed is worthless if the numerical error breaks the model’s tolerance. So how much error does fp16 introduce?
The test. Multiply random standard-normal matrices of size \(1024\times K\) and \(K\times1024\) in fp32 and fp16, and compare each with a float64 reference using relative Frobenius-norm error. A control rounds the inputs to fp16 and back, then multiplies in float64, to separate the error from storing inputs in fp16 from the error of computing in fp16.
| \(K\) | fp32 relative error | fp16 relative error | fp16-rounded inputs, float64 product |
|---|---|---|---|
| 64 | \(1.5 \times 10^{-7}\) | \(3.6 \times 10^{-4}\) | \(2.9 \times 10^{-4}\) |
| 512 | \(4.1 \times 10^{-7}\) | \(3.6 \times 10^{-4}\) | \(2.9 \times 10^{-4}\) |
| 4,096 | \(5.7 \times 10^{-7}\) | \(3.6 \times 10^{-4}\) | \(2.9 \times 10^{-4}\) |
fp32 error grows slightly with \(K\); fp16 error stays near \(3.6\times10^{-4}\). And rounding the inputs alone already accounts for about \(2.9\times10^{-4}\) of that. So in this test, storing operands in fp16 caused most of the error, not the multiplication itself.
That does not tell us how the kernel accumulates internally; establishing fp32 accumulation would need documentation or targeted inspection. And a Frobenius norm can hide a large error in one element. Quantization and Numerical Precision tests maximum and percentile errors, logit changes and generated-token agreement on real activations, including the large outliers seen in The Transformer as a Computation, before drawing conclusions about model quality.
From one product to a model
Now we put a whole model on the GPU: the library’s GPT-2, including embeddings, attention, MLP and normalisation, in one forward call.
One measurement boundary to note first. The timed function is gpu(ids.cuda()), so copying the token ids from CPU to GPU happens inside the timed interval. These are not pure GPU-kernel latencies (exercise 4 moves the copy out). Ranges are over two runs; the CPU uses one thread.
| Tokens | GPU forward | CPU forward, 1 thread | Ratio |
|---|---|---|---|
| 1 | 6.6 to 8.3 ms | 34 to 42 ms | 5× |
| 16 | 7.0 to 16.6 ms | 94 to 109 ms | 7× to 14× |
| 128 | 12.9 to 13.3 ms | 312 to 752 ms | 24× to 57× |
| 512 | 27.7 to 32.4 ms | 1.16 to 2.90 s | 36× to 104× |
The CPU figures are noisy: at 128 tokens, about 0.75 s in one run and 0.31 s in the other. Without controlling other system activity, clocks and threads, the ratios are ranges for this command, not a hardware ranking.
The interesting part is the GPU column. Across the reported measurements, one position took about 5.5–8.3 ms and 128 positions about 8.6–13.3 ms. That is far less than 128 times longer. So what is the GPU doing with a single token?
Where does one-token time go? To find out, the Lab timed two moments separately: when the model call returned to Python, and when the GPU had finished:
| Tokens | Call returns after | GPU finished after | GPU still working after return |
|---|---|---|---|
| 1 | 4.9 ms | 5.5 ms | 0.6 ms |
| 16 | 5.2 ms | 6.0 ms | 0.8 ms |
| 128 | 4.6 ms | 7.7 ms | 3.0 ms |
| 512 | 5.4 ms | 29.8 ms | 24.5 ms |
For 1 and 16 tokens, the CPU spent about 5 ms just submitting the model’s work, and the GPU finished within a millisecond after that. At 512 tokens the CPU still returned after about 5 ms, but the GPU needed about 30 ms in total.
So at short lengths, the CPU’s job of submitting work is a strong candidate for the bottleneck: the GPU is waiting for instructions. At long lengths, the GPU’s own work dominates. This supports the submission-overhead hypothesis without proving it; it does not show that every kernel sat idle. The profiler recorded 1,224 PyTorch operator events for a 16-token pass but no CUDA device events on this Windows set-up, so it cannot say how many kernels ran or how long each took. A profiler that exposes device events is the next instrument needed.
Graph capture, compilation or fusion could reduce submission overhead. Any gain should be measured with its capture or compile cost reported separately, and with outputs checked against the reference. Compilation and Execution Graphs takes this up.
The engine on the GPU
Finally, the whole Chapter 6 engine: 32 greedy tokens from the pinned GPT-2 prompt, with a device-aware backend, five runs per device. This is end-to-end loop time after the model is built, not event-timed matmul throughput.
| CPU | GPU | |
|---|---|---|
| Total time (median) | 6.41 s | 0.453 s |
| Tokens per second | 5.0 | 70.7 |
| Forward per step (median) | 194 ms | 11.9 ms |
| Selection per step (median) | 5.2 ms | 1.6 ms |
| Output identical across runs | yes | yes |
This is the 14.2× from the opening. The engine’s step includes small operations submitted one by one from Python, input preparation and token selection, so the total must not be attributed to matrix-multiplication performance alone. This chapter does not measure how the 14.2× divides between submission, memory traffic and arithmetic. The one-row projection and tiny-operation results above were not taken on the engine’s own shapes (about 17–48 positions per uncached step), so they are candidate explanations, not a measured account. (Key-Value Caching later recorded 117 tokens/s for the uncached library engine on this GPU, against 70.7 here; the runs differ in backend construction and session, and the difference is not explained.)
A few details:
- Same tokens on both devices. CPU and GPU produced identical 32-token sequences. One greedy trajectory does not establish numerical equivalence, though; near-tied logits could pick differently. The manifest hashes differ because the recorded device differs.
- Selection matters more on the GPU. Selection took 1.6 ms per step on the GPU against an 11.9 ms forward pass, a larger share than on the CPU, because the forward pass shrank so much. (Comparing shares properly needs the same aggregation for both; the medians alone do not establish a fixed overhead percentage.)
- The uncached loop is still wasteful. It processed 1,040 positions to produce 32 tokens from this 17-token prompt. On a GPU at short lengths, that waste is relatively cheap, but this chapter did not benchmark a cached loop, so it cannot say when caching starts to win. Key-Value Caching makes that comparison directly.
Inference Lab increment
The Lab now has reusable measurement tools. Here is what each provides, and what it does not:
time_cuda(fn, warmup, iters, inner)returns CUDA-event-bracketed per-call times. Withinner > 1it reports a sustained stream of calls, not isolated single-kernel latency.time_cputimes a warm CPU callable.ramp_clocks()runs a warm-up workload. It does not lock clocks or power states.gflops,matmul_bytes,arithmetic_intensity,roofline_gflops,ridge_pointandrelative_errorimplement the cost model transparently.matmul_bytesis an idealised minimum traffic count, not a hardware reading.LibraryBackendfrom Building Our First Inference Engine accepts a CPU or CUDA device and records it in the manifest. That supports comparisons; it does not make results reproducible across devices.examples/ch07/gpu_matmul.pyhas separate commands:env,timing,ceilings,scaling,thin,launch,layout,precision,forwardandengine. Their results must be joined to environment metadata by hand; the code does not yet produce a self-contained record for every command.
The publication gate for this harness: every result carries its full environment; CPU submission time, event-bracketed GPU time and end-to-end latency are kept separate; individual samples are retained; input-transfer inclusion, cache state and clock state are stated; and comparisons use the same model and sampling policy. The scripts demonstrate most of these techniques but do not yet enforce the full record (exercise 9). Until they do, treat any single GPU throughput number as a measurement from one session, not a capability of the machine.
Limits of this chapter’s evidence
About the set-up
- One shared consumer GPU. An RTX 2060 12 GiB under Windows WDDM, PyTorch 2.6.0+cu124, with varying clocks and display contention. Other GPUs and drivers will have different knees and ceilings.
- Not measured at all: energy, multithreaded CPU, int8, data-centre GPUs, and a direct cached-versus-uncached comparison.
About the measurements
- Timing boundaries. The model-forward timings include copying the ids to the GPU. Engine timings include Python dispatch, tensor creation and sampling. Neither is kernel-only time.
- Memory traffic was estimated, not measured. The thin-projection GB/s values divide idealised bytes by time. “Bandwidth-bound” is a hypothesis consistent with the model, not a direct observation, and the roofline calibration is partly circular.
- Few repetitions. Size sweeps have three runs; the alignment sweep one run of 15 calls; CPU forward timings differed by more than a factor of two between sessions. The data support mechanisms and orders of magnitude, not universal rankings.
About what was not visible
- GPU internals. The Windows profiler gave no CUDA kernel events. Occupancy, real DRAM traffic, tensor-core instruction use and accumulation mode were not established.
- Precision scope. The error test used random normal matrices, not model activations, and did not test end-to-end generation with fp16 weights.
What you should now be able to do
- Calculate the FLOPs and idealised memory traffic of a matrix product, and distinguish that estimate from measured traffic.
- Apply a roofline with clearly identified ceilings, and explain why falling below the roof does not identify a single bottleneck.
- Separate enqueue time, synchronised wall time, CUDA-event time, repeated-call throughput and end-to-end latency.
- Explain why a one-token output projection uses about 2% of the GPU’s arithmetic while a large square product saturates it, and why the uncached engine is a different case.
- Test the effects of warm-up, clocks, shape, alignment and layout without turning one run into a general rule.
- Say what a Frobenius-error result can and cannot tell you about fp16 accumulation and generated tokens.
- Build a benchmark record identifying hardware, software, precision, timing boundary, samples and device provenance.
The output projection was the clearest case here: one token reading 154 MB of weights to do very little arithmetic. Attention has its own version of this problem, and one that grows with context length rather than staying fixed. Attention and Its Computational Cost measures it.
Key terms
- GEMM: general dense matrix-matrix multiplication; its conventional approximate arithmetic cost is \(2MNK\) FLOPs.
- Arithmetic intensity: arithmetic divided by bytes transferred at a specified memory level; the chapter’s closed-form version uses an optimistic operand/output traffic estimate.
- Roofline bound: maximum attainable FLOP/s under stated bandwidth and arithmetic ceilings.
- Ridge point: the ratio of compute ceiling to bandwidth ceiling, at which the roofline changes slope.
- Bandwidth-bound / compute-bound: classifications that require a defined traffic and bottleneck model, not just low measured utilisation.
- Host submission / launch overhead: CPU and runtime work required to enqueue device operations; distinct from pure GPU kernel execution time.
- Asynchronous execution: queued GPU work can continue after the CPU call returns.
- CUDA event: a stream-ordered marker usable to time intervals on the GPU.
- Tensor core: specialised matrix-multiply hardware with supported operand shapes and precision modes.
- Clock ramp: change in frequency/power state under load, which can affect a benchmark’s first runs.
- Effective modelled bandwidth: an estimated byte count divided by elapsed time; not a device-memory-counter measurement.
Reader exercises
- Time a large GPU GEMM using (a) only the Python call, (b) synchronised wall time and (c) CUDA events. Retain raw runs and explain the difference in measurement boundary before comparing GFLOP/s.
- Run
launchand compare (a) one isolated event-timed tiny operation with (b) a long queue of tiny operations. Which value changes, and what does that tell you about host submission? - Rebuild the roofline once using 278 GB/s from the copy probe and once using 303 GB/s of modelled effective traffic from the thin GEMM. How do the candidate ridge and conclusions change? What additional hardware counter would be needed for a genuine DRAM roofline?
- In
cmd_forward, moveids.cuda()outside the event-timed lambda and compare results at 1, 16, 128 and 512 tokens. Report separately the input transfer, model event interval and end-to-end wall latency. - Re-run the fp16 \(M=8\) and \(M=16\) output-projection cases with more repetitions and a profiler that records CUDA kernels. Can you identify an algorithm change, or must the cause remain unresolved?
- Re-run the 4,095–4,100 alignment sweep in independently restarted processes. Report distributions, not just medians. If you pad a vocabulary, how will you ensure padded logits cannot be sampled?
- Repeat the precision experiment with real GPT-2 activations. Record maximum error and percentile error as well as relative Frobenius error, then compare final logits and generated tokens across fp32 and fp16.
- Correct
gflops_modelso that its dense attention-matmul count matches the actual \(T\times T\) products executed before masking. Does the reported effective model GFLOP/s change? Distinguish a calculation fix from a new timing measurement. - Extend the benchmark record with environment snapshot, cache/warm-up settings, input placement, individual timings and an explicit “device kernel / event interval / request wall time” field. Validate that missing metadata causes the report to be marked incomplete.
References
- Research paper 1 — Samuel Williams, Andrew Waterman and David A. Patterson, Roofline: An Insightful Visual Performance Model for Multicore Architectures (2009). Establishes the arithmetic-intensity/bandwidth/throughput upper-bound model; it does not validate the book’s RTX 2060 ceilings.
- Research paper 2 — Zhe Jia, Marco Maggioni, Jeffrey Smith and Daniele Paolo Scarpazza, Dissecting the NVIDIA Turing T4 GPU via Microbenchmarking (2019). Supplies an independent example of probing a Turing GPU’s memory hierarchy, instructions and low-precision matrix behaviour. The paper studies T4, not the book’s RTX 2060.
- Research paper 3 — Paulius Micikevicius et al., Mixed Precision Training (2017). Motivates separating low-precision operand storage from numerical accuracy and accumulation; its experiments concern training, so it is contextual rather than evidence for this inference benchmark.
- Implementation documentation — NVIDIA Deep Learning Performance: Matrix Multiplication, for tiling, shapes and throughput considerations.
- Implementation documentation — PyTorch CUDA semantics and NVIDIA CUDA Best Practices Guide, for asynchronous execution, synchronisation and event timing.
Evidence in this chapter
| Claim | Evidence classification |
|---|---|
| Dense GEMM conventionally costs approximately \(2MNK\) FLOPs; roofline uses a compute and a memory ceiling | Established background; Williams et al. (2009) |
| CUDA calls can return before GPU work completes; correct timing requires an appropriate device-completion boundary | Established background; PyTorch/NVIDIA documentation |
| The call-only timer implied about 757 TFLOP/s, versus about 5.8–5.9 TFLOP/s by event or synchronisation | Book measurement; pinned hardware and session |
| The small GPU 8×8 operation averaged about 35 µs per call in a 2,000-call Python/PyTorch loop, versus 4 µs for a CPU-thread call | Book measurement of the submission path, not isolated kernel launch latency |
| Thin fp32 output projection took about 510–592 µs from 1 to 32 tokens; \(M=1\) achieved around 2% of observed square-GEMM fp32 throughput | Book measurement, three runs per shape |
| The thin-GEMM effective rate reached 303 GB/s | Derived from idealised bytes/time; not observed DRAM-controller bandwidth |
| The measured thin-product timing curve is compatible with a roofline knee near \(M\approx49\) | Model-consistent hypothesis, partly circular calibration |
| fp16 output-projection time at \(M=1\) was 271 µs versus 510 µs for fp32 | Book measurement; mechanism not isolated |
| A 4,097-square fp16 product had ~28% less throughput than 4,096 | Book measurement; one alignment sweep, no general guarantee |
| fp16 error was \(3.6\times10^{-4}\) relative Frobenius; rounded operands alone gave \(2.9\times10^{-4}\) | Book result on random normal matrices; accumulation mode not determined |
Whole-model GPU timing includes ids.cuda() within the event-timed callable |
Implementation observation; not pure kernel timing |
| CPU-side model-call submission is a material candidate bottleneck at short sequence lengths | Book observation and hypothesis; profiler has no CUDA events |
| 32-token engine median was 6.41 s on CPU and 0.453 s on GPU; output ids agreed | Book result, one prompt and one GPU setup |
| True device-memory traffic, kernel launch count, tensor-core instruction mix, int8, cache speedup, power/energy | Not established or not measured |