← Inference From First Principles

Attention and Its Computational Cost

Attention is quadratic in arithmetic, but what hurts first is the score tensor. Measured memory, time and bandwidth for prefill-shaped and decode-shaped attention.

For 16,384 positions, twelve attention heads and fp16 storage, a single dense attention-score tensor occupies 6.0 GiB. The direct implementation in this chapter reached a recorded 12,568 MiB of additional PyTorch-allocated memory; the forced memory-efficient SDPA backend reached 24 MiB, a difference of about 524-fold in that measurement. Remarkably, the 12,568 MiB allocation succeeded on a machine reporting approximately 12 GiB of GPU memory. That is an allocator observation, not evidence that all those bytes were simultaneously resident in physical VRAM. Separately, on tested sequences of up to 2,048 tokens, both implementations agreed closely with a float64 reference, and at 8,192 tokens the memory-efficient backend was about eleven times faster than the naive implementation in fp16. The 16,384-token case was a memory test, not a numerical-equivalence or timing test.

The crucial difference is where intermediate values live, not a change to the mathematical attention function. Direct attention materialises quadratic score and probability tensors; an IO-aware implementation combines blocks with an online softmax and avoids storing those full tensors in device memory. The arithmetic remains quadratic for dense full-sequence attention, but its temporary storage and memory traffic can be dramatically smaller. The 524-fold figure above refers to the measured additional PyTorch allocation at one shape, not total model memory or a universal speedup.

This chapter follows the same calculation through three lenses: arithmetic, temporary memory and wall-clock time. It treats prefill—many query positions against a known prefix—separately from cached decode, where one new query attends to previously computed keys and values. Those shapes have different performance limits, even though they use the same attention rule. All GPU figures below are for one recorded Windows/PyTorch environment, not general hardware constants.

Where this sits

The Transformer as a Computation showed why attention is the operation that mixes information between token positions, and why a naive attention-score or probability matrix grows quadratically with sequence length. Autoregressive Generation distinguished the parallel scoring of known tokens from serial generation decisions. Matrix Multiplication and GPU Execution introduced arithmetic intensity and the roofline bound. We now connect those ideas: an operation can have moderate arithmetic cost yet be slow because it moves large intermediates, and a faster kernel may save memory traffic without reducing the asymptotic FLOP count.

The Inference Lab adds the testable arithmetic and storage helpers attention_flops, score_bytes and kv_bytes, and a comparison harness for naive attention and explicitly requested PyTorch SDPA backends. Correctness checks use a float64 implementation on the same already-rounded inputs, while GPU experiments separately record timings and PyTorch allocator peaks. The new measurement rule is specific: record the device, framework version, input shape, dtype, causal setting and actual selected or forced backend. A call to scaled_dot_product_attention is an API request; without backend evidence, it does not identify a kernel.

For the Pi series, context length is a design decision shared by retrieval, memory and serving. Adding retrieved material increases the prompt length and can improve the information available to the model, but it also increases prefill work and the state retained for decode. Retrieval and persistent memory help when they select useful context rather than simply adding more tokens. The formulas here quantify some hardware consequences of that choice; they do not measure retrieval quality or justify truncating useful evidence.

What is being computed

Attention: the cost of writing down the scores

For one attention head, let queries be \(Q \in \mathbb{R}^{T_q \times d}\), keys \(K \in \mathbb{R}^{T_{kv} \times d}\), and values \(V \in \mathbb{R}^{T_{kv} \times d}\). Here query/key and value head widths are equal, as in the GPT-2-shaped experiments. The mask \(M\) assigns \(-\infty\) to disallowed key positions; softmax is taken across the key dimension of each query row:

\[ S = \frac{QK^\top}{\sqrt{d}} + M, \qquad P = \operatorname{softmax}(S), \qquad O = PV \]
There are two matrix products and one row-wise softmax. Both the score matrix \(S\) and probability matrix \(P\) have shape \([T_q,T_{kv}]\) per head. Forming \(QK^\top\) costs approximately \(2T_qT_{kv}d\) FLOPs and multiplying \(PV\) costs another \(2T_qT_{kv}d\). With \(B\) sequences and \(h\) heads, the **dense matmul count** is therefore:
\[ \text{FLOPs} = 4\,B\,h\,T_q\,T_{kv}\,d \]
For causal self-attention on a full sequence of \(T\) positions, only \(T(T+1)/2\) query–key pairs are *logically permitted*. An implementation that skips masked pairs can approach half the dense matmul work; one that computes the full square matrices and masks afterwards does **not** receive that saving. The chapter's `attention_flops(..., causal=True)` reports the ideal triangular count, whereas `naive_attention` executes dense products. Softmax, masking, kernel launches and data movement are omitted from that FLOP formula and can still dominate elapsed time.

The two shapes are:

Phase Query length \(T_q\) Key/value length \(T_{kv}\) Dense matmul growth Dense scores per head
Prefill of a known prompt \(T\) \(T\) \(O(T^2 d)\) \(T \times T\)
Cached single-token decode 1 \(T\) \(O(Td)\) \(1 \times T\)

The second row assumes a valid KV cache and a new query at the end of the prefix; it is not the cost of the deliberately uncached loop from Autoregressive Generation–Building Our First Inference Engine–Matrix Multiplication and GPU Execution. In that single-query case all supplied keys are eligible, so the isolated decode experiment passes is_causal=False.

Doubling \(T\) quadruples dense prefill attention products and doubles one-query cached attention products, as the unit tests verify. This describes attention, not the whole model: projections, feed-forward layers and the output vocabulary projection add substantial work. The Transformer as a Computation’s 13% figure is for its last-position per-token matmul cost model at a context of 1,024, not the average attention share of a whole prompt’s forward pass. The ratio changes when counting all prefill positions or when using a kernel that exploits triangular causality.

The cost of writing down the scores

The direct formula creates scores, optionally applies a causal mask, applies softmax to obtain probabilities, and multiplies by values. A simple eager implementation can materialise multiple large intermediate tensors; a fused implementation can avoid doing so. The lower-bound size of one fp16 score or probability array with batch size 1 and twelve heads is:

\(T\) One score tensor (fp16)
512 6 MiB
1,024 24 MiB
2,048 96 MiB
4,096 384 MiB
8,192 1.5 GiB
16,384 6.0 GiB

Each doubling of sequence length quadruples the storage of a materialised square attention tensor; batch size scales it again. The direct implementation’s peak is close to the storage of two such arrays once they dominate smaller allocations, but the exact peak is implementation-dependent. The following measurements report torch.cuda.max_memory_allocated() minus the allocated baseline after Q, K and V were created. They are extra tracked allocations during the call, not total GPU-process memory, physical VRAM occupancy or measured memory-controller traffic:

\(T\) Naive peak extra SDPA math peak extra SDPA memory-efficient peak extra
512 21 MiB (3.52 score tensors) 34 MiB (5.67) 0.75 MiB
1,024 50.5 MiB (2.10) 124 MiB (5.17) 1.5 MiB
2,048 200 MiB (2.08) 472 MiB (4.92) 3 MiB
4,096 790 MiB (2.06) 1,840 MiB (4.79) 6 MiB
8,192 3,148 MiB (2.05) 7,264 MiB (4.73) 12 MiB
16,384 12,568 MiB (2.05) 28,864 MiB (4.70) 24 MiB

Parenthesised values divide the allocator peak by the size of one dense fp16 score tensor from the preceding table. Measurements are for batch 1, 12 heads, head dimension 64, with already-allocated inputs excluded.

The naive measurement approaches about 2.05 score tensors of extra tracked allocation; the forced SDPA math backend approaches about 4.70, which reflects additional precision and workspace choices in this build. By contrast, the memory-efficient backend’s measured extra allocation equals its fp16 output size: \(12 \times T \times 64 \times 2\) bytes, or 24 MiB at 16,384 tokens. That does not prove the kernel has no on-chip or temporary workspace, only that no quadratic extra allocation was visible to this PyTorch allocator measurement. IO-aware exact-attention methods retain per-block softmax statistics, such as a running maximum and normaliser, and combine partial results without globally materialising the dense score matrix. The cited algorithms establish the principle; these measurements establish what this backend allocated here.

There is an unresolved platform question in the largest rows. PyTorch reported 12,568 MiB and 28,864 MiB of additional allocated tensors even though torch.cuda.get_device_properties() reported roughly 12 GiB of total device memory, and the operations completed. WDDM-managed GPU memory oversubscription is a plausible explanation, but the experiment did not record resident VRAM, page faults or transfers to system RAM; the allocator counter alone cannot establish a paging mechanism. No timing or numerical comparison was made for these largest allocations. Do not infer that a 12 GiB card can sustain a 28 GiB attention workload at normal speed or that the same allocation would succeed under another driver model.

Which kernel ran

PyTorch’s scaled_dot_product_attention (SDPA) is a semantic interface that can dispatch to different implementations. The harness uses sdpa_kernel([SDPBackend.<name>]) to constrain the candidates, and records whether each call succeeds for the chosen test shape (batch 1, twelve heads, head dimension 64, sequence 256). These are availability tests under this environment, not exhaustive claims about support for every shape, precision or PyTorch release:

Backend fp16 fp32
Math runs runs
Memory-efficient runs runs
FlashAttention unavailable: no kernel unavailable
cuDNN attention unavailable unavailable

For the recorded PyTorch 2.6.0+cu124 Windows build on an RTX 2060 (compute capability 7.5), forced math and memory-efficient SDPA both ran in fp16 and fp32. Forced FlashAttention and cuDNN attention returned no available kernel. The run’s diagnostic notes attribute the former to the build lacking FlashAttention support and the latter to capability restrictions; the saved availability table itself records only the failure message. No timings in this chapter are measurements of the FlashAttention backend. The memory-efficient backend demonstrates the same broad IO-aware strategy, but should not be assigned FlashAttention’s implementation details or performance claims.

Backend choice is part of the experimental identity. It may depend on PyTorch version/build, device capability, dtype, head dimension, mask, dropout and shape. A report that says only “SDPA” does not establish which path executed. The isolated tests below explicitly force their backend; the whole-model attn_implementation="sdpa" run does not separately capture the kernel dispatched at each layer. Treat those two levels of evidence differently.

Same answer?

Correctness was checked on sequences of length 64, 512 and 2,048, with twelve heads of width 64. For each dtype, the harness first creates Q, K and V in that dtype, converts those already-rounded operands to float64, and computes the direct causal formula as a reference. It then measures the maximum absolute output-element difference from that reference. Thus the comparison isolates implementation/accumulation differences given those operands; it does not measure the original input quantisation error or validate the 8,192- and 16,384-token outputs:

Precision Length Naive Math Memory-efficient
fp32 64 \(8.3 \times 10^{-7}\) \(1.0 \times 10^{-6}\) \(8.9 \times 10^{-7}\)
fp32 2,048 \(7.1 \times 10^{-7}\) \(7.1 \times 10^{-7}\) \(9.4 \times 10^{-7}\)
fp16 64 \(1.6 \times 10^{-3}\) \(9.7 \times 10^{-4}\) \(9.8 \times 10^{-4}\)
fp16 2,048 \(1.8 \times 10^{-3}\) \(9.7 \times 10^{-4}\) \(9.7 \times 10^{-4}\)

In this sample, maximum absolute errors are roughly \(10^{-6}\) for fp32 and \(10^{-3}\) for fp16, relative to the corresponding float64 computation on the same stored inputs. The naive fp16 path is less accurate than both tested SDPA paths by this measure, consistent with extra rounding of explicit intermediate tensors. PyTorch documents that its math SDPA backend can keep intermediates in a higher-precision type; the memory-efficient kernel’s exact internal arithmetic was not inspected here. Neither the error scale nor the close outputs prove bitwise identity, calibration or correctness on trained-model activations with unusual numerical ranges.

Time

The following timings use the Matrix Multiplication and GPU Execution CUDA-event harness after a device warm-up, with three recorded runs on the same GPU. Values are milliseconds for causal, batch-1, twelve-head attention with random inputs; the efficient column is PyTorch’s forced EFFICIENT_ATTENTION backend, not FlashAttention. The available repetition evidence shows good agreement for these runs, but the broader clock and display-driver variability from Matrix Multiplication and GPU Execution still applies:

\(T\) fp16 naive fp16 efficient fp32 naive fp32 efficient
512 0.29 ms 0.04 ms 0.55 ms 0.16 ms
1,024 1.07 ms 0.14 ms 2.18 ms 0.52 ms
2,048 5.71 ms 0.43 ms 8.83 ms 1.79 ms
4,096 18.7 ms 1.52 ms 33.3 ms 6.74 ms
8,192 67.0 ms 5.97 ms 155.8 ms 26.0 ms

For the measured range, both implementations follow approximately quadratic growth. Fits over \(T \ge 1{,}024\) yielded exponents of 1.96 (fp16 naive), 2.04 (fp32 naive), 1.82 (fp16 efficient) and 1.88 (fp32 efficient). These are empirical slopes over four sequence lengths, not asymptotic complexity proofs. The memory-efficient path retains quadratic arithmetic while improving parallelism and reducing global-memory traffic; its attained throughput rose across this range. At \(T=8{,}192\), fp16 fell from 67.0 ms (naive) to 5.97 ms (efficient), a measured 11.2× improvement for this shape and device—not a whole-model or production-serving speedup.

Using the ideal causal triangular FLOP count, the efficient fp16 run at \(T=8{,}192\) corresponds to 17.3 TFLOP/s, while naive attention corresponds to roughly 1.5 TFLOP/s. Interpret those carefully: the naive code actually forms dense query–key and probability–value products, so dividing its time by the triangular count understates its executed matmul arithmetic. A hand estimate assigns several reads and writes to the large score/probability arrays: \(12 \times 8{,}192^2\) elements multiplied by roughly 12 bytes of fp16 traffic per element gives about 9.7 GB. At a separately measured 278 GB/s copy rate, that transfer alone would take about 35 ms, versus the observed 67 ms naive time. This is an illustrative traffic model, not a memory-controller measurement or a decomposition of the kernel’s actual runtime; cache reuse, temporary precision, launches and dense matmuls remain unmeasured confounders. The defensible conclusion is that avoiding quadratic intermediates is highly valuable here.

What the causal mask saves

The causal mask: prefix reuse

Causality prohibits future keys, so the number of permitted query–key pairs is \(T(T+1)/2\), approximately half of full attention’s \(T^2\). That is a logical workload reduction only for a kernel that can skip masked work. The measured causal-to-unmasked time ratios for fp16 at three lengths were:

Implementation Causal time over full time (T = 1,024 / 2,048 / 4,096)
Work ratio (arithmetic) 0.50
Memory-efficient kernel 0.71 / 0.59 / 0.58
Math backend 1.27 / 1.32 / 1.30
Naive implementation 1.69 / 1.68 / 1.74

The efficient backend benefits increasingly from causal structure, reaching 0.58 times the unmasked runtime at \(T=4{,}096\); its implementation can avoid much of the masked region. In the tested math and explicit naive implementations, causal processing was slower (ratios about 1.27–1.32 and 1.68–1.74) because the dense operations still occurred and masking added work. These measurements reveal implementation behaviour at these shapes, not a universal rule that causal masking makes attention slower or faster.

A causal mask specifies which information may flow. It does not, by itself, specify how many operations the backend executes. When estimating latency, distinguish the masked mathematical function, the ideal count of valid pairs, and the matmuls or blocks actually scheduled by the kernel.

In the whole model

The isolated attention benchmark is not the whole transformer. To check whether its advantage survives surrounding layers, the experiment loaded Hugging Face GPT-2 small twice, selecting attn_implementation="eager" and attn_implementation="sdpa". It compared float32, batch-1 forward passes at three lengths on the same GPU. The model configurations report those two interfaces; the experiment did not independently record the exact CUDA SDPA backend chosen inside each model layer:

Tokens Eager median SDPA median SDPA time reduction Eager peak extra SDPA peak extra Max absolute logit difference
128 7.64 ms 7.11 ms 6.9% 33.9 MiB 33.9 MiB \(9.2 \times 10^{-5}\)
512 31.10 ms 26.84 ms 13.7% 147.7 MiB 148.2 MiB \(1.1 \times 10^{-4}\)
1,024 71.43 ms 54.74 ms 23.4% 272.3 MiB 271.3 MiB \(1.4 \times 10^{-4}\)

The relative timing benefit grows with sequence length but remains a fraction of one full forward pass, not the isolated attention kernel’s elevenfold speedup. The two measured peaks were similar, not identical. One important contribution is the output logits tensor: at \(T=1{,}024\), \(1{,}024\times 50{,}257\times4\) bytes is about 206 MB (196 MiB). That is roughly 72% of the 272 MiB peak extra allocation, though the allocator peak is not simply a sum of permanent tensors and does not prove which allocations overlapped. GPT-2 returns logits for every input position; an autoregressive loop usually needs only the final row at that step. Attention’s quadratic intermediates may therefore be hidden in this particular whole-model peak by output projection and other allocations. The experiment did not implement or measure last-row-only logits.

The correct conclusion is shape-dependent. In GPT-2 small at its maximum supported context of 1,024 tokens, the observed whole-model allocation is not dominated by attention alone. At 16,384 positions, the isolated attention benchmark demonstrates the cost that an explicit quadratic tensor would incur—but GPT-2 small cannot be run at 16,384 positions unchanged, because its learned position-embedding table supports only 1,024. For a long-context model, the largest allocation depends on sequence length, vocabulary size, attention implementation, dtype, batch size and what outputs the API retains. Inspect the runtime and measure rather than extrapolating this model’s peak.

The other shape: one query, many keys

Decode: one query, many keys

In a KV-cached generation step, the new token contributes one query per attention head and attends over its permitted prefix, including itself. Earlier keys and values can be reused if the model, position handling and cache state remain consistent. The attention product for that layer is therefore a \(1\times T\) problem, costing approximately \(4hTd\) matmul FLOPs for a single sequence when key and value head widths both equal \(d\)—about 3.15 million FLOPs at \(T=1{,}024\), \(h=12\), \(d=64\). This excludes projections, softmax and other layers. The Chapter 8 decode command benchmarks isolated attention against synthetic cached-shaped K/V tensors; it does not implement or time a complete cached GPT-2 engine, which comes in Key-Value Caching.

The storage of a full KV cache, not necessarily the bytes physically fetched in one step, follows from the number of layers, key/value heads and stored positions. For GPT-2 small at batch 1 in fp16, with twelve layers and twelve KV heads of width 64:

\[ \text{bytes} = 2 \times 12 \times T \times 768 \times 2 = 36{,}864\,T \]
At \(T=1{,}024\), this is **36 MiB** per sequence; at \(T=4{,}096\), it would be **144 MiB** if this architecture supported that context length. The model's 124,439,808 parameters would occupy roughly **249 MB** at an idealised two bytes per parameter, ignoring buffers, allocator overhead and other state. Comparing cache capacity with weight size is useful, but treating both as bytes *read once on every step* is only a first-order traffic model: actual traffic depends on cache layout, reuse, kernels, precision, batching and the memory hierarchy.
Batch Modelled context \(T\) Full 12-layer KV footprint in fp16 KV footprint / ideal 249 MB weight size
1 1,024 36 MiB 15%
7 1,024 252 MiB 106%
16 1,024 576 MiB 243%
16 4,096 2.25 GiB 970%

These are capacity ratios, not direct measurements of weight or KV-cache bytes transferred during an actual model step. The 4,096-token row is hypothetical for unchanged GPT-2 small.

The modelled full-cache capacity crosses the ideal fp16 weight size at roughly seven concurrent 1,024-token sequences. This tells us where stored KV data becomes larger than the weights and where cache traffic could become competitive. It does not prove that attention overtakes all other compute or traffic at batch seven, nor does it establish a serving-system capacity limit: one weight matrix may be reused across a batch while keys and values are accessed in different patterns. Still, this increasing per-request state explains why paged caches, cache quantisation and grouped-query attention deserve separate chapters. Grouped-query attention reduces the number of stored KV heads without necessarily reducing the query-head count.

The isolated decode experiment applies the forced memory-efficient SDPA backend to one query against \(T\) synthetic keys and values, with batch 1, 16 or 64 and twelve heads of width 64. The reported byte count comes from the input K/V tensor sizes for one layer; the bandwidth column divides that nominal byte count by measured elapsed time. It is effective bandwidth under a one-read assumption, not a hardware counter for actual DRAM transactions:

Batch Context \(T\) Median time Nominal K/V bytes, one layer Effective nominal K/V bandwidth
1 128 25.6 µs 0.375 MiB 15 GB/s
1 1,024 64.7 µs 3 MiB 49 GB/s
1 16,384 1,007 µs 48 MiB 50 GB/s
16 1,024 205 µs 48 MiB 246 GB/s
16 16,384 3,112 µs 768 MiB 259 GB/s
64 1,024 779 µs 192 MiB 258 GB/s
64 16,384 12,226 µs 3,072 MiB 263 GB/s

The batch-64, 16,384-position single-layer input alone uses 3 GiB of K/V tensors; a corresponding twelve-layer full cache would require 36 GiB. The measured microbenchmark should not be mistaken for a full-cache allocation or an end-to-end serving run.

For the longer tested prefixes, elapsed time grows approximately with \(T\), as expected for one query against a growing cache. At batch 16 and 64, the nominal-byte/time rate reaches 246–263 GB/s, approaching Matrix Multiplication and GPU Execution’s measured copy-bandwidth reference; this is consistent with a bandwidth-sensitive kernel under the one-read model, not proof of its hardware bandwidth limit. At batch 1 the nominal rate plateaus near 49–50 GB/s. Limited parallelism over twelve heads is one plausible explanation, supported in general by research on attention work partitioning, but occupancy, memory transactions and kernel scheduling were not measured here. A profiler or an implementation that deliberately splits the key dimension would be needed to test it.

The practical implication is a trade-off rather than “always batch more.” Batching supplies parallel work and can improve the effective use of the GPU, but each active sequence brings its own context, KV capacity, cache accesses and scheduling constraints. Prefill and Decode combines prefill and decode at request level; the later cache and serving chapters test how far these benefits persist when the full model and multiple requests share hardware.

What the numbers do not show

  • No FlashAttention measurement. The forced FlashAttention backend was unavailable in the recorded PyTorch build; all “memory-efficient” timings here are for PyTorch’s EFFICIENT_ATTENTION path.
  • One RTX 2060 under Windows WDDM. Kernel availability, clocks, driver behaviour and possible memory oversubscription may differ elsewhere. GPU residency and paging were not instrumented.
  • PyTorch allocator peaks, not VRAM telemetry. max_memory_allocated() - baseline excludes already-created Q/K/V inputs and does not report physical residency or all kernel-internal storage.
  • Correctness only up to 2,048 tokens. The float64 reference reuses inputs already rounded to the tested dtype. Neither 8,192 nor 16,384 outputs were checked for numerical equivalence.
  • Ideal causal versus executed dense arithmetic. The causal FLOP helper counts permitted pairs; the naive implementation still performs dense matmuls and masks them afterward.
  • Whole-model backend not fully observed. attn_implementation="sdpa" is recorded, but the dispatched kernel inside each GPT-2 layer was not independently captured.
  • Synthetic, isolated decode. The K/V inputs are randomly generated for one layer; no twelve-layer KV-cached engine was benchmarked. Contexts above 1,024 are hypothetical for unmodified GPT-2 small.
  • Calculated effective bandwidth. The decode byte/time ratio uses nominal K/V size, not measured DRAM transactions. The traffic hand count for the naive kernel is likewise an estimate.
  • No alternative masking, GQA or trained-activation sweep. Padding, sliding windows, grouped-query heads and real-model activation outliers can change support and numerics.
  • No measured occupancy or end-to-end serving benefit. The proposed explanation of batch-1 inefficiency remains a hypothesis.

Inference Lab increment

The Lab now has:

  • attention_flops(batch, heads, q_len, kv_len, head_dim, causal), score_bytes(...), kv_bytes(...) and fit_exponent(...): mathematical and allocation-size helpers; causal=True counts the ideal permitted triangle, not necessarily executed operations.
  • naive_attention and sdpa(backend=...): independently callable attention paths, with numerical comparisons to the float64 formula on the same stored inputs.
  • backends, correctness, memory, scaling, causal, decode, cpu and model subcommands: availability probes, allocator peaks, time measurements and selected model comparisons. The large-memory probes intentionally do not time paged/oversubscribed runs.
  • A remaining instrumentation task: store full runtime provenance, verify automatic SDPA dispatch, collect GPU residency/DRAM counters where available, and distinguish output allocations from internal attention workspaces.

The Building Our First Inference Engine acceptance rule therefore acquires two independent gates. First, the candidate must meet a stated numerical tolerance over relevant input shapes, dtypes and causal settings; disagreement must be investigated rather than dismissed as “rounding.” Second, performance comparisons must describe the executed backend, measured timing method and the exact memory metric. A 500-fold reduction in additional allocator memory does not by itself mean a 500-fold decrease in total GPU memory, and a nominal bytes/time ratio is not a measured hardware bandwidth. The Lab now has the tools to ask those questions and an explicit list of which remain unanswered.

What you should now be able to do

  • Derive dense attention FLOPs, the ideal triangular causal count and the executed-dense caveat from \(B\), \(h\), \(T_q\), \(T_{kv}\) and head width.
  • Compute score/probability tensor sizes and full KV-cache storage, with explicit batch, layer, dtype and head-count assumptions.
  • Explain how tiled, online-softmax attention preserves the mathematical function while avoiding a quadratic materialised intermediate.
  • Distinguish torch.cuda.max_memory_allocated() from resident VRAM, process-wide capacity and measured memory-controller traffic.
  • Name the SDPA backend that was actually forced or observed; do not infer the kernel from the API name alone.
  • Interpret absolute error against a reference computed from already-quantised operands, and identify which numerical behaviours remain untested.
  • Compare prefill-shaped and cached-decode-shaped attention, including the consequences for arithmetic, KV capacity and batching.
  • Treat a roofline or effective-bandwidth number as a model with assumptions, not a profiler measurement.

Key terms

  • Score matrix: the \([T_q,T_{kv}]\) array of scaled query–key products for one head; an equally sized probability matrix follows softmax in a direct implementation.
  • Materialise: allocate and store a full intermediate tensor, typically in device/global memory.
  • Prefill attention / cached-decode attention: many queries over a known prompt versus one new query over cached keys and values.
  • KV cache: per-layer stored key and value vectors for previously processed positions.
  • Exact attention: computation of the same mathematical softmax-attention function, allowing numerical differences from rounding or reassociation; not a promise of bitwise equality.
  • SDPA backend: a concrete implementation selected or forced beneath PyTorch’s scaled-dot-product-attention API.
  • Online softmax: combining blocks using running maxima, normalising sums and rescaled partial outputs, without constructing all scores at once.
  • Allocator peak: maximum memory tracked as allocated by the framework, distinct from reserved memory and physical VRAM residency.
  • Effective nominal bandwidth: assumed input bytes divided by measured time; a modelled traffic rate, not a direct measurement of memory transactions.
  • Arithmetic reduction versus IO reduction: skipping masked operations changes the FLOP count; avoiding materialised intermediates primarily reduces memory storage and movement.

Reader exercises

  1. For 32 layers, 32 KV heads of width 128, context 8,192 and fp16, calculate the KV-cache bytes per sequence. Compare that capacity with ideal two-byte storage for seven billion parameters, then state why a capacity ratio is not a measured per-step bandwidth ratio.
  2. Repeat the memory command for 32 heads of width 128. Record peak allocated and peak reserved memory separately; identify any out-of-memory event without assuming that successful allocation proves VRAM residency.
  3. Modify naive_attention to use an explicit materialised block-wise causal mask, then compare its runtime with the original full-square mask. Explain why merely changing the mask construction does not skip the dense matmuls.
  4. Re-run correctness with additional seeds, trained-model activations if available, fp32/fp16 and longer lengths that fit. Report both max absolute and relative error, and state which errors from input quantisation the reference excludes.
  5. Force each SDPA backend on your device; record the failure reason and test explicit boolean masks, dropout and a non-square single-query shape. For decode at the end of a prefix, explain why is_causal=False is used in the isolated one-query experiment.
  6. Profile one decode call at batch 1 and batch 16. Compare nominal KV bytes/time with measured memory traffic or occupancy if your profiler exposes it; otherwise report that the causal hypothesis is untested.
  7. Change the whole-model experiment to return only the last-position logits if your model API permits it, and compare allocated peaks. Distinguish peak-live allocations from the size of the returned logits tensor.
  8. Use the The Transformer as a Computation cost model to derive a context at which ideal attention FLOPs reach half of total per-token FLOPs, and separately estimate the full-prefill average. Explain why the answers differ and why unchanged GPT-2 cannot validate contexts above 1,024.

References

Evidence in this chapter

Claim Category and scope
Dense attention matmuls cost approximately \(4BhT_qT_{kv}d\) FLOPs Established arithmetic, excluding softmax, mask and movement
Causal self-attention permits \(T(T+1)/2\) pairs Mathematical count; not the naive code’s executed dense FLOPs
Exact IO-aware attention can avoid a quadratic materialised score/probability tensor Established by Rabe–Staats and FlashAttention; no FlashAttention kernel was run here
At \(T=16{,}384\), naive and efficient paths recorded 12,568 MiB and 24 MiB extra allocation Book allocator result; not physical VRAM or numerical comparison at that length
Forced math and memory-efficient SDPA ran; FlashAttention and cuDNN paths did not Book availability result on one GPU/build/shape
All three tested implementations closely matched float64 on the same stored inputs up to \(T=2{,}048\) Book numerical result; maximum absolute errors, not model-quality evidence
Memory-efficient SDPA was about 11.2× faster than naive fp16 attention at \(T=8{,}192\) Book microbenchmark result, one hardware environment
Causal masking sped up efficient SDPA and slowed the math/naive paths at tested lengths Book time ratios; depends on actual implementation
Whole GPT-2 SDPA configuration reduced measured time 6.9–23.4% at 128–1,024 tokens Book fp32/batch-1 result; exact dispatched kernels not independently traced
Cached KV storage is 36 MiB per GPT-2-shaped sequence at \(T=1{,}024\) Arithmetic capacity model; batch-seven crossover is not a measured traffic crossover
Isolated decode nominal KV byte/time reaches approximately 246–263 GB/s at batches 16–64 Book derived effective bandwidth; not DRAM counter telemetry
Windows paging, precise physical memory residency, batch-1 occupancy cause and serving benefit Hypotheses or not measured
Output agreement and speed for \(T=16{,}384\); trained activation numerics; GQA; other hardware Not measured