← All notes
Course chapters
On this page

Lesson 26 · Large language models

KV caching, sparse attention and FlashAttention

Separate three attention optimisations: fewer connections, cached prefix computation and less memory traffic. Count score positions, estimate a KV cache and calculate online Softmax across blocks.

1. The quadratic attention bill

For a sequence of nn positions, dense self-attention compares nn queries with nn keys. One head's full score table has n2n^2 positions:

S=QKTdk,S∈Rn×n.S=\frac{QK^{\mathsf T}}{\sqrt{d_k}},\qquad S\in\mathbb R^{n\times n}.

Computing scores costs O(n2dk)O(n^2d_k) arithmetic; combining values also involves all allowed pairs. For a fixed head width, we often describe this as quadratic in sequence length.

1,024 tokens

1,048,576 square score positions

32,768 tokens

1,073,741,824 square score positions

128,000 tokens

16,384,000,000 square score positions

Figure 26-1. Per-head, full-square score counts grow quadratically. These are not FLOP counts, allocations or specifications of a particular model.

For 128,000128{,}000 positions, a full square contains 16,384,000,00016{,}384{,}000{,}000 entries per head. A materialised two-byte table alone would take about 30.530.5 GiB. This excludes other heads, layers, probabilities and activations, and is not a claim about any particular model's architecture.

A causal mask permits only n(n+1)/2n(n+1)/2 positions, still a quadratic count. Kernels can skip masked work, and fused algorithms can avoid materialising the whole score table. Quadratic attention arithmetic does not require every implementation to store quadratic intermediate memory.

Pause and think

Do all long-sequence attention optimisations solve the same problem?

I've thought about it — show the answerHide answer

No. Some change which positions interact, some reuse work from earlier generation steps, and some perform the same attention operation with less data movement.

Those distinctions explain why the techniques have different trade-offs and can sometimes be combined.

2. Sparse attention: calculate fewer connections

A local window lets each query attend to a limited set of nearby keys. In a causal window of width WW, including the current position:

max⁡(0,i−W+1)≤j≤i.\max(0,i-W+1)\leq j\leq i.

Across the sequence there are at most nWnW allowed positions. With fixed width and head dimension, the leading attention arithmetic becomes O(nW)O(nW) rather than O(n2)O(n^2).

Dense causal

Local causal · W=3

Local + first-token key

Figure 26-2. Causal access patterns, not learned weights. The first-token key can be read by later queries but cannot read future tokens itself; this preserves causality.

For bidirectional encoders, a window can extend on both sides. For causal generation, future keys must remain excluded. Adding a supposedly “global” token that reads the entire future and then broadcasts that information would leak future targets through later layers.

Longformer combines local and task-motivated global attention for long-document tasks. Other sparse designs use dilated connections, selected global positions or mixtures of local and full-attention layers. Their masks and intended tasks differ.

Sparse attention changes the connectivity and generally changes the output compared with unrestricted dense attention. But a model trained with that sparse pattern computes its own defined operation exactly; it is not necessarily an approximation introduced only at inference.

A token can receive distant information through multiple layers, even if it cannot directly access that distant key in one layer. This expands the receptive field, without making all long-range dependencies equally easy or preserving every dense interaction.

Simply applying a sparse-looking mask to a dense kernel may not save work. Efficient execution also needs an implementation that exploits the pattern.

Full square score positions per head: 1,048,576

Allowed causal positions per head: 524,800

Allowed local causal positions per head: 122,944

Illustrative KV cache: 0.125 GiB

Counts are permitted score positions, not FLOPs or measured runtime. Cache assumes batch 1, 32 layers, 8 KV heads, head width 128 and two bytes per element, retaining all n positions. Window selection does not evict this cache. Allocation overhead and other tensors are excluded.

Experiment 26-A. Compare score-position counts and an explicitly specified KV cache budget.

The experiment counts score positions and separately estimates a specified KV cache. It does not measure speed. The cache retains the complete prefix even when a local window is selected, so its number deliberately does not change with that control.

3. KV caching: stop recomputing the causal prefix

Autoregressive generation repeatedly extends a prefix. A naive implementation processes the whole enlarged prefix every time, recomputing earlier representations and their key/value projections.

In a causal model, an earlier position cannot depend on later tokens. With unchanged model parameters, prefix, positions and inference settings, its existing per-layer keys and values remain valid when we append a token.

Prefill: process the prompt and retain each layer's K and V.

Existing prefix
Reuse cached keys and values
New input token
Compute its query, key and value
K1:t=[K1:t−1;kt],V1:t=[V1:t−1;vt]K_{1:t}=[K_{1:t-1};k_t],\qquad V_{1:t}=[V_{1:t-1};v_t]ot=softmax⁡ ⁣(qtK1:tTdk)V1:to_t=\operatorname{softmax}\!\left(\frac{q_tK_{1:t}^{\mathsf T}}{\sqrt{d_k}}\right)V_{1:t}

The newest output predicts the following token. Repeat at each layer and generation step.

Figure 26-3. Cache causal prefix representations to reuse work. The semicolon appends a row along the sequence axis. This is not a cache of final answers or model weights.

The first stage, prefill, processes the prompt and builds the cache. In a subsequent decode step, each layer processes the new input position, appends its key and value and attends over the available cached prefix.

The reason reuse works is causal dependence, not merely that a word has the same spelling. Different contexts give the same word different contextual representations. Editing the prefix, changing position handling or changing the model can invalidate cached entries. Bidirectional prefix representations can also change when new text is appended.

Time saved, memory retained

For a new query over tt cached positions, dense attention still uses O(tdk)O(td_k) score work and a value-mixing pass. It does not become constant-time. Across many generated positions, these growing scans still accumulate quadratic attention work in the total sequence length.

Compared with repeatedly recomputing full-prefix attention tables, caching removes substantial repeated work. That comparison must distinguish a single decode step from prefill and from the entire generation run.

An idealised cache size, with equal key/value head widths, is:

bytesKV=2BLnHKVdhb,\text{bytes}_{\mathrm{KV}} =2BLnH_{\mathrm{KV}}d_hb,

where BB is batch size, LL layer count, nn retained positions, HKVH_{\mathrm{KV}} the number of key/value heads, dhd_h their width and bb bytes per stored element. The factor two accounts for keys and values.

MQA and GQA share key/value heads across query heads, reducing this head-count factor. They do not remove the need to read cached content. Quantisation, cache eviction and allocation strategies introduce further trade-offs; none are simulated by the budget experiment.

4. FlashAttention: change the execution and data movement

Dense attention need not store every score and probability in high-bandwidth GPU memory, or HBM. FlashAttention tiles the work and uses fast on-chip storage for intermediate calculations.

HBM provides large capacity. On-chip SRAM is much smaller and closer to the compute units. Actual capacities and transfer rates depend on the hardware; the important distinction is the cost of repeatedly moving a huge intermediate table between memory levels.

Conventional materialised computation

Q/K/V → score table in HBM → Softmax table in HBM → multiply by V

Tiled computation

Load Q/K/V tiles → compute and update on-chip statistics/output → continue → write final output

Full score and probability tables need not be stored in HBM. Inputs, outputs and small saved statistics still use device memory.

Figure 26-4. FlashAttention reorganises data movement and computation. Exact attention means the same mathematical operation, allowing floating-point rounding differences.

The obstacle seems to be Softmax: its normalisation depends on an entire row. How can we process a row in pieces without knowing its final maximum or denominator?

Online Softmax: update and rescale the running totals

For scores sjs_j, maintain a running maximum mm, denominator ℓ\ell and weighted-value numerator uu. For a new block BB, update:

m′=max⁡(m,max⁡j∈Bsj),α=em−m′,ℓ′=αℓ+∑j∈Besj−m′,u′=αu+∑j∈Besj−m′vj.\begin{aligned} m'&=\max\left(m,\max_{j\in B}s_j\right),\\ \alpha&=e^{m-m'},\\ \ell'&=\alpha\ell+\sum_{j\in B}e^{s_j-m'},\\ u'&=\alpha u+\sum_{j\in B}e^{s_j-m'}v_j. \end{aligned}

After the final block, the attention output is:

o=uℓ.o=\frac{u}{\ell}.

When a larger maximum arrives, the old accumulators are rescaled into the new exponential reference. The numerator needs the same rescaling as the denominator; tracking only a denominator does not yet compute attention's value-weighted output.

For scores [2,1,4,0][2,1,4,0], first process [2,1][2,1]. Then m=2m=2 and ℓ=1+e−1≈1.367879\ell=1+e^{-1}\approx1.367879. Processing [4,0][4,0] changes the maximum to 44:

ℓ′=e−2(1+e−1)+1+e−4≈1.203438.\ell'=e^{-2}(1+e^{-1})+1+e^{-4} \approx1.203438.

This equals the full-row sum e−2+e−3+1+e−4e^{-2}+e^{-3}+1+e^{-4}.

Scores: [2, 1, 4, 0] · scalar values: [1, 2, 3, 4]

Running maximum m: 2

Old accumulator rescaling: 0.000000

Running denominator ℓ: 1.367879

Running weighted numerator u: 1.735759

Current output u / ℓ: 1.268941

Full-row reference output: 2.748934

The first block's output is provisional. The final result includes every score and value. This scalar JavaScript calculation demonstrates the recurrence; it is not a GPU kernel or performance benchmark.

Experiment 26-B. Update the running maximum, denominator and weighted numerator across two blocks.

The experiment also uses scalar values [1,2,3,4][1,2,3,4] to accumulate an actual weighted output. The first block's result is provisional; only the final result accounts for all four inputs.

What “exact” does and does not mean

FlashAttention computes the same mathematical dense attention rather than removing low-weight connections. Reordered floating-point operations can still produce rounding differences, so “exact” does not mean bit-for-bit identical to every reference implementation.

It avoids writing full score and probability tables to HBM, but inputs, outputs and saved statistics still use memory. During training, recomputation can trade additional arithmetic for reduced memory traffic. The leading dense pairwise arithmetic remains quadratic.

Speedups depend on hardware, sequence shape, precision, masks and implementation. A fixed “two to four times faster” claim is not universal, and a compatible kernel is not automatically the best choice for every workload.

Tiling can also be combined with supported sparse patterns. This combines efficient execution with changed connectivity; it does not turn sparse attention back into full dense attention.

5. What you have discovered

| Technique | Main change | Important trade-off | | --- | --- | --- | | Sparse attention | Calculate fewer permitted query-key connections. | Changes connectivity and generally changes the result. | | KV cache | Reuse per-layer keys and values during causal decoding. | Retains cache memory and still scans available keys. | | FlashAttention | Tile and fuse exact attention with less intermediate memory traffic. | Dense arithmetic remains quadratic; performance is workload-dependent. |

Full-sequence processing, one-token decoding and intermediate storage are different accounting problems. Keeping them separate makes both complexity claims and implementation choices easier to understand.

Next, we will explore mixture-of-experts models, which route tokens to selected feed-forward experts to separate total parameter capacity from the work activated for each token.

Check your understanding

1. What is quadratic in a conventional full-sequence dense attention calculation?
2. Which technique reuses keys and values for earlier tokens during causal generation?