1. The quadratic attention bill
For a sequence of positions, dense self-attention compares queries with keys. One head's full score table has positions:
Computing scores costs 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
For positions, a full square contains entries per head. A materialised two-byte table alone would take about 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 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.
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 , including the current position:
Across the sequence there are at most allowed positions. With fixed width and head dimension, the leading attention arithmetic becomes rather than .
Dense causal
Local causal · W=3
Local + first-token key
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.
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.
Reuse cached keys and values
Compute its query, key and value
The newest output predicts the following token. Repeat at each layer and generation step.
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 cached positions, dense attention still uses 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:
where is batch size, layer count, retained positions, the number of key/value heads, their width and 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.
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 , maintain a running maximum , denominator and weighted-value numerator . For a new block , update:
After the final block, the attention output is:
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 , first process . Then and . Processing changes the maximum to :
This equals the full-row sum .
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.
The experiment also uses scalar values 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.