Attention kernels, KV heads and long context
hard 6 minLong contexts increase both the work of mixing positions and the size of retained decoding state.
Video lesson · Chapter 1 of 4
The conversation filling the cabinet
Theory
Read or listen first. About 2 min.
What it is
Long contexts increase both the work of mixing positions and the size of retained decoding state. Tiled attention changes where intermediate calculations are stored. Sharing KV heads reduces the bytes retained per position. Position-encoding schemes change how the model represents distance.
Why it exists
Diagnose the actual bottleneck by separating prompt processing, per-token decoding and retained memory. Supporting a larger position index does not by itself establish that the model can recover a fact from the middle of a long document.
Estimate the KV cache before doubling context
Inside this chapter
Chapter sources- Flash Attention
- FlashAttention tiles the exact attention computation to reduce expensive traffic between GPU memory levels. It avoids materializing the full score matrix in high-bandwidth memory. Its principal improvement is I/O efficiency; standard dense attention still considers quadratically many query–key pairs in sequence length.
Naive attention writes the full n by n score matrix to GPU main memory, reads it back for the softmax, and reads it again to multiply by V. On modern GPUs that memory traffic, not the arithmetic, is the bottleneck. FlashAttention keeps a block of queries on chip, streams K and V through in tiles, and uses an online softmax that rescales partial sums as larger maxima appear, so the full matrix never exists. The number of query-key pairs is unchanged; the win is fewer bytes moved and lower peak memory.
Example. Trace an attention tile that reads Q and K, updates running normalization and accumulates V. The full score matrix need not be written to device memory.
Another example. A long-document summariser that ran out of memory at 16k tokens with a naive kernel can fit with a tiled kernel, yet its prefill time still grows roughly with the square of length.
One query block, tile by tile - 1Load Q block to SRAMfast on-chip memory
- 2Load next K, V tilea slice of the sequence
- 3Scores for this tilenever written to HBM
- 4Update running max, sumonline softmax rescaling
- 5Accumulate into outputwrite O once at the end
Repeat: back to Load Q block to SRAMSame exact attention result, far less traffic to high-bandwidth memory.
- Multi-Query & GQA
- Multi-query attention shares a key and value head across query heads. Grouped-query attention shares each KV head within a group. Both can reduce KV-cache size and bandwidth during decoding. The number of query heads and the number of KV heads are different inputs to a cache estimate.
During decoding every new token reads the entire cache, so cache size sets both memory and bandwidth per step. Multi-query attention keeps one KV head for all query heads; grouped-query attention is the middle ground, with each KV head shared by a group. Query heads still compute their own attention patterns, so much of the expressiveness is kept while the cache shrinks by the group factor.
Example. With 32 query heads, GQA using eight KV heads stores one quarter as many KV heads as ordinary 32-head attention at equal head width.
Another example. With 32 layers, 2,048 positions, head size 128 and 2-byte values: 32 KV heads need 1 GiB per sequence, 8 KV heads need 256 MiB, and a single shared KV head needs 32 MiB.
32 query heads sharing 8 KV heads
Each group of 4 query heads reads the same keys and values, so the cache holds a quarter of the heads full attention would. - Long Context (RoPE, ALiBi)
- RoPE encodes relative position through rotations of queries and keys. ALiBi applies a distance-dependent bias to attention scores. Both affect how positions influence attention. A configuration that accepts a longer prompt still needs tests for retrieval and reasoning at distant positions.
RoPE splits each query and key into pairs of dimensions and rotates each pair by an angle that grows with position, using a different frequency per pair. Because rotations compose, the attention score depends only on how far apart two tokens are. ALiBi adds no embedding at all and simply penalises distant keys with a linear bias. Both let you feed longer inputs than training used, often with scaling tricks, but accepting a long prompt is not the same as using it well, so test fact recovery at many depths.
Example. Move the same source fact from token 500 to token 15,000. Compare evidence recovery with the same question and distractors.
Another example. Place one contract clause at token 500, 8,000 and 15,000 of a padded document, ask the same question with the same distractors, and plot accuracy by position.
Two ways to make distance matter
RoPE rotates queries and keys by angles proportional to position, so their dot product depends on the offset. ALiBi subtracts a per-head slope times the distance from each causal score. - Quadratic attention cost
- Dense self-attention compares every query with every key, so the score work per head grows with the square of sequence length while the KV cache grows linearly.
Computing QK transpose for n positions with head size d costs on the order of n squared times d multiply-adds, and the same again for multiplying by V. Tiled kernels avoid storing the n by n matrix, but the arithmetic is still there, so very long prompts make prefill slow. Sparse, sliding-window and linear-attention variants change the arithmetic itself, usually at some cost in what the model can attend to.
Example. Going from 1,024 to 8,192 tokens multiplies score entries per head per layer by 64, but multiplies the KV cache by only 8.
Score entries per head per layer
Sequence length n Score entries n x n Relative to 1k KV cache relative 1,024 1,048,576 1x 1x 2,048 4,194,304 4x 2x 4,096 16,777,216 16x 4x 8,192 67,108,864 64x 8x Prefill pays the quadratic term. Each decode step attends over n cached positions, which is linear per step. - Sliding-window attention
- Each position attends only to the most recent w positions instead of the whole prefix, so attention work and cache per layer stay bounded by the window size.
Windowed layers cap the cost of long inputs, and many models mix them with a few full-attention layers so distant facts can still be reached directly. The risk is a fact that sits beyond every window and is never carried forward, which shows up as accuracy that drops sharply once evidence is further back than the window.
Example. With a 4,096-token window, token 10,000 attends to tokens 5,905 to 10,000. Information from earlier can only arrive indirectly through stacked layers.
Window of 4 positions
Work per token is proportional to w, not to the full length. Each extra layer can carry information roughly one window further back.
How it works
Step through the idea, or press Play.
Active sequence. 2,048 positions
Understand it
Worked example
Estimate the KV cache before doubling context
- 1
2,048 positions
A single sequence is active. The model has 32 layers, 8 KV heads and head dimension 128. Stored cache elements use two bytes.
- 2
2 tensors per layer
Multiply positions by layers, KV heads, dimension, bytes and two for keys and values. Query head count is irrelevant to this particular cache shape.
- 3
256 MiB for this sequence
Doubling context doubles this payload. FlashAttention changes memory traffic for attention computation; it does not make stored history independent of length.
KV-cache payload for one sequence
Follow the handoffs
KV cache for one sequence as context grows
| Positions S | Bytes 2 x 32 x S x 8 x 128 x 2 | Size | Change |
|---|---|---|---|
| 2,048 | 268,435,456 | 256 MiB | baseline |
| 4,096 | 536,870,912 | 512 MiB | doubled |
| 8,192 | 1,073,741,824 | 1 GiB | 4x |
What shrinks the cache
- Fewer KV heads (GQA or MQA)
- Smaller element size, such as an 8-bit cache
- Shorter retained context or a window
What does not
- FlashAttention (it changes traffic, not stored history)
- More query heads sharing the same KV heads
- A bigger GPU (it only raises the ceiling)
Summary
The whole topic in one minute.
Only keys and values are retained in this estimate. Grouped query heads share those stored representations.
Diagnose the actual bottleneck by separating prompt processing, per-token decoding and retained memory. Supporting a larger position index does not by itself establish that the model can recover a fact from the middle of a long document.