Highlights

Contents

Part X
10

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.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

#Section 53Every Token Scores Every Token

In Part VII the score grid S=QK⊤S = QK^\top had one row per query and one column per key. With TT tokens, that is T×T=T2T \times T = T^2 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.

TOKENS GROW IN A LINE, SCORES GROW IN A SQUARE4 tokens16 scores8 tokens64 scores16 tokens256 scores1,000 tokens:1,000,000100,000 tokens:10,000,000,000per head, per layer
Figure 1.72Tokens grow in a line; scores grow in a square. Four tokens make 16 scores, eight make 64, sixteen make 256.

Strictly speaking, the causal mask hides about half the grid, so a decoder only needs T(T+1)/2T(T+1)/2 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 322=1,02432^2 = 1{,}024.

DOUBLING THE CONTEXT QUADRUPLES THE SCORE GRID4k×18k×416k×1632k×6464k×2564k → 128k:32× the tokens,1,024× the scores
Figure 1.73Each square has double the side of the previous one and four times the area. Five doublings from 4k to 64k multiply the score grid by 256.

#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 m×nm \times n matrix by an n×pn \times p matrix costs about 2mnp2mnp 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.

24 d2⏟projections + MLPversus4 T d⏟attention⟹equal when T=6d\underbrace{24\,d^2}_{\text{projections + MLP}} \quad \text{versus} \quad \underbrace{4\,T\,d}_{\text{attention}} \quad\Longrightarrow\quad \text{equal when } T = 6d

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.

FORWARD FLOPS PER TOKEN PER LAYER: LINEAR LAYERS 24 d² VERSUS ATTENTION 4 T d (d = 4,096)context length TFLOPs per tokenT = 6d = 24,576projections + MLP: flatattention: grows with T016,38432,76849,15265,536below the line,attention is the cheap part
Figure 1.74Forward FLOPs per token per layer for a 4,096-wide model. The linear layers cost a flat 24d²; attention grows in a line with T and crosses at T = 6d, about 24,600 tokens.

(For causal attention the real attention cost is about half, 2Td2Td averaged over positions, which moves the crossover to roughly 12d12d. 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 VV. Storing one grid in 16-bit numbers takes T2×2T^2 \times 2 bytes per head.

Materializing every head's full score matrix can exhaust memory before arithmetic becomes the main bottleneck.

MEMORY TO STORE ONE LAYER’S FULL SCORE GRIDS IN 16-BIT (LOG SCALE)1 MB100 MB10 GB1 TBone 80 GB GPU1,0244,0968,19232,768131,072slate: 8 heads (Finch-19) orange: 32 heads (Llama 3 8B size)1.1 TB at 128k
Figure 1.75Memory needed to store one layer's full score grids in 16-bit, for 8 and 32 heads, on a log scale. Past about 32k tokens, a 32-head layer no longer fits on one 80 GB GPU.

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 T×TT \times T grid is never stored anywhere. Tiles entirely above the diagonal are skipped completely, because the causal mask would hide them anyway.

FLASHATTENTION: WORK TILE BY TILE, NEVER STORE THE WHOLE SQUAREquery blocks down, key blocks acrossskipped:all futureFAST ON-CHIP MEMORY (SRAM)query block 3key/value block 2scores for this tile: used, then thrown awaykept per query row:running max m, running sum ℓ, running output Oexact same answer, a fraction of the memory
Figure 1.76FlashAttention's tiling. One query block stays in fast memory while key/value blocks stream past; each tile's scores are used and discarded. Future tiles are skipped entirely.

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, mm, and the running sum of exponentials relative to it, ℓ\ell, 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.

ONLINE SOFTMAX: SCORES ARRIVE IN TWO CHUNKS, KEEP A RUNNING MAX AND SUMchunk 1[2.0, 1.0, 3.0]m = 3ℓ = e⁻¹ + e⁻² + e⁰ = 1.503chunk 2[5.0, 0.0, 4.0]m = 5rescale: 1.503 × e^(3−5) = 0.203add: e⁰ + e⁻⁵ + e⁻¹ = 1.375resultℓ = 0.203 + 1.375 = 1.578checkall six at oncem = 5Σ e^(s − 5) = 1.578 ✓when a bigger max arrives, shrink the old sum to match
Figure 1.77Online softmax with two chunks. When a larger maximum arrives, the old running sum is rescaled by e to the power of (old max minus new max) before adding the new terms. The result equals the all-at-once sum.

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.

COMPUTE FEWER SCORES: CELLS EACH PATTERN KEEPS, T = 16full causal136 of 136 cellssliding window (4)58 of 136 cellswindow + stride 473 of 136 cells
Figure 1.78Three patterns on 16 tokens. Full causal attention keeps 136 cells, a sliding window of four keeps 58, and adding a stride of four keeps 73.

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 TT, not a T×TT \times T 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.