← Inference From First Principles

Memory Bandwidth and Compute Bottlenecks

Build and audit a three-term GPU performance model against 58 isolated operations and a batched GPT-2 decode that exposes its limitations.

I built a deliberately small performance model and tested it on 58 GPU operations. Its inputs were the operation’s approximate arithmetic count, a minimum byte count, and three performance measurements made on the same machine: a launch-related timing floor, sustainable bandwidth, and arithmetic throughput. Across two runs, the median measured time was 1.10–1.14 times the estimated floor; 55 of 58 operations in the less favourable run, and all 58 in the other, fell within a factor of two. None of the operations classified as memory-dominated finished more than five per cent below its estimated memory-time term. That is useful calibration evidence, not proof that the chosen bandwidth value is a physical upper bound.

The same model was less useful when applied to an entire cached decode step. In a batch sweep, step latency began rising visibly by 64 sequences; at batch 256, the measured 30.5–33.4 ms was 3.1–3.3 times the model’s 9.9–10.1 ms estimate. The model’s launch term had been calibrated to the measured batch-1 step, yet it still missed the work that appeared as batch size increased.

A model that describes isolated operations but fails on their composition has done something valuable: it has located a missing cost. This chapter builds the model, tests it against its calibration measurements and new shapes, and records where it stops explaining the data. Later chapters can use it to form specific hypotheses about batching, fusion, precision and execution overhead—but not to certify a speedup without another measurement.

Where this sits

Matrix Multiplication and GPU Execution introduced the compute-and-memory roofline, including the difficulty of measuring GPU execution independently of Python submission time. Attention and Its Computational Cost exposed attention’s intermediate-memory costs; Prefill and Decode found an approximately flat per-step decode latency for GPT-2 small; and Key-Value Caching measured KV-cache reuse and allocator effects. This chapter combines those observations into a testable cost accounting model, while keeping the distinction between a theoretical lower bound and an empirical estimate visible.

The Inference Lab increment is predict_time(flops, bytes_moved, launch_s, bandwidth_gb_s, peak_gflops): a helper that returns three time estimates, their maximum, and the term that dominates under the supplied assumptions. The chapter adds measure_ceilings() and two evaluation paths: a 58-operation suite and a batched cached-decode experiment. The engineering habit is to state the performance lever, calculate the expected effect, measure it, and record disagreements rather than relabel them as successes.

For the Pi series, this is a diagnostic method rather than a universal three-way diagnosis. A slow local model can be limited by launch and host overhead, memory movement, arithmetic, kernel efficiency, synchronisation, allocation, or scheduling. The three-term estimate is a useful first screen. A large unexplained gap is the signal to inspect what that screen omitted.

Three ceilings

Three ceilings on a kernel

For a specified operation and an explicitly chosen execution boundary, the Lab begins with this model:

\[ \hat t = \max\!\left(t_{\mathrm{issue}},\frac{D_{\mathrm{nominal}}}{B_{\mathrm{ref}}},\frac{F_{\mathrm{model}}}{P_{\mathrm{ref}}}\right). \]
Here \(\hat t\) is the **estimated floor**, \(D_{\mathrm{nominal}}\) is a model of minimum bytes transferred, \(F_{\mathrm{model}}\) is an arithmetic-count convention, and \(B_{\mathrm{ref}}\) and \(P_{\mathrm{ref}}\) are achieved rates on reference kernels. These last two are not the hardware's proven maximum rates. If actual minimum traffic and true physical ceilings were known, corresponding memory and compute terms would be lower bounds; as implemented, \(\hat t\) is a calibrated diagnostic estimate.
  • Issue/launch term, launch_s: a measured elapsed-time floor from a tiny PyTorch operation of the same class. It includes characteristics of the calling framework, GPU queue and benchmark method; it is not a portable constant or a measurement of driver launch latency alone.
  • Memory term, bytes_moved / bandwidth_gb_s: nominal bytes divided by an achieved bandwidth reference. Hardware may serve some bytes from cache, replay inputs, or require extra traffic; the counted bytes are not a memory-controller reading.
  • Compute term, flops / peak_gflops: estimated operations divided by the best observed arithmetic throughput in a selected benchmark. The counting convention for elementwise kernels is approximate.

predict_time labels the largest term launch, memory, or compute. These are model classifications, not profiler diagnoses. The classic roofline is a bound on attainable arithmetic rate given operational intensity and specified ceilings. Adding an empirical issue floor is a useful extension for small operations, but does not make the three-term result a universal performance law. A term may dominate this calculation while the measured operation remains slow for another reason.

In the simple model, predicted time is the largest estimated component. Real timings can fall on either side: a small ratio may indicate an outdated reference ceiling, approximate FLOP or byte accounting, timer variation, cache effects, or a mismatch between the reference and evaluated kernels. A measured/predicted ratio above one identifies unexplained time; a ratio below one requires checking assumptions. Neither outcome, by itself, establishes which hardware resource was saturated.

Measuring the ceilings

A believable estimate needs a reproducible calibration. measure_ceilings() benchmarks copy, reduction and fill throughput over several tensor sizes; tiny operations for per-class timing floors; and large matrix products for fp32 and fp16 throughput. These measurements use CUDA events and repeated queued calls, so the short-operation figures describe steady-state per-call elapsed time, not isolated client-visible latency. The recorded environment is a Windows display GPU; clocks and competing work were not experimentally controlled.

Bandwidth probes. The harness computes nominal GB/s by dividing a calculated byte count by a CUDA-event timing: two buffer sizes for copy_ (read plus write), one for sum (read), and one for fill_ (write). A reduction also performs arithmetic, and on-cache traffic can differ from the counted bytes. Two run records provide the following values; the unit is decimal GB/s, while buffer sizes use binary prefixes.

Buffer Copy Reduction (sum) Fill Copy time per call
4 KiB 0.89–0.91 GB/s 0.41–0.42 GB/s 0.55 GB/s 9.0–9.2 µs
256 KiB 67–73 GB/s 28–30 GB/s 35–42 GB/s 7.2–7.8 µs
1 MiB 261–269 GB/s 78–80 GB/s 128–162 GB/s 7.8–8.0 µs
16 MiB 274–275 GB/s 275 GB/s 288–293 GB/s 122 µs
64 MiB 276–279 GB/s 298 GB/s 290–297 GB/s 482–486 µs
256 MiB 277–279 GB/s 304–305 GB/s 292–299 GB/s 1.9 ms
1 GiB 213–231 GB/s 253–300 GB/s 244–292 GB/s 9.3–10.1 ms

At small sizes, fixed submission and execution costs dominate and dividing small byte counts by time gives a low apparent rate. By the tens-of-megabytes regime, the copy and reduction probes approach several hundred nominal GB/s; the largest observed value was about 305 GB/s on the 256 MiB reduction. measure_ceilings() takes the maximum achieved rate of any measured pattern at 64 MiB or more. This is a calibration reference, not a universal read-bandwidth maximum. A 1 GiB copy was slower, at 213–231 GB/s, and the cause was not isolated. It is inappropriate to attribute differences between copy, sum and fill exclusively to read/write physics without their kernel costs and memory-traffic counters.

Arithmetic probes. In the recorded chapter runs, the ceilings command found best large-GEMM throughputs of approximately 6.2–6.4 TFLOP/s in fp32 and 27.2–30.8 TFLOP/s in fp16. Matrix Multiplication and GPU Execution had seen larger values in another session. A best-observed GEMM rate is a practical reference for that precision and shape family; it is not a proof of the GPU’s absolute arithmetic maximum. Clock variation is plausible, but power, temperature, scheduling and implementation choice were not isolated here.

Small-operation timing. The probe queues many calls between CUDA events and divides elapsed GPU-event time by the number of calls. The observed per-call rates include whatever bottleneck prevents the work queue from completing faster; calling all of it a GPU kernel-launch cost would be too strong.

Operation Observed steady-state time per call
8×8 matrix product 12.1–13.5 µs
1,024-element add 9.0–9.6 µs
Layer norm, 4×768 11.1–11.8 µs
Softmax, 4×1,024 8.7–8.9 µs

The small matrix product took 12.1–13.5 µs here, against approximately 35.4 µs in Matrix Multiplication and GPU Execution’s differently timed session. That discrepancy matters, but the source does not establish its cause. Host scheduling, PyTorch dispatch behaviour, GPU workload, clock state, framework synchronisation and event batching may all contribute. The library’s cached decode timing also varied between Prefill and Decode and Key-Value Caching, but these numbers alone cannot prove that host CPU state explains the change. Record the discrepancy as a reproducibility problem and test the cause with a controlled profiler or isolated host/GPU measurement.

The practical rule is to calibrate close to the benchmark and preserve the calibration record: kernel, tensor shape, precision, inner-call batching, GPU/CPU synchronisation boundary, and environment. Repeat both calibrations and target measurements across sessions when making a comparative claim. Even same-session reference rates can drift during a run; they reduce, rather than eliminate, that uncertainty.

Counting the bytes

Counting the bytes a request moves

A byte estimate begins with the tensors a kernel logically consumes and produces. The following counts are convenient nominal traffic and FLOP conventions, not counter measurements. They deliberately omit data reuse, extra intermediates, padding, kernel-specific algorithms and caching effects.

Operation FLOP estimate Nominal bytes (element size \(s\))
Matrix product \((M\times K)(K\times N)\) \(2MNK\) \((MK+KN+MN)s\), counting each input once and output once
Elementwise binary add over \(n\) elements \(n\) \(3ns\) if two inputs and one output are distinct
GELU over \(n\) elements implementation-dependent; Lab assumes \(8n\) \(2ns\) for an input and output
Layer norm over \(n\) elements implementation-dependent; Lab assumes \(8n\) \(2ns\), excluding parameter and workspace traffic
Softmax over \(n\) elements implementation-dependent; Lab assumes \(5n\) \(2ns\), excluding reduction workspace
One-layer decode attention, \(B\) sequences, \(h\) heads, \(T\) cached keys and head size \(d\) \(4BhTd\) for two products \(2BhTds\) for key/value reads alone, excluding queries, outputs and intermediates

For the chosen fp32 conventions, binary add has \(1/(3\times4)\approx0.083\) FLOP/byte, while GELU and layer norm each have a nominal intensity of \(8/(2\times4)=1\), and softmax \(5/8\approx0.625\). Those values lie below a nominal ridge point near \(6.4\,\mathrm{TFLOP/s}/305\,\mathrm{GB/s}\approx21\) FLOP/byte. That suggests memory pressure once execution overhead and kernel-specific inefficiencies cease to dominate; it does not establish memory bandwidth saturation from intensity alone. Fused multi-operation kernels can have different byte counts and much higher intensity.

These counts can understate physical traffic if a kernel makes copies or spills intermediates, but they can also overstate off-chip traffic if values reside in caches. Accordingly, a nominal byte count divided by a DRAM bandwidth probe is not always a strict time bound. Later experiments should pair the model with profiler-reported memory transactions when available. The batch experiment below tests—and rejects—one proposed extra-copy explanation, not the general possibility of hidden traffic.

58 predictions

cmd_model() runs 29 operation shapes in each of fp32 and fp16: thin and square matrix products, vector add, GELU, layer norm and softmax, for 58 cases. It calculates a prediction from class-specific reference floors and a new measure_ceilings() calibration, then times each operation with CUDA events. The source records two separate command runs; individual operation timings use batches of calls to amortise submission effects. This is evaluation on related shapes, not a held-out prediction set independent of the calibration machinery.

The evaluation statistic is \(r=t_{\mathrm{measured}}/\hat t\). A value of one means agreement; above one means unexplained time; below one means that the calibrated estimate was too high. Here within_25_percent is explicitly defined by the code as \(0.8\le r\le1.25\), and within_2x as \(0.5\le r\le2\). The faster_than_bound counter means \(r<0.95\) and should be read as below the model estimate, not as proof of physical impossibility.

Summary over 58 cases Run 1 Run 2
Median measured / estimated time 1.14 1.10
Within the code’s 0.8–1.25 band 60% 74%
Within a factor of two 100% (58/58) 95% (55/58)
More than 5% faster than estimate 16% 10%

Grouping the same cases by the term that dominates the model—not by counters showing actual hardware saturation—gives:

Model’s dominant term Cases (run 1 / run 2) Median measured / estimated More than 5% below estimate
Memory 29 / 28 1.21 / 1.13 0% / 0%
Compute 12 / 12 1.09 / 1.07 25% / 17%
Launch 17 / 18 1.02 / 1.08 35% / 22%

Seven cases from the first recorded run illustrate the spread. The regime column is the model’s assigned class; prediction and measurement use the same time unit.

Operation Measured Estimated Assigned class Measured / estimated
1×768 @ 768×3,072 (fp32) 34 µs 31 µs memory 1.11
1×768 @ 768×50,257 (fp32) 644 µs 504 µs memory 1.28
512×768 @ 768×3,072 (fp32) 355 µs 382 µs compute 0.93
4,096² (fp32) 21.97 ms 21.73 ms compute 1.01
Add, 134 M elements (fp32) 6.83 ms 5.25 ms memory 1.30
Layer norm, 16,384×768 375 µs 328 µs memory 1.14
Layer norm, 1×768 12.3 µs 7.9 µs launch 1.57

The model explains many of these operations to within tens of per cent, especially those it labels memory-dominated. None of that group’s measurements fell more than five per cent below their estimates in these two runs. Other cases did: the first run’s fastest-to-estimate ratio was about 0.68, and the second contained three cases outside a factor of two. Apparent bound violations may arise from a reference kernel slower than the evaluated kernel, approximate operation counts, caching or noisy timing. It is unsafe to conclude that a bandwidth ceiling is conclusively correct, or that CPU launch state alone explains short-kernel discrepancies, from these classifications.

These measurements are small PyTorch operations executed in isolation, most as batches between CUDA events. They do not include an actual autoregressive loop, CPU sampling, model input/output transport, memory allocation under concurrency, or serving-level queueing. All 58 shapes were chosen by the experimenter, many to resemble GPT-2; a useful next test would freeze the ceilings and parameters, then evaluate held-out shapes and another device. The result is a diagnostic baseline, not an externally validated performance predictor.

The composition fails

The deliberately harder test is composing many operators into one cached decode step. cmd_batch() uses Key-Value Caching’s unfused hand-written GPT-2 forward pass, fp32 weights, a static cache and an initial 128-token prefix. Each timed iteration extends the cache by one position for every sequence in the batch. The sweep uses synthetic token IDs and ten wall-clock timings per batch, synchronising the GPU after each pass. It is a model-step benchmark, not end-to-end text-generation throughput.

The initial model counts approximately 475 MiB of weight tensors, 128 cached positions per sequence at \(73{,}728\) fp32 KV bytes per position, and the modeled per-token FLOPs. It divides combined nominal bytes and FLOPs by reference throughput, and takes the maximum with the measured batch-1 step latency of 8.3–8.5 ms. That batch-1 term is an empirical calibration, not a pure kernel launch measurement. The predicted time stays at that observed floor through batch 128, then rises near batch 256. The cache itself grows during each run, so the nominal fixed-context calculation is an approximation.

The recorded median per-step times and corresponding throughput proxy \(B/t_{\mathrm{step}}\) are:

Batch Measured step time Tokens/second proxy Max-of-totals estimate Measured / estimated
1 8.3–8.5 ms 118–121 8.3–8.5 ms 1.0 (calibrated)
8 9.8–10.3 ms 774–816 8.3–8.5 ms 1.2
32 9.1–9.9 ms 3,224–3,523 8.3–8.5 ms 1.1–1.2
64 11.7–12.4 ms 5,160–5,470 8.3–8.5 ms 1.4–1.5
128 18.0–21.3 ms 5,997–7,117 8.3–8.5 ms 2.1–2.6
256 30.5–33.4 ms 7,673–8,406 9.9–10.1 ms 3.1–3.3
512 87.9–96.0 ms 5,331–5,823 19.8–20.1 ms 4.4–4.8

The practical observation is that batching can dramatically increase the number of sequences advanced per second without increasing step time in proportion to batch size. At batch 32, measured latency was only about 7–20% above the batch-1 result while the proxy throughput was roughly 27–30 times as high. The largest proxy throughput in this sweep occurred at batch 256, roughly 7,700–8,400 token positions advanced per second, before falling at batch 512. This is not a measured serving throughput with variable arrivals, sampling or response streaming. It is a throughput/latency trade-off for this specific forward implementation, context and GPU.

The max-of-totals estimate stays near its baseline for too long and underestimates the larger batches. A single maximum permits all the model’s work to overlap as though it were one perfectly fused operation. But the actual model executes a sequence of different kernels. Two follow-up checks help explain the limits of that simplification; neither establishes the remaining cause.

Add model components that execute serially. As a stronger diagnostic, the analysis separately estimates weight-matrix work and cached-attention traffic, then adds their terms where the work cannot overlap. The resulting estimates are about 8.9 ms at batch 128, 17.8 ms at 256 and 35.6 ms at 512, versus measured ranges of 18.0–21.3, 30.5–33.4 and 87.9–96.0 ms respectively. The gap is still 2.0–2.4×, 1.7–1.9× and 2.5–2.7×. The recorded batch_composed_prediction is a post-hoc analytical calculation, not a separately implemented, unit-tested per-kernel instrumentation pipeline. A complete per-kernel sum would also need the layer norms, activations, biases and their launch costs.

Test one possible hidden cost. StaticCache returns slices of a larger preallocated tensor. A single-layer test at batch 256 compared attention using those views with attention using contiguous copies: 0.754 ms versus 0.766 ms, against a nominal 0.665 ms memory-time estimate. The views were not slower in that case. This observation argues against an expensive implicit copy for the tested shape; it does not prove that no copy, other layout penalty or additional traffic occurs in the full model.

The rest remains unassigned. Candidates include unfused elementwise operations and bias additions, imperfect GEMM and attention occupancy, cache reuse assumptions, allocator pressure, clock/power changes and scheduling. The large throughput decline at batch 512 was not profiled. At batch 256, the 30–33 ms measured step is much larger than even the improved 17.8 ms estimate; describing the difference as a precise percentage of actual GPU time would imply a measurement the experiment did not make. It is a gap between a coarse model and a wall-clock observation.

Moving the dots

Moving the dots: from model to measurement

The next question is which changes should be worth trying. The model suggests a direction but does not settle the result: fusion may cut intermediate traffic and launches; narrower dtypes may reduce byte counts; batching may amortise weights and issue costs; attention tiling may remove unnecessary materialisation. Two small experiments demonstrate the principle under controlled shapes without claiming an end-to-end model speedup.

Fusion reduces intermediate traffic. In this experiment, (x * y) + z is evaluated as two PyTorch operations, while torch.addcmul(z, x, y) expresses the fused computation. Under the simple assumption that each operand is read once and each result written once, the separate form moves six tensor-length units and the fused form four—a predicted traffic ratio of 1.5. Both were measured on 67,108,864 elements (64 Mi elements), with CUDA-event timings.

Precision Separate operations torch.addcmul Speedup Nominal fused throughput
fp32 5.89 ms 3.70 ms 1.59× 290 GB/s
fp16 2.82 ms 1.83 ms 1.54× 293 GB/s

The observed 1.54–1.59× improvement is close to the 1.5× nominal-traffic argument. Dividing the modeled fused traffic by elapsed time gives about 290–293 GB/s, near the reference reduction rate. These are not measured off-chip bytes, and a difference from the predicted 1.5× may reflect caching, instructions, clocks or kernel choice. The conclusion is narrow but useful: for this memory-intensive elementwise expression, eliminating an intermediate substantially improved throughput.

Lower precision reduces nominal bytes, subject to numerical correctness. The same expression took about 2.09× less time in fp16 than in fp32 when unfused and 2.02× less when fused, broadly consistent with the tensors occupying half as many bytes. That is a speed measurement, not an accuracy test; it does not establish that an arbitrary model can switch precision without changing its output or that every memory-bound kernel scales exactly with byte width. Quantization and Numerical Precision must evaluate the numerical trade-off independently.

These levers can affect more than one term at once, and their benefit depends on the actual bottleneck and execution shape:

Lever First-order cost effect Evidence and limitation
Larger batch Amortises weight reads and issue work over more tokens; raises compute and KV work This chapter measures a throughput gain followed by a drop at batch 512
KV cache Removes recomputation but stores and rereads keys and values Key-Value Caching, validated on a bounded GPT-2 workload
Narrower weights or cache Reduces nominal bytes; may alter kernels and numerical outputs Matrix Multiplication and GPU Execution’s precision tests; Quantization and Numerical Precision and later must test inference accuracy
Fusion Eliminates launches and intermediate reads/writes This chapter tests one elementwise expression only
Compilation and execution graphs Can reduce host dispatch and replay costs Hypothesis to test in Compilation and Execution Graphs
Block-wise attention Reduces intermediate storage and slow-memory traffic Attention and Its Computational Cost and FlashAttention and Optimized Kernels; backend-specific performance

A change to a non-dominant term may have little effect, but categorical statements such as “quantisation cannot help a launch-bound step” are too strong: changing dtypes can also change kernels, instruction paths or launch counts. Treat the largest estimate as a prioritisation hint. First establish an output-accuracy requirement, then predict a cost shift, implement the candidate, measure total request latency and throughput, and keep or reject the change based on evidence.

A procedure

A practical diagnostic protocol for an operation or step is:

  1. Define the timing boundary. Decide whether the target is a CUDA-event kernel interval, a synchronised model step, or client-observed request latency; do not compare unlike boundaries.
  2. Calibrate with the experiment. Record hardware, software, clocks where available, precision, warm-up, batching, data shape and reference rates. Repeat calibration across sessions for important claims.
  3. Model nominal work. Count FLOPs and minimum logical tensor bytes; identify any known cache reuse, workspace or non-GEMM operations omitted.
  4. Compute and label the three estimates. Use predict_time to name the dominant modeled term, without asserting measured saturation.
  5. Compare against distributions. Report measured/estimated ratio, representative spread and violations of the nominal estimate. A ratio around 1.3 may be useful but is not a universal acceptance threshold.
  6. Instrument the missing work. If the gap persists, obtain per-kernel timings, allocations and hardware counters where possible; separately test candidate explanations.
  7. Validate the optimisation. Measure numerical parity and complete-step throughput/latency, not just isolated kernel speed.

Hardware performance counters were not available for this run, and the PyTorch profiler used in Matrix Multiplication and GPU Execution recorded no CUDA activity on that Windows setup. Consequently the chapter cannot report measured memory-controller bytes, occupancy, individual kernel launch counts or a decomposition of the 30–96 ms batched steps. The model can identify questions worth asking, but its assignments of “memory” and “compute” are not substitutes for those counters.

What the numbers do not show

  • One consumer GPU under Windows WDDM. Calibration and model measurements share the hardware but have different short-call behaviour across sessions.
  • Two full model runs, not repeated qualification across hardware. The 58-case score is descriptive; no held-out devices or kernels were tested.
  • Event batches versus synchronised steps. Isolated operators are timed with CUDA events over repeated calls; cached batch steps use host wall time with GPU synchronisation.
  • Empirical, not rigorous, bounds. The byte counts assume logical reads/writes; achieved GEMM and reduction rates are references, not certified maxima.
  • Unfused hand-written GPT-2. The batch sweep uses fp32, one initial context (128), a static cache and synthetic token IDs; no token selection or client transport is timed.
  • Missing profiler counters. The large-batch gap, the 1 GiB copy anomaly and the fall in throughput at 512 sequences remain unexplained.
  • No end-to-end numerical or quality comparison for fusion. The elementwise experiment is not evidence that an fp16 language model would preserve its outputs.

Inference Lab increment

The Lab now has:

  • predict_time, classify, matmul_flops_bytes, elementwise_flops_bytes, decode_step_bytes, decode_step_flops and ratio_summary. The unit tests exercise these pure helpers with illustrative values.
  • measure_ceilings(), which measures three access patterns, fp32/fp16 large GEMMs and small-operation reference timing floors; it must be rerun for a new environment.
  • model, batch and fusion commands in examples/ch11/bottlenecks.py, with stored results in research/ch11/results.json. Their GPU benchmarks are not exercised by the pure-helper test suite.
  • A research-backed hypothesis: predict which class of cost should change, then verify with an isolated measurement and a complete-step result. The work still needs automated environment capture and robust regression gates before it can claim that predictions transfer.

The new acceptance rule is: a performance claim identifies the modeled term, the testable prediction, the measured scope and its uncertainty. For example, “fusing this 64 Mi-element expression reduced the nominal number of tensor-length memory passes from six to four; expected 1.5×; observed 1.54–1.59× on this GPU” is a defensible claim. It should not be shortened to “fusion always gives a 1.5× speedup.”

What you should now be able to do

  • Construct the launch, bandwidth and arithmetic terms and distinguish the Lab’s empirical estimate from a strict hardware lower bound.
  • Compute nominal FLOPs, bytes, intensity and ridge point while stating which intermediates and memory hierarchy effects are excluded.
  • Measure reference rates with appropriate synchronisation and recognise the differences between CUDA-event batches and whole-step wall time.
  • Interpret measured/predicted ratios, including cases where an operation finishes faster than the estimate.
  • Explain why one maximum over aggregate bytes and FLOPs can underpredict a sequence of kernels whose costs do not overlap.
  • Quantify the measured throughput/latency trade-off of batched GPT-2 on the tested hardware without implying production server throughput.
  • Predict and verify the benefit of eliminating an intermediate tensor in an elementwise expression.
  • Identify a candidate optimisation and design an experiment that could disprove the expected improvement.

Key terms

  • Modeled launch-, memory-, compute-dominated: whichever of the three estimated costs is largest; not proof of an observed hardware stall.
  • Reference bandwidth: achieved throughput on a documented access-pattern probe, used to calibrate a model.
  • Reference arithmetic rate: best observed GEMM throughput at a precision and selected sizes, not a hardware guarantee.
  • Nominal bytes: logical tensor traffic counted from shapes; distinct from measured DRAM transactions.
  • Estimated floor: the maximum of calibrated issue, byte-time and arithmetic-time estimates.
  • Fusion: combining operations to avoid some intermediate tensors and launches.
  • Arithmetic intensity: modeled FLOPs per counted byte; depends on the choice of counted traffic.
  • Ridge point: compute reference rate divided by bandwidth reference rate.
  • Event-batched timing: elapsed GPU-event time across repeated calls, divided by the number of calls.
  • Composed-step gap: measured time not explained by the current aggregate or partial component model.

Reader exercises

  1. Run ceilings in multiple fresh processes and compare the four small-operation floors, bandwidth probes and fp32/fp16 GEMM rates. Record GPU and CPU conditions.
  2. Freeze one set of calibration values and test on ten held-out matrix and elementwise shapes. How much do error rates change from the 58-case evaluation?
  3. Repeat the batch sweep at contexts 128 and 1,024 without exceeding positional or memory capacity. Which nominal costs grow with context and which do not?
  4. Profile a batch-256 forward step to attribute elapsed time to matrix products, KV attention, layer norm, GELU, bias operations and synchronisation. Can the unexplained gap be reduced?
  5. Repeat batch 512 with several clock, temperature and memory traces. Is the throughput decline reproducible, and can any proposed cause be ruled out?
  6. Reproduce the fusion test in fp16 and fp32, and verify its numerical result against a higher-precision reference as well as measuring time.
  7. Extend the model to more than one device. Add measured communication, collective-operation launch and synchronization terms and state which can overlap.
  8. Compare end-to-end generation with and without one proposed optimization while fixing output sequence, token limit, batch and precision policy.

References

  1. Williams, Waterman & Patterson (2009), Roofline: An Insightful Visual Performance Model for Multicore Architectures. Primary research establishing the compute-and-bandwidth model; it does not supply the chapter’s GPU timing values.
  2. Pope et al. (2023), Efficiently Scaling Transformer Inference. Primary research modelling transformer inference memory and arithmetic costs, including weight and KV traffic; its TPU results must not be transplanted to this GPU.
  3. Dao et al. (2022), FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. Primary research demonstrating how execution structure and intermediate memory movement change performance; the FlashAttention kernel was not measured here.
  4. NVIDIA, Deep Learning Performance: Matrix Multiplication. Vendor documentation for shape, arithmetic intensity and hardware utilisation; a technical guide rather than a primary research paper.
  5. PyTorch, CUDA semantics. Framework guidance on asynchronous execution and correct timing methodology.

Evidence in this chapter

Claim Evidentiary status and limitation
The roofline relates throughput to arithmetic intensity and bandwidth Established theory: Williams et al.; chapter adds a heuristic issue-time term
The largest of three terms is a strict hard lower bound for every PyTorch operation Not established: empirical bandwidth, peak and issue references can overestimate minimum time
Reduction probe reached ~305 GB/s, copy ~279 GB/s in these runs Recorded nominal-throughput measurements; not memory-controller counters
Small-operation observed floors changed from ~35 µs in Matrix Multiplication and GPU Execution to ~12–14 µs here Recorded across sessions; cause not isolated
58 tested operations had median measured/estimated ratio 1.10–1.14 Book experiment, two runs; 58 specified cases per run
Zero memory-classified cases beat the estimate by >5% Book experiment, classification-specific; not a hardware theorem
Batched step reaches ~7,700–8,400 token advances/s at batch 256 then falls at 512 Book experiment: fp32, GPT-2, static cache, synthetic tokens, no server
Max-of-totals estimate misses batch 256 by 3.1–3.3× Book experiment, including batch-1-calibrated latency floor
Partial composed-cost analysis reduces but does not close the large-batch gap Post-hoc model comparison, not measured per-kernel attribution
A non-contiguous KV view caused a triple-traffic copy Proposed explanation not supported by the single-layer contiguous-control test
Fusion of the tested expression gives 1.54–1.59× Book experiment on one operation and two dtypes; nominal traffic estimate
Actual cause of the batch-512 regression, achieved occupancy, cache transactions Not measured or established