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.
Here is the most dramatic measurement in this chapter. For 16,384 positions, twelve heads and fp16, a single dense attention-score tensor occupies 6.0 GiB. Computing attention the direct way, PyTorch allocated an extra 12,568 MiB. Computing the same attention with PyTorch’s memory-efficient backend, it allocated an extra 24 MiB: about 524 times less.
(These are additional allocations tracked by PyTorch’s allocator during the call, not total GPU memory, so the 524-fold figure is about that allocation at one shape, not total model memory or a universal speed-up. Strangely, the 12,568 MiB allocation succeeded on a card reporting about 12 GiB; we come back to that.)
At shorter lengths both agreed with a float64 reference: up to 2,048 tokens, to about \(10^{-6}\) in fp32 and \(10^{-3}\) in fp16, and at 8,192 tokens the memory-efficient backend was about eleven times faster in fp16. (The 16,384-token run was a memory test only; its outputs and timings were not compared.)
How can the same calculation need 500 times less additional allocation at this shape? Because the difference is where intermediate values live, not what is computed. The direct method writes the full \(T\times T\) score and probability matrices to GPU memory. An IO-aware method processes blocks, combines them with an online softmax, and never stores the full matrices. Dense attention still does quadratic arithmetic either way, but its temporary storage and memory traffic can be dramatically smaller.
This chapter looks at attention through three lenses: arithmetic, temporary memory and time. It treats the two shapes separately: prefill, where many queries attend over a known prompt, and cached decode, where one new query attends over stored keys and values. They follow the same rule but hit different limits. All GPU figures come from one recorded Windows/PyTorch environment.
Where this sits
The Transformer as a Computation showed that attention is the only operation that moves information between positions, and that a naive implementation’s score and probability matrices grow quadratically. Autoregressive Generation separated parallel scoring from serial generation. Matrix Multiplication and GPU Execution introduced arithmetic intensity and the roofline. This chapter connects them: an operation can have modest arithmetic yet be slow because it moves large intermediates, and a faster kernel can cut memory traffic without changing the FLOP count.
The Inference Lab gains arithmetic and storage helpers (attention_flops, score_bytes, kv_bytes) and a harness comparing naive attention with explicitly chosen PyTorch backends. It also gains a rule: record the device, framework version, shape, dtype, causal setting and the backend actually used. Calling scaled_dot_product_attention is a request to an API; on its own it does not tell you which kernel ran.
For the Pi series, context length is a design decision shared by retrieval, memory and serving. Adding retrieved material can give the model better information, but it also lengthens prefill and enlarges the state kept for decode. Retrieval and memory help when they add useful context, not just more tokens. The formulas here quantify the hardware side of that choice; they say nothing about retrieval quality.
What is being computed
For one head, with queries \(Q \in \mathbb{R}^{T_q \times d}\), keys \(K \in \mathbb{R}^{T_{kv} \times d}\), values \(V \in \mathbb{R}^{T_{kv} \times d}\), and a mask \(M\) that puts \(-\infty\) on disallowed positions:
| 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\) |
Doubling \(T\) quadruples prefill attention and doubles cached-decode attention, as the unit tests check. (The decode row assumes a valid KV cache and a query at the end of the prefix. It is not the cost of the uncached loop from Chapters 5–7. And because the single query sits at the end, every supplied key is allowed, so the isolated decode experiment passes is_causal=False.)
What the causal mask saves, in principle. Causal self-attention over \(T\) positions only permits \(T(T+1)/2\) query–key pairs, about half of \(T^2\). A kernel that skips the masked pairs can approach half the work. One that computes the full square and masks it afterwards gets no saving. The Lab’s attention_flops(..., causal=True) reports the ideal triangular count; naive_attention actually runs dense products. Keep these apart; we will measure the difference below.
What the count leaves out. Softmax, masking, kernel launches and data movement are not in the formula, and they can dominate the time. Nor is the rest of the model: projections, feed-forward layers and the vocabulary projection add a lot. (The 13% attention share in The Transformer as a Computation was for a single last-position query at context 1,024, not the average share across a whole prompt.)
The cost of writing down the scores
The storage problem. A direct implementation computes scores, applies the mask, applies softmax, and multiplies by values, storing large intermediate tensors along the way. Just one fp16 score or probability array, at batch 1 with twelve heads, needs:
| \(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 length quadruples it, and batch size multiplies it again.
What was actually allocated. The next table reports torch.cuda.max_memory_allocated() minus the baseline after Q, K and V were created: extra tracked allocation during the call (not total process memory, physical VRAM or memory traffic). Batch 1, 12 heads, head dimension 64. The numbers in brackets divide the peak by the size of one score tensor from the table above.
| \(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 |
Three implementations, three patterns:
- Naive settles at about 2.05 score tensors: roughly the scores plus the probabilities.
- SDPA math backend settles at about 4.70, reflecting extra precision and workspace in this build.
- Memory-efficient backend allocates exactly its fp16 output, \(12 \times T \times 64 \times 2\) bytes (24 MiB at 16,384 tokens), and nothing quadratic.
How the efficient backend avoids storage. IO-aware exact-attention methods process the keys in blocks. For each query row they keep a running maximum and a running normaliser, rescale partial results as each new block arrives, and so never need all the scores at once. That is the online softmax. (The allocator saw no quadratic allocation; that does not prove the kernel uses no on-chip or temporary workspace. The cited algorithms establish the principle; these measurements show what this backend allocated here.)
The unresolved puzzle. In the largest rows, PyTorch reported 12,568 MiB and 28,864 MiB of extra allocation on a card whose properties reported about 12 GiB, and the operations completed. Windows’ WDDM driver oversubscribing GPU memory is a plausible explanation, but the experiment did not record resident VRAM, page faults or transfers to system RAM, so it cannot establish one. Do not conclude that a 12 GiB card can run a 28 GiB attention workload at normal speed, or that the same allocation would succeed under another driver.
Which kernel ran
PyTorch’s scaled_dot_product_attention (SDPA) is an interface that can dispatch to several implementations. The harness forces each candidate in turn with sdpa_kernel([SDPBackend.<name>]) and records whether it runs, at batch 1, twelve heads, head dimension 64, sequence 256:
| Backend | fp16 | fp32 |
|---|---|---|
| Math | runs | runs |
| Memory-efficient | runs | runs |
| FlashAttention | unavailable: no kernel | unavailable |
| cuDNN attention | unavailable | unavailable |
On this build (PyTorch 2.6.0+cu124, Windows, RTX 2060, compute capability 7.5), math and memory-efficient ran; FlashAttention and cuDNN did not. The run’s notes attribute the FlashAttention failure to the build lacking support and the cuDNN failure to capability restrictions, though the saved table records only the error message.
So no timing in this chapter measures FlashAttention. The memory-efficient backend uses the same broad IO-aware strategy, but FlashAttention’s specific design and performance claims should not be attributed to it.
Backend choice belongs in the experiment’s identity. It can depend on PyTorch version and build, device, dtype, head dimension, mask, dropout and shape, and “SDPA” alone does not say which path ran. The isolated tests below force their backend explicitly. The whole-model test later does not record which kernel each layer dispatched, so treat those two kinds of evidence differently.
Same answer?
A memory saving is only useful if the answer is the same. The test. Sequences of 64, 512 and 2,048 tokens, twelve heads of width 64. For each dtype, Q, K and V are created in that dtype, then converted to float64 to compute a reference with the direct formula. So the reference uses the same already-rounded inputs: the comparison isolates differences in how each implementation computes, not the error of storing inputs in fp16. The table shows the maximum absolute difference of any output element:
| 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}\) |
Errors are around \(10^{-6}\) in fp32 and \(10^{-3}\) in fp16. In fp16 the naive path is the least accurate, consistent with it rounding its large intermediate tensors to fp16. PyTorch documents that its math backend can keep intermediates in higher precision; the memory-efficient kernel’s internal arithmetic was not inspected.
Close outputs are not bitwise identity, and random inputs are not trained-model activations. The 8,192- and 16,384-token outputs were not checked at all.
Time
The set-up. The CUDA-event harness from Matrix Multiplication and GPU Execution, after a warm-up, three runs. Causal attention, batch 1, twelve heads, random inputs. “Efficient” is PyTorch’s forced EFFICIENT_ATTENTION backend, not FlashAttention. The runs agreed well, but Chapter 7’s warnings about clocks and the display driver still apply.
| \(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 |
Both are still quadratic. Fitting time against length for \(T \ge 1{,}024\) gives exponents of 1.96 (fp16 naive), 2.04 (fp32 naive), 1.82 (fp16 efficient) and 1.88 (fp32 efficient). (Empirical slopes over four lengths, not proofs of complexity.) The efficient kernel does the same quadratic arithmetic; it just does it with less memory traffic and better parallelism.
But the efficient kernel is much faster. At \(T=8{,}192\) in fp16, time fell from 67.0 ms to 5.97 ms: 11.2× for this shape on this device (not a whole-model speed-up).
Why? Two calculations point the same way.
Arithmetic rate. Dividing by the ideal causal FLOP count, the efficient run achieved about 17.3 TFLOP/s and the naive run about 1.5 TFLOP/s. (The naive code actually does dense products, so the triangular count understates its real arithmetic; its true rate is somewhat higher, but still far below the efficient kernel’s.)
Memory traffic. The naive kernel writes and reads large score and probability arrays. A rough count: \(12 \times 8{,}192^2\) elements, times about 12 bytes of fp16 traffic per element, is about 9.7 GB. At the 278 GB/s copy rate measured in Chapter 7, moving that alone would take about 35 ms, against an observed 67 ms. That is an illustrative traffic model, not a measurement: caching, temporary precision, launches and the dense matmuls themselves were not separated out. But it supports the main point: avoiding the quadratic intermediates is worth a great deal here.
What the causal mask saves
In principle the causal mask halves the work: only \(T(T+1)/2\) of the \(T^2\) pairs are permitted. In practice, it depends entirely on whether the kernel can skip masked work. Here is causal time divided by unmasked time, fp16:
| 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 kernel benefits more as length grows, reaching 0.58 of the unmasked time at 4,096: it skips much of the masked region. The math backend and the naive implementation got slower with the mask (ratios 1.27–1.32 and 1.68–1.74), because they still do all the dense work and then add masking on top.
So a causal mask specifies which information may flow, not how much work the kernel does. When estimating latency, keep three things apart: the masked mathematical function, the ideal count of permitted pairs, and the operations the kernel actually runs. (These are results for these implementations at these shapes, not a general rule.)
In the whole model
An isolated kernel benchmark is not the whole transformer. Does the advantage survive the surrounding layers?
The test. Hugging Face GPT-2 small loaded twice, with attn_implementation="eager" and attn_implementation="sdpa"; fp32, batch 1, three lengths, same GPU. (The configuration records the interface chosen, not which CUDA kernel each layer actually dispatched.)
| 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}\) |
Time. SDPA’s advantage grows with length, up to 23.4% at 1,024 tokens. That is a real gain but nowhere near the isolated kernel’s 11×, because attention is only part of the forward pass.
Memory. The peaks were nearly identical. Why didn’t the attention saving show up? One candidate explanation, untested here (exercise 7), is the logits tensor. GPT-2 returns logits for every position: at 1,024 tokens that is \(1{,}024\times 50{,}257\times4\) bytes, about 206 MB (196 MiB), roughly 72% of the 272 MiB peak. (An allocator peak is not just a sum of tensors, so this does not prove which allocations overlapped.) A generation loop only needs the last row of logits, but this experiment did not try returning just that.
So the answer depends on the shape. For GPT-2 small at its maximum of 1,024 tokens, whole-model memory is not dominated by attention alone. At 16,384 positions the isolated benchmark shows what an explicit quadratic tensor would cost, but GPT-2 small cannot run at 16,384 positions: its learned position table stops at 1,024. For a real long-context model, the largest allocation depends on length, vocabulary, attention implementation, dtype, batch and what the API returns. Measure it rather than extrapolating from this model.
The other shape: one query, many keys
In a cached generation step, the new token brings one query per head, which attends over the stored keys and values of every earlier position (and itself). Per layer, that is a \(1\times T\) problem costing about \(4hTd\) matmul FLOPs: about 3.15 million FLOPs at \(T=1{,}024\), \(h=12\), \(d=64\). Tiny, compared with prefill.
But the cache itself is not tiny.
How big is the cache?
For GPT-2 small at batch 1 in fp16 (twelve layers, twelve KV heads of width 64, both keys and values):
| 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% |
At about seven concurrent 1,024-token sequences, the stored cache becomes larger than the model. (The 4,096 row is hypothetical: unchanged GPT-2 small cannot use that context.)
What does that crossover mean? It is a capacity comparison: it says when stored KV data outgrows the weights, and so where cache traffic could start to compete with weight traffic. It does not show that attention overtakes everything else at batch seven, or set a serving limit: one set of weights is shared across a batch, while each sequence’s keys and values are read separately and in different patterns. It does explain why the growing per-request state earns its own chapters on paged caches, cache quantisation and grouped-query attention (which reduces the number of stored KV heads without necessarily reducing query heads).
How fast is one decode step?
The test. The forced memory-efficient backend runs one query against \(T\) synthetic keys and values, at batch 1, 16 or 64, with twelve heads of width 64. This is a single layer on random tensors, not a cached GPT-2 engine (that comes in Key-Value Caching). The bandwidth column divides the nominal size of the K/V inputs by the elapsed time, assuming they are read once; it is not a hardware counter.
| 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 |
(For scale: the batch-64, 16,384-position input is 3 GiB for one layer; a twelve-layer cache that size would be 36 GiB.)
What it shows.
- Time grows roughly linearly with context at the longer lengths, as expected for one query against a growing cache.
- With enough batch, the kernel approaches memory speed. At batch 16 and 64, the nominal rate reaches 246–263 GB/s, close to Chapter 7’s 278 GB/s copy rate. That fits a kernel limited by reading keys and values, under the read-once assumption, though it is not proof of a hardware limit.
- At batch 1 it stalls at about 50 GB/s. One plausible reason is too little parallel work: twelve heads may not be enough to keep the GPU busy. Research on splitting attention across the key dimension supports this in general, but occupancy and memory transactions were not measured here, so it remains a hypothesis.
The practical lesson is a trade-off, not “always batch more”. Batching supplies parallel work and uses the GPU better, but every extra sequence brings its own context, cache capacity, memory reads and scheduling constraints. Prefill and Decode puts prefill and decode together at the level of a whole request.
Inference Lab increment
The Lab now has:
attention_flops(batch, heads, q_len, kv_len, head_dim, causal),score_bytes(...),kv_bytes(...)andfit_exponent(...): arithmetic and storage helpers.causal=Truecounts the ideal permitted triangle, not necessarily the operations a kernel executes.naive_attentionandsdpa(backend=...): separately callable attention paths, compared numerically against float64 on the same stored inputs.- Subcommands
backends,correctness,memory,scaling,causal,decode,cpuandmodel: availability probes, allocator peaks, timings and model comparisons. The large-memory probes deliberately do not time possibly-paged runs.
Still to do: store full runtime provenance, verify automatic SDPA dispatch, collect GPU residency and DRAM counters where available, and separate output allocations from internal attention workspace.
Two gates, not one. The acceptance ladder from Building Our First Inference Engine now has two independent requirements for any new attention path:
- Numerical: it must meet a stated tolerance across the relevant shapes, dtypes and causal settings. Disagreement is investigated, not dismissed as “rounding”.
- Performance: comparisons must state the backend that executed, the timing method and the exact memory metric.
A 500-fold drop in extra allocator memory is not a 500-fold drop in total GPU memory, and a nominal bytes-per-second figure is not measured bandwidth.
Limits of this chapter’s evidence
About the set-up
- No FlashAttention. The FlashAttention backend was unavailable in this PyTorch build; every “efficient” timing is PyTorch’s
EFFICIENT_ATTENTIONpath. - One RTX 2060 under Windows WDDM. Kernel availability, clocks, driver behaviour and memory oversubscription may differ elsewhere.
About the measurements
- Allocator peaks, not VRAM.
max_memory_allocated()minus baseline excludes the Q/K/V inputs and reports neither physical residency nor all kernel-internal storage. Paging was not instrumented. - Correctness checked only up to 2,048 tokens, against a reference using inputs already rounded to the tested dtype. No trained-model activations, padding masks, sliding windows or grouped-query heads.
- Ideal versus executed arithmetic. The causal FLOP helper counts permitted pairs; the naive code runs dense products and masks afterwards.
- Effective bandwidth is calculated, from nominal K/V sizes or a hand traffic count, not from memory counters.
About scope
- The whole-model test did not record dispatched kernels inside GPT-2’s layers.
- Decode was isolated and synthetic: one layer of random K/V tensors, no cached engine. Contexts above 1,024 are hypothetical for unmodified GPT-2 small.
- The batch-1 inefficiency explanation is a hypothesis; occupancy and end-to-end serving benefit were not measured.
What you should now be able to do
- Derive dense attention FLOPs and the ideal causal count from \(B\), \(h\), \(T_q\), \(T_{kv}\) and head width, and say when the causal saving is actually realised.
- Compute score-tensor sizes and full KV-cache storage, stating batch, layer, dtype and head-count assumptions.
- Explain how tiled attention with an online softmax computes the same function without storing a quadratic intermediate.
- Distinguish
torch.cuda.max_memory_allocated()from resident VRAM, device capacity and measured memory traffic. - Name the SDPA backend that was actually forced or observed, rather than inferring it from the API name.
- Interpret error against a reference built from already-rounded inputs, and say which numerical behaviours remain untested.
- Compare prefill-shaped and decode-shaped attention in arithmetic, cache capacity and the effect of batching.
- Treat a roofline or effective-bandwidth number as a model with assumptions, not a profiler reading.
We now have the costs of both attention shapes in isolation. A real request runs both: one prefill over the prompt, then many decode steps, each with its own limits. Prefill and Decode follows a request through both phases and asks where its time actually goes, and what happens when one request’s prefill lands in the middle of another’s decode.
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
- 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.
- Repeat the
memorycommand 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. - Modify
naive_attentionto 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. - Re-run
correctnesswith 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. - 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=Falseis used in the isolated one-query experiment. - 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.
- 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.
- 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
- Vaswani et al., Attention Is All You Need (2017) — defines multi-head scaled dot-product attention, causal masking and the mathematical reference computation.
- Rabe and Staats, Self-attention Does Not Need O(n²) Memory (2021) — establishes that quadratic arithmetic does not require quadratic attention workspace; an independent foundation for the chapter’s memory distinction.
- Dao et al., FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (2022) — develops IO-aware tiled exact attention and the role of online softmax; this paper’s FlashAttention kernel was not benchmarked here.
- PyTorch
scaled_dot_product_attentiondocumentation — implementation-dependent backend dispatch, dtype, masking and numerical behaviour (documentation, not a research paper).
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 |