Three tricks, three different problems
A fully trained model should write fast and need little memory. Three techniques help with that without changing anything that was learned:
- The KV cache remembers intermediate results instead of recomputing them for every new token.
- GQA lets several attention heads share the same keys and values, saving memory.
- FlashAttention computes attention in small blocks so less data is shuffled back and forth in memory.
Three different bottlenecks: duplicate work, storage space and data traffic. When someone promises “faster attention”, it is worth asking: what exactly is being saved?
Two terms that come up often: a kernel is a small program for one calculation, tailored to specific hardware. A benchmark is a standardized measurement, for example of speed.
The KV cache: don't compute everything twice
So far, something wasteful happens when generating: for every new token, the model runs through the entire previous text again. With 1000 tokens of text, that means recomputing 1000 positions just to add a single one.
Yet the keys and values of the old positions don't change at all; the mask makes sure old positions learn nothing from new ones. So you can simply keep them. That is the KV cache: every layer stores the keys and values of all previous positions. For a new token, only its own query, key and value are computed. The new query then reads the stored keys and values plus the new entry. Like mental arithmetic with a notepad: write down intermediate results instead of starting from scratch every time.
There are two phases. During prefill the model reads the complete prompt at once: many positions in parallel, and the cache gets filled. During decode exactly one new token is added at a time.
How much memory does the cache need?
The cache grows with every layer, every token and every conversation running at the same time. An example: 6 layers, 1024 stored tokens, 2 key/value heads with 64 numbers each, 2 bytes per number, times 2 (keys and values) gives 3,145,728 bytes, so 3 MiB. For a single conversation.
Sounds small. But with large models with many layers, long texts and thousands of users at once, the cache becomes the biggest memory hog, often bigger than the model itself. Hence the next tricks.
Cache size as a formula
For L layers, B simultaneous texts, T stored positions, key/value heads, head width d and e bytes per number:
The 2 stands for K and V. With the numbers from above: 2 × 6 × 1 × 1024 × 2 × 64 × 2 = 3,145,728 bytes. One MiB is 1024 × 1024 = 1,048,576 bytes.
GQA: heads share notepads
In normal multi-head attention, every query head has its own keys and values, and they all have to go into the cache. Grouped-query attention (GQA) lets groups of query heads use the same keys and values. With 8 query heads and 2 key/value heads, four query heads share each set.
So the questions stay diverse (8 different queries), but the labels and contents are shared. That shrinks the cache to a quarter, and quality suffers surprisingly little. The extreme where all heads share a single set is called multi-query attention (MQA). Original GQA paper.
repeat = cfg.heads // cfg.kv_heads
k_for_attention = k.repeat_interleave(repeat, dim=1)
v_for_attention = v.repeat_interleave(repeat, dim=1)
out = F.scaled_dot_product_attention(q, k_for_attention, v_for_attention, is_causal=True)This version simply copies the shared keys and values as often as they are needed. Easy to understand, but not the most economical implementation; optimized versions avoid the copies.
A trap: the mask with a cache
Careful when building it yourself: normally there are as many queries as keys. With a cache there is suddenly one query (the new token) and a thousand keys (all previous ones). A blindly copied triangular mask might then block the wrong keys. But the new token is supposed to see all previous ones. RoPE also has to know the real position of the new token, not “position 0”.
That is why our project deliberately doesn't have a built-in KV cache yet; it is a task for advanced readers. The golden rule: with and without the cache, exactly the same predictions must come out. A cache that is faster but delivers different tokens is simply broken.
FlashAttention: less hauling
Normal attention builds the complete score table (every position with every other) in the large, slow graphics memory. With long texts that is a huge table, and hauling it back and forth costs more time than the computing itself.
FlashAttention instead computes in small blocks in the chip's fast cache and assembles the result piece by piece with a clever softmax trick. The result is exactly the same; there is just less hauling. Like cooking where you put the ingredients next to the stove in portions instead of running to the cellar for every pinch. FlashAttention.
PyTorch automatically picks a suitable kernel depending on the device and situation. Whether FlashAttention actually runs on your computer isn't revealed by the function name alone. Measure!
More tricks of the big players
Two more common methods: multi-head latent attention (MLA) stores a compressed summary per token instead of keys and values, shrinking the cache even more than GQA (DeepSeek-V2). Speculative decoding lets a small, fast model propose a few tokens, and the big model checks them all in one go. If they fit, you get several tokens for the price of one, and with the right acceptance rule the result is the same as if the big model had written alone (Leviathan et al., 2022).
Your extension plan
If you want to build a KV cache yourself: first for the classic decoder, without context shifting. At every position compare the predictions with and without the cache. Then add RoPE with the correct position offset and compare again. Only after that, GQA caches and long contexts.
Key points
- The KV cache stores the keys and values of previous tokens so not everything gets recomputed when generating.
- GQA lets several query heads share the same keys and values. That makes the cache much smaller.
- FlashAttention delivers the same result but pushes far less data through memory.