← Inference From First Principles

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.

The Chapter 6 engine generated 32 greedy tokens from GPT-2 in a median of 6.41 seconds on one configured CPU thread. With the same model snapshot and selection rule, the five-run median was 0.453 seconds using the GPU: about 14.2 times faster. The generated token ids agreed for this prompt. That is a substantial improvement, but it is much smaller than the ratio between the machine’s best measured large-matrix throughput figures would suggest.

On this machine, large fp32 GPU matrix products reached roughly 7.4 TFLOP/s in the best observed runs; a single CPU thread reached about 53 GFLOP/s on the larger square products it could handle, a ratio near 140. Yet those are different workloads and measurement boundaries, not a predicted end-to-end model speedup. A model evaluation comprises many projections, normalisations, attention operations, Python dispatches, and allocations. The output projection alone, at one token, achieved about 151 GFLOP/s—around 2% of this GPU’s observed large-fp32-matmul rate—on an idealised arithmetic count. Its weights are large relative to the work performed, so reading them is a plausible limit. At the other extreme, a tiny GPU operation took about 35 microseconds per Python/PyTorch call in the measured submission loop, even though its arithmetic was negligible. The data point to at least two regimes: moving bytes and issuing small operations. They do not, by themselves, apportion the complete engine’s latency between them.

We will derive a cost model, check it against measured matrix shapes, and examine how GPU timing can fail by orders of magnitude if the CPU’s enqueue time is mistaken for execution time. Throughout, distinguish measured elapsed time, derived throughput, estimated bytes transferred, and hypotheses about the bottleneck. They are not interchangeable.

Where this sits

Chapter 4 counted matrix-multiplication operations inside the forward pass; Chapter 5 showed the cost of repeatedly processing an entire prefix without a KV cache; Chapter 6 assembled and measured a baseline engine. Operation counts alone cannot predict latency. Here we add operand size, memory locality, data movement, parallelism and dispatch overhead. Those constraints explain why the best kernel for a prompt-length matrix is not necessarily the best for one token of decode.

The Inference Lab increment is a GPU measurement harness: CUDA-event timing with explicit synchronisation, an optional repeated-call mode, a warm-up workload, probes for arithmetic and copy throughput, and a roofline calculation. Chapter 6 already supports a device-aware library backend; its manifest includes the reported parameter device. The lab does not yet guarantee that every benchmark result automatically records the full environment or isolates kernel-only execution. Those are acceptance criteria for the next revision of the harness.

The recorded hardware was an NVIDIA GeForce RTX 2060 with approximately 12 GiB of device memory, compute capability 7.5, under Windows 11 using the WDDM display driver. It also drove the desktop and a browser. The study used PyTorch 2.6.0+cu124, CUDA runtime 12.4 and NVIDIA driver 591.44. That provenance matters: these measurements describe a shared consumer GPU and a particular software stack, not a universal GPU baseline. The GPU-computing and serving volumes can build on the method, but must establish their own ceilings and latency curves.

What a matrix multiplication costs

What a matrix multiplication costs

A product of an \(M \times K\) matrix and a \(K \times N\) matrix has \(MN\) output elements. Each is a dot product of length \(K\): \(K\) multiplies and \(K-1\) additions. Counting one multiply-add as two floating-point operations gives the usual dense-GEMM approximation

\[ \text{FLOPs} = 2MNK \]
For a transformer's dense projections, \(M\) counts positions evaluated together and \(K \times N\) describes a weight matrix. GPT-2's representative shapes are below. This table excludes biases, the QKᵀ and attention-value products, activation functions and layer normalisation; the latter operations also cost time even where they contribute relatively little to this FLOP count.
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

For a given weight matrix, its element count is independent of \(M\), while useful dense-matmul arithmetic scales with \(M\). A prefill of 500 positions may multiply a \(500 \times K\) activation matrix by the weights; an incremental, KV-cached decode step can have \(M=1\) for the same projection. The deliberately uncached generator used in Chapters 5–7 is different: at every step it reprocesses the entire growing prefix, so its projection \(M\) increases with context length. Do not apply the \(M=1\) roofline directly to that engine.

Arithmetic intensity

Arithmetic intensity is useful arithmetic divided by bytes moved, in FLOPs per byte. For an isolated dense product, a simple optimistic traffic model counts one read of each input and one write of the output. With \(b\) bytes per element, that gives

\[ I = \frac{2MNK}{b\,(MK + KN + MN)} \]
If the weight operand \(KN\) dominates both the activations \(MK\) and the output \(MN\), this *modelled* intensity approaches
\[ I \approx \frac{2M}{b} \]
For \(M=1\) and fp32 (\(b=4\)), the limiting estimate is about 0.5 FLOP per byte; for fp16 (\(b=2\)), about 1. At \(M=64\), the weight-dominated approximation gives 32 FLOP/byte for fp32. The actual intensity is lower when activation and output bytes matter, and **actual device-memory traffic is not measured by this formula**. Caches, tiling, repeated loads, intermediate writes and data transfers between memory levels can change it. We will use the estimate to form a hypothesis and then compare it with elapsed time.

The roofline

Roofline: arithmetic intensity vs performance

Let \(P\) be a sustained or theoretical arithmetic ceiling in FLOP/s and \(B\) a bandwidth ceiling in bytes/s, defined for the same device, precision and memory level. If a kernel performs \(F\) FLOPs and transfers \(D\) bytes at that level, with \(I=F/D\), its throughput is bounded by

\[ \text{attainable} \le \min(P,\; B \cdot I) \]
This **roofline bound** has a sloped bandwidth-limited region and a flat compute ceiling, meeting at \(I^*=P/B\). It is an upper bound conditional on the chosen ceilings and traffic model, not a classifier that proves a kernel is memory-bound or compute-bound. A point below the roof may reflect occupancy, instruction dependencies, launch overhead, poor tiling, host submission, or simply an inaccurate estimate of bytes actually moved. We use the roofline as a diagnostic question: *what further measurement would distinguish these explanations?*

Timing a GPU without fooling yourself

Timing a GPU without fooling yourself

CUDA operations are generally asynchronous with respect to the CPU. A Python call such as a @ b normally queues work and may return before the device finishes. A wall-clock timer around only that call can therefore capture CPU dispatch and enqueueing rather than the completed operation. Synchronising immediately after the call gives end-to-end elapsed time for the queued work; CUDA events give an elapsed interval on the device’s stream. Neither measure should be labelled “pure kernel execution time” without checking what else falls inside the timed interval, including transfers, queued work and host-side starvation.

For a 4,096 × 4,096 fp32 product—approximately 137.4 billion nominal FLOPs—the recorded medians were:

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 enqueue-only result implies roughly 757 TFLOP/s, far beyond the measured fp32 rate of this card. That is not an accelerated kernel; it is a measurement-boundary error. Synchronised wall time and event time agree to within a few per cent here, supporting the conclusion that the product takes approximately 23–24 milliseconds in this particular experiment. The first, older GPU benchmark did synchronise, but selected the fastest of only five runs for a 512³ product; that sampling and summary rule was too weak to establish a stable performance comparison.

CUDA events timestamp stream progress and usually give the clearest measurement of a device-side interval. They still need a well-defined start and end, warm-up, an appropriate amount of queued work, and a final synchronisation before elapsed time is read. When the host cannot submit small operations fast enough, a long event-bracketed sequence can include device idle gaps. The lab therefore reports event-bracketed per-call queue throughput separately from wall-clock request latency and CPU enqueue time. See the CUDA and PyTorch timing documentation in the references.

Four conditions for a trustworthy number

  1. Define the boundary. Decide whether the target is dispatch time, event-bracketed work, a model call including host-to-device copies, or an end-to-end request. Do not combine them under one label.
  2. Synchronise or use CUDA events. A timer that ends before GPU work finishes does not report the operation’s latency.
  3. Warm up and report state. Kernel loading, allocator behaviour, algorithm selection, clocks, power and thermal conditions may change over the first calls. A three-second compute workload reduced variation in this session but did not lock clocks.
  4. Use repetitions and report dispersion. Include device, driver, runtime and framework versions, precision, data shapes, thread count, warm-up, timing method, and samples or quantiles. For tiny operations, compare single-call latency with batched repeated-call throughput; they answer different questions.

The RTX 2060 was also driving a display under Windows WDDM. Very short event timings had two visible clusters—about 4 microseconds and roughly 60–100 microseconds for the same nominal operation—while observed clocks varied under load. Repeated-call timing reduced some dispersion by keeping a queue busy; it did not remove contention or establish the isolated latency of a single kernel. Separate process runs also varied by up to about 40% for some sizes. Those facts belong beside the benchmark, not in a footnote that disappears when someone copies one number.

What this machine can do

The measurements below establish observed rates for selected microbenchmarks, not immutable hardware ceilings. A large contiguous copy approximates one memory-traffic pattern; a large GEMM probes an arithmetic regime; and a thin output projection provides another traffic pattern. Datasheet specifications and low-level memory counters would be useful additional cross-checks but were not independently established in this chapter.

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 copy probe and the thin-GEMM “GB/s” number are not interchangeable measurements of DRAM bandwidth. For the copy, source and destination bytes are known at the API level. For the thin product, the numerator is the optimistic traffic estimate \(b(MK+KN+MN)\); the code did not read hardware memory-traffic counters. An effective value of 303 GB/s therefore does not prove that 303 GB/s crossed the memory controller. The much higher fp16 GEMM rate compared with fp32 is consistent with access to faster reduced-precision matrix hardware, but this experiment did not inspect which tensor-core instructions each chosen kernel executed.

For a worked, empirical roofline I use 303 GB/s as the effective thin-product traffic calibration and the best observed fp32/fp16 square-GEMM rates, approximately 7.4 and 31.4 TFLOP/s. They imply illustrative ridges near 24.6 and 103.7 FLOP/byte. Because the bandwidth value is partly derived from the thin operation later being assessed, this comparison is not an independent confirmation of its bottleneck. Rebuild the roofline with the 278 GB/s copy-probe rate as a sensitivity check, and do not treat either bound as a universally attained chip specification.

Matrix size and the cost of a call

Square-matrix throughput for sizes 32 to 8,192, using medians from three separate runs at each size (where available). The CPU column uses one configured PyTorch thread. These are throughputs derived from time, so a fast call with very little arithmetic can still have a tiny GFLOP/s value.

\(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

Read the table in three bands.

At the smallest sizes the single-thread CPU path wins. For \(n=32\), the derived times are roughly 6.6 microseconds on the CPU and 38 microseconds along this Python-to-GPU path. The recorded CPU/GPU crossover for these square products is between sizes 64 and 128. That is a property of the tested shape, software stack and measurement method—not a universal threshold for GPU usefulness.

In the small-to-medium range, dispatch and useful arithmetic overlap awkwardly. The reported GPU per-call time stayed around 36–43 microseconds from \(n=32\) to \(n=512\) even as nominal arithmetic increased sharply. In a separate 2,000-call Python submission loop, an 8×8 GPU matmul took a median 35.4 microseconds per call from enqueue to completion, versus 4.2 microseconds on the configured CPU thread; a 1,024-element GPU add took 19.6 microseconds. These are host/PyTorch submission-path measurements under sustained queuing, not a universal 35-microsecond CUDA kernel launch latency. The similar enqueue and completion averages show that the queue could be kept busy in this test; they do not establish that the device performed no work.

Large matrices reach a high fraction of the recorded arithmetic rate. The fp32 square products near 512 and above often reached 6–7 TFLOP/s; fp16 required larger shapes before reaching roughly 25–31 TFLOP/s. Calling every \(n\ge512\) operation “compute-bound” would go beyond the measurements: occupancy, dispatch and clock changes can still matter, and a roofline classification needs a defensible traffic measurement.

The 2,048 row was especially variable: across the three runs fp32 ranged from 3,791 to 5,987 GFLOP/s and fp16 from 14,614 to 23,227 GFLOP/s. Power or clock-state changes are a plausible explanation on a shared display GPU, but the experiment did not isolate them. This row illustrates why a median without the individual runs is insufficient for diagnosing a performance regression.

Transformer shapes

Square matrices are convenient calibration workloads, but GPT-2’s dense projections often multiply \(M \times 768\) by \(768 \times N\), where \(M\) is the number of positions in the current invocation. I measured an MLP-up projection and the output projection as \(M\) varied between one and 2,048. The thin-matrix probe is relevant to incremental decode; the no-cache generation engine instead repeats longer and longer prefix-sized invocations.

The output projection uses \(K=768\) and \(N=50{,}257\): 38,597,376 weights, or about 154.4 MB in fp32 and 77.2 MB in fp16 (decimal units). These weight-byte counts are an important scale comparison, not a measurement of traffic on every invocation.

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

From \(M=1\) to 32, measured fp32 time increased only from about 510 to 592 microseconds while nominal FLOPs increased 32-fold. The table’s “GB/s” divides idealised operand/output bytes by elapsed time; it does not report hardware-counter bandwidth. At \(M=1\) the operation achieved about 151 GFLOP/s, or 2% of the best observed large-fp32-GEMM rate on this card. These observations are consistent with repeatedly making a large weight matrix available, but they do not by themselves distinguish DRAM traffic, cache behaviour, kernel selection and host overhead. A roofline is a useful first diagnostic, not an explanation by itself.

Using the empirical ridge of 24.6 FLOP/byte and the simplified \(I\approx M/2\), the model places a candidate transition near \(M\approx49\). The measured fp32 time is almost flat through 32 positions and increases between 64 and 128; that is compatible with the model. However, the traffic calibration was partly derived from this same projection, so the apparent agreement is not an independent validation. A GPU profiler with memory-traffic counters, or experiments varying weight size while holding FLOPs similar, would provide stronger evidence.

The fp16 output projection changes both weight bytes and the available matrix-execution path; its timings should not be interpreted as a pure two-byte-versus-four-byte experiment.

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 \(M=1\), fp16 took 271 microseconds compared with 510 for fp32, almost a 1.9× reduction. Halved weight storage is consistent with that change under a bandwidth-sensitive hypothesis, but kernel choice, arithmetic mode and launch effects also changed. At \(M=8\), fp16 was slower than at \(M=16\) in all three recorded runs (around 554–605 microseconds against roughly 344–357); the code did not inspect the chosen kernels, so an algorithm-switch explanation remains a hypothesis. At \(M=1{,}024\), the fp16 shape reached about 57% of the best observed square-matmul fp16 rate, while the fp32 case reached about 90% of its corresponding rate. Different shapes and hardware paths have different utilisation; a single peak number is not a measured entitlement.

For the smaller MLP-up projection, \(N=3{,}072\), the fp32 weight operand is about 9.4 MB (decimal). Observed fp32 times of roughly 36–43 microseconds at \(M=1\) to 8 overlap the small-operation submission-path floor. Moving 9.4 MB at 278 GB/s would take about 34 microseconds if every weight crossed that interface once, so these two estimates overlap. This experiment cannot apportion delay between dispatch, memory traffic and computation; measuring effective traffic and using a lower-overhead launch path would help distinguish them.

Layout and alignment

Memory layout can matter, but its effect is shape- and kernel-dependent. On a 2,048-square experiment, transposed views changed recorded fp32/fp16 times by less than about 10% in either direction. A case that explicitly materialised a contiguous transpose inside the timed callable was about 19% slower than the fp16 contiguous baseline. The strided-slice case operated on half the reduction dimension, so it performed half the nominal matmul arithmetic; the test did not measure whether PyTorch created an internal copy. This evidence supports the narrower advice: inspect both strides and materialisation, and compare elapsed time only after normalising the work actually done.

Alignment is especially relevant to the reduced-precision matrix path because implementations use tiled instructions with shape constraints. However, a dimension that is not a multiple of eight does not necessarily force a particular fallback; the library may pad, choose a different tile, use another kernel, or handle the edge directly. Here is the recorded 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

In this sweep, size 4,097 achieved about 28% less throughput than 4,096 despite changing the dimension by one. The pattern is not monotonic: 4,090 and 4,092 performed much better than 4,095 or 4,100. The sweep used 15 event-timed calls per size in one run, so it cannot establish a universal rule or isolate alignment from algorithm selection and clock state. The pragmatic lesson is to benchmark actual candidate dimensions and to document any padding. GPT-2’s 50,257-entry vocabulary is not divisible by eight; padding its output projection may change throughput, but unused padded logits must be masked or excluded if the generation distribution is to stay the same.

What reduced precision does to the answer

Higher matrix throughput is not useful if numerical changes violate the model’s required tolerance. The lab multiplied \(1024\times K\) and \(K\times1024\) matrices drawn from a standard-normal distribution and compared fp32 and fp16 results with a float64-computed reference using relative Frobenius-norm error. The “inputs rounded only” control converted the operands to fp16 and back to float64 before a float64 matrix product. That isolates much of input quantisation error; the float64 product is a high-precision numerical reference, not literally exact real arithmetic.

\(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}\)

The observed fp32 error increased modestly with \(K\), while fp16 error remained near \(3.6\times10^{-4}\) in these three random-input tests. The rounded-input control already contributed roughly \(2.9\times10^{-4}\), suggesting that operand quantisation dominated this particular error metric. It does not reveal the kernel’s internal accumulation mode: proving fp32 accumulation would require documentation or a targeted numerical/assembly inspection, not this table alone. Frobenius error can also conceal a large local deviation. Chapter 12 should test maximum and percentile elementwise errors, attention/logit changes and generated-token agreement on real activations—including the outliers measured in Chapter 4—before drawing a model-quality conclusion.

From one product to a model

The next test measures the library GPT-2 model, not Chapter 4’s hand-written reference. It includes embeddings, attention, MLP and normalisation in one forward invocation. The GPU event-timed callable is gpu(ids.cuda()): the token ids are copied from CPU to GPU inside the timed function. Thus these figures are not isolated device-only model-kernel latencies. Two runs of the surrounding experiment produced the ranges below; the CPU uses one configured PyTorch 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×

At 128 tokens, the CPU-forward measurement changed from approximately 0.75 s in the first run to 0.31 s in the second. Without isolated controls for other system activity, clock state and thread configuration, this spread should prevent a firm hardware ranking beyond the tested environment. The GPU intervals were narrower but still include the particular input-copy and queuing behaviour of the benchmark. Their time ratios are empirical ranges for this command, not a forecast of service speedup.

A more precise reading of the GPU column is that a one-position forward took approximately 5.5–8.3 ms across the reported measurements, while 128 positions took roughly 8.6–13.3 ms. That is far less than a 128× increase, but not “the same time”. The likely contributors include small matmuls, memory access, Python launch/submission, attention work and the input copy. To investigate the submission component, the lab separately timed how long a model invocation took to return to Python and how long until an explicit GPU synchronisation completed:

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 one and 16 tokens, the CPU had spent about 5 ms submitting the model work, and synchronisation completed within another millisecond in this test. At 512 tokens the CPU still returned after roughly 5 ms, while completion required approximately 30 ms in total. These measurements support a CPU-submission/launch-overhead hypothesis at short lengths; they do not prove that each CUDA kernel was idle or that arithmetic alone explained long lengths. The profiler returned 1,224 PyTorch operator events for a 16-token pass, including nested wrappers, but zero CUDA device events on this Windows setup. It therefore cannot establish how many kernels ran or their per-kernel time. A profiler that exposes device events is the next necessary instrument.

Reducing host submission overhead through graph capture, compilation or fusion may help, but any measured gain should include capture or compile cost separately and verify that model outputs still meet the reference tolerance. Chapter 18 takes up those questions.

The engine on the GPU

The same Chapter 6 engine then generated 32 greedy tokens from the pinned GPT-2 prompt using a device-aware backend. Five request timings were recorded for each device; the table reports medians. This is end-to-end loop wall time after backend/model construction, not isolated 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

Across those recorded runs, CPU and GPU produced identical sequences of 32 token ids. The result is encouraging, but one greedy trajectory cannot establish cross-device numerical equivalence; near-tied logits may pick different tokens. The backend manifest hashes differ because the recorded device and execution path differ. The engine also constructs its input tensor and moves logits or sampling intermediates across software boundaries, so the total result must not be attributed to GEMM performance alone.

Selection occupied a larger fraction of the measured GPU step than the CPU step because the forward component became much shorter, and the sampler has its own operations and dispatch costs. The medians in the table—1.6 ms GPU selection versus 5.2 ms CPU—do not by themselves prove a fixed “12% launch tax”: each percentage needs the same aggregation method and workload. The no-cache loop reprocessed 1,040 positions to produce 32 new tokens from this 17-token prompt (Chapter 5). That redundant work can be relatively cheap at short GPU sequence lengths, but this chapter did not benchmark a cached loop, so it cannot establish when a KV cache begins to win. Chapter 10 must make the direct comparison.

What the numbers do not show

  • Hardware scope. One shared RTX 2060 12 GiB under Windows WDDM, PyTorch 2.6.0+cu124, with changing clocks and display contention. Performance knees will differ on other GPUs and drivers.
  • Measurement boundaries. The event-timed model-forward callable copies ids to the GPU during the timed interval; engine measurements include Python dispatch, tensor creation and sampler work. They are not kernel-only timings.
  • Estimated memory traffic. The thin-product GB/s values use idealised operand/output bytes divided by time, not memory-controller counters. “Bandwidth-bound” remains a model-consistent hypothesis rather than a direct measurement.
  • Statistical limitations. Some size sweeps have three separate runs, the alignment test one 15-call run, and the CPU-forward timings differed by a factor above two between sessions. These data support mechanisms and order-of-magnitude estimates, not universal rankings.
  • Device internals. The Windows profiler did not supply CUDA kernel events. Occupancy, actual DRAM traffic, tensor-core instruction selection and exact accumulation mode were not established.
  • Precision scope. Relative Frobenius error was measured on random normal matrices, not model activations or end-to-end generation under fp16 weights.
  • Other omissions. No energy study, multithreaded CPU comparison, int8 inference, dedicated data-centre GPU, or direct cached-versus-uncached speedup measurement.

Inference Lab increment

The Lab now contains reusable measurement primitives, with a distinction between available functionality and what the current scripts actually enforce:

  • time_cuda(fn, warmup, iters, inner) returns CUDA-event-bracketed per-call times; inner > 1 reports a sustained stream of calls, not necessarily isolated single-kernel latency. time_cpu measures a warm CPU callable.
  • ramp_clocks() supplies a GPU warm-up workload; it does not lock clock or power states.
  • gflops, matmul_bytes, arithmetic_intensity, roofline_gflops, ridge_point and relative_error implement a transparent cost model. The bytes helper is an idealised minimum traffic count, not a memory-counter reading.
  • LibraryBackend from Chapter 6 accepts a CPU or CUDA device and includes that device in its manifest; this supports comparative tests, not automatic cross-device reproducibility.
  • env, timing, ceilings, scaling, thin, launch, layout, precision, forward and engine are separate commands in examples/ch07/gpu_matmul.py. Their results must be joined to captured environment metadata explicitly; the code does not yet produce a self-contained benchmark record for every command.

The publication gate for this harness is repeatable, appropriately bounded evidence: capture all environment fields alongside every result; distinguish CPU submission time, event-bracketed device time and end-to-end request latency; retain individual samples; state input-transfer inclusion and cache/clock state; and compare against the same model and sampling policy. The existing scripts demonstrate most techniques, but do not yet enforce the full record contract. Until then, treat a single GPU throughput number as a measurement from one session, not a machine capability that can be reused without qualification.

What you should now be able to do

  • Calculate dense-GEMM FLOPs and the idealised operand/output traffic for given dimensions; distinguish that traffic estimate from measured device-memory bytes.
  • Apply a roofline bound using clearly identified bandwidth and compute probes, and explain why falling below the roof does not identify one specific bottleneck.
  • Separate asynchronous enqueue time, synchronised wall time, CUDA-event time, batched queue throughput and end-to-end service latency.
  • Explain why an output projection at \(M=1\) can achieve low GFLOP/s even when a large square GEMM saturates arithmetic units; distinguish cached decode from the uncached chapter engine.
  • Inspect the effects of device warm-up, clock/power state, shape, alignment and layout without turning one run into a general rule.
  • Explain what a relative Frobenius-error result can and cannot establish about fp16 accumulation and generated-token equivalence.
  • Construct a benchmark record that identifies hardware, software, precision, timing boundary, samples and relevant artefact/device provenance.

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

  1. 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.
  2. Run launch and 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?
  3. 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?
  4. In cmd_forward, move ids.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.
  5. 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?
  6. 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?
  7. 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.
  8. Correct gflops_model so 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.
  9. 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

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