The n × n Matrix: Where the Cost Lives
Full attention compares many position pairs. Long contexts increase both work and intermediate storage. Efficient kernels avoid large intermediates; sparse patterns instead remove comparisons and change the available information.
#Section 53Every Token Scores Every Token
In Part VII the score grid had one row per query and one column per key. With tokens, that is scores. For our 7-token sentence, 49. For 1,000 tokens, 1,000,000. For 100,000 tokens, 10,000,000,000. And that is for one head in one layer: Finch-19 has 8 heads in each of 8 layers, so 64 such grids per forward pass.
This growth with the square of the length is called quadratic cost, and it is the main reason long contexts are hard and expensive. The tokens themselves grow in a line: double the text, double the tokens. The grid grows in both directions at once: double the text, and both the number of rows and the number of columns double, so the area quadruples.
Strictly speaking, the causal mask hides about half the grid, so a decoder only needs scores: 28 for our sentence, 136 for 16 tokens. Half of a square is still a square in how it grows. Dividing by two does not change the shape of the curve.
#Section 54Doubling Is Quadrupling
The quadratic law has a counter-intuitive consequence that is worth stating as plainly as possible. Going from a 4,000-token context to an 8,000-token one does not double the attention work; it quadruples it. Going from 4,000 to 128,000 tokens multiplies the tokens by 32 and the scores by .
#Section 55When Does Attention Actually Dominate?
The square sounds alarming, but attention is not the only work in a layer, and for short texts it is not even the biggest. To compare fairly, count FLOPs, floating-point operations (one multiplication or one addition each). A matrix multiply of an matrix by an matrix costs about FLOPs, one multiply and one add for each term.
Projection and MLP work scale with model width and the number of positions. Pairwise attention additionally grows with the amount of history each position sees.
At short contexts, projections and the MLP can dominate. At long contexts, pairwise comparisons become more important. The crossover depends on architecture and kernels, so measure the workload.
(For causal attention the real attention cost is about half, averaged over positions, which moves the crossover to roughly . Both conventions appear in the literature; the shape of the argument is what matters.)
#Section 56The Memory Bill
The square costs twice: once in arithmetic, and once in memory. A simple implementation computes the whole score grid, stores it, applies softmax, stores the result, and then multiplies by . Storing one grid in 16-bit numbers takes bytes per head.
Materializing every head's full score matrix can exhaust memory before arithmetic becomes the main bottleneck.
There is a subtler cost hiding here too. Even when the grid fits, writing gigabytes of scores out to the GPU's main memory and reading them back for softmax takes time, and on modern GPUs that data movement, not the arithmetic, is usually what makes attention slow. Unit II's FlashAttention chapter is built entirely on that observation.
#Section 57How Real Systems Cope
There are two ways out. Keep exactly the same maths but never store the full grid, or deliberately skip most of the grid.
FlashAttention: never build the whole square
FlashAttention, introduced by Tri Dao and colleagues in 2022, cuts the score grid into tiles and handles one tile at a time. A block of queries is loaded into the GPU's small, very fast on-chip memory. The method then sweeps across the blocks of keys and values: for each tile it computes the scores, uses them immediately to update a running result, and throws them away. The full grid is never stored anywhere. Tiles entirely above the diagonal are skipped completely, because the causal mask would hide them anyway.
The answer at the end is exactly the same as ordinary attention, not an approximation. The trick that makes that possible is the next subsection.
Online softmax
Softmax seems to need the whole row at once: the maximum (for the overflow fix of Section 41) and the total of all the exponentials. How can you do it tile by tile? By keeping two running numbers per query row, the largest score seen so far, , and the running sum of exponentials relative to it, , and correcting them whenever a bigger maximum turns up.
Maintain a running maximum and exponential sum. When a later tile raises the maximum, rescale earlier totals to the new reference. Apply the same rescaling to the weighted-value sum, preserving the full softmax result without storing all scores.
This technique is called online softmax, described by Maxim Milakov and Natalia Gimelshein in 2018. FlashAttention combines it with tiling. Unit II gives FlashAttention a whole part, including what happens during training.
Or compute fewer scores
Sparse attention selects fewer query-key pairs. A sliding window keeps nearby history; a strided pattern adds spaced long-range links. These change the available relationships, unlike an exact dense kernel that merely executes them efficiently.
Unlike FlashAttention, this is not exact. Some tokens can no longer see each other directly, and information has to hop through intermediate tokens across layers, so quality can drop on tasks that need precise long-range lookups. Mistral 7B's first version used a 4,096-token sliding window, and several large models mix windowed layers with a few full-attention layers.
Sharp edges of attention cost
For short prompts, blame the MLP. With a few hundred tokens, attention is a small share of the work; the projections and MLP dominate (Section 55). Measure before you optimize attention.
FlashAttention is exact. People sometimes avoid it thinking it trades accuracy for speed. It computes the same answer in a different order, with only last-digit rounding differences.
Padding wastes squares. If one sequence in a batch has 2,000 tokens and the rest have 100, everyone is padded to 2,000 and you compute a huge grid that is mostly padding. Sort batches by length, pack sequences together, or use kernels that accept variable lengths.
Generation is linear per step. When generating one token at a time, the new token's query scores only against the existing keys: one row of , not a grid. Each step's attention cost grows in a line with the length. Part XI shows how.
Linear attention trades quality. Some methods replace softmax attention with alternatives whose cost grows linearly with length. They are much cheaper but usually remember precise long-range details less well, which is why hybrids often mix a few full-attention layers back in.