Lesson 3.4: Scaling attention: cost, memory and KV caches
See why attention gets expensive on long sequences, how blockwise attention avoids storing the big matrix, and how a key-value cache makes generation fast.
By the end of this lesson you will be able to count the memory and arithmetic of attention as the sequence grows, compute attention in blocks without ever holding the full score matrix, explain and build a key-value cache, and size the cache of a real-shaped model. You will show that blockwise attention gives the same result as full attention while holding 256 of 65,536 score entries at once, that cached generation produces identical outputs at every one of 64 steps while computing 64 key and value rows in place of 2,080, and that a decoder with 32 layers and 32 heads of 128 numbers needs 0.5 MiB of cache per token (2 GiB at 4,096 tokens and 64 GiB at 131,072), a quarter of that with 8 key-value heads. You need Python and NumPy, helpers.py from Lesson 3.1 and attention.py from Lesson 3.2.
Module 3 has built attention and trained it. Our models were tiny: windows of 16 tokens. Real models read thousands, and in some cases hundreds of thousands, of tokens. The T by T matrix of scores, which cost nothing at T = 16, starts to dominate. And generation, where a model writes one token at a time, raises a second problem: done naively, it repeats almost all of its work at every step. This lesson looks at both, and at the two ideas that answer them. The lesson ends the module on attention, and prepares the next module, which assembles attention into a full transformer.
The cost of the square
Attention compares every position with every position. For a sequence of T tokens, each head builds a T by T matrix of scores. Two costs follow.
Arithmetic. Lesson 3.2 counted it: about 2 T² d multiply-adds for the scores and the weighted sums, against about 4 T d² for the four projections. The ratio is T divided by 2d. For our 16-token window and width 16, the ratio is 0.5, and the projections dominate. For a model with width 4,096 reading 32,768 tokens, the ratio is 4, and attention dominates. Doubling the sequence doubles the projections and quadruples the attention.
Memory. If the score matrix is stored, it takes T² numbers per head per layer. In 32-bit numbers that is 4 bytes each.
python
GiB = 1024 3
def scorebytes(T, pernumber=4):
"""One T x T score matrix for one head in one layer, in 32-bit numbers."""
return T T pernumber
def kvbytespertoken(layers, kvheads, headdim, pernumber=2):
"""Keys and values for one token, all layers (16-bit numbers)."""
return 2 layers kvheads headdim pernumber
for T in (1024, 8192, 32768, 131072):
print(T, round(scorebytes(T) / 1024 2, 1), "MiB per head per layer")
an example decoder of a common shape: 32 layers, 32 heads of 128 numbers, 16-bit cache
pertoken = kvbytespertoken(32, 32, 128)
print("bytes per token:", pertoken, "=", pertoken / 1024 2, "MiB")
for T in (1024, 4096, 32768, 131072):
print(T, round(pertoken T / GiB, 2), "GiB for one sequence")
print("batch of 8 at 4096:", round(8 pertoken 4096 / GiB, 1), "GiB")
for kv in (32, 8, 1):
print(kv, "key-value heads:", round(kvbytespertoken(32, kv, 128) 4096 / GiB, 4), "GiB at 4096 tokens")
The first four lines of output, for one head in one layer:
Sequence length T · Score matrix, 32-bit1,024 · 4 MiB
8,192 · 256 MiB
32,768 · 4,096 MiB (4 GiB)
131,072 · 65,536 MiB (64 GiB)
Each time the sequence grows by a factor of 4, the matrix grows by a factor of 16. At 131,072 tokens, a single head of a single layer would need 64 GiB, more than the memory of most accelerators, and a model has many heads and many layers. Storing the score matrices cannot scale.
Attention in blocks
The score matrix is not needed after its rows have been turned into weights and used. What we want is the output, a weighted sum of values. There is a way to get it without storing the whole matrix: process the keys in blocks, keeping a running summary.
The difficulty is the softmax, which needs the maximum and the sum over a whole row. The trick is online softmax. For each query, keep three running quantities as blocks of keys arrive: the largest score so far m, the sum of exp(score minus m) so far l, and the weighted sum of values so far acc. When a new block brings a larger maximum, rescale what you have by exp of the old maximum minus the new one. At the end, divide acc by l. The result is exactly the softmax-weighted sum, and no more than one block of scores was ever in memory.
python
import numpy as np
def fullattention(Q, K, V):
T, dh = Q.shape
S = Q @ K.T / np.sqrt(dh)
S = np.where(np.triu(np.ones((T, T), dtype=bool), 1), -np.inf, S)
A = np.exp(S - S.max(axis=1, keepdims=True))
return (A / A.sum(axis=1, keepdims=True)) @ V
def blockwiseattention(Q, K, V, block):
"""Same result, but never holds more than a (block x block) piece of the score matrix."""
T, dh = Q.shape
out = np.zeroslike(V)
biggest = 0
for i in range(0, T, block): # a block of queries
q = Q[i : i + block]
m = np.full(len(q), -np.inf) # running maximum score for each query
l = np.zeros(len(q)) # running sum of exp(score - m)
acc = np.zeros((len(q), V.shape[1])) # running weighted sum of values
for j in range(0, i + block, block): # only blocks at or before the diagonal
k, v = K[j : j + block], V[j : j + block]
s = q @ k.T / np.sqrt(dh)
rows, cols = np.arange(i, i + len(q))[:, None], np.arange(j, j + len(k))[None, :]
s = np.where(cols > rows, -np.inf, s) # causal mask inside the block
biggest = max(biggest, s.size)
mnew = np.maximum(m, s.max(axis=1))
scale = np.exp(m - mnew) # shrink what we had before
p = np.exp(s - mnew[:, None])
l = l scale + p.sum(axis=1)
acc = acc scale[:, None] + p @ v
m = mnew
out[i : i + block] = acc / l[:, None]
return out, biggest
rng = np.random.defaultrng(0)
T, dh = 256, 32
Q, K, V = (rng.standardnormal((T, dh)) for in range(3))
ref = fullattention(Q, K, V)
for block in (16, 64):
out, biggest = blockwiseattention(Q, K, V, block)
print(block, np.allclose(out, ref), "largest piece held:", biggest, "of", T T)
The output is:
16 True largest piece held: 256 of 65536
64 True largest piece held: 4096 of 65536
With blocks of 16, the code reproduces full attention exactly (True) while holding at most 256 scores at a time, out of 65,536. With blocks of 64 it holds 4,096. Because of the causal mask, it also skips blocks above the diagonal entirely: the loop over j stops at the diagonal, which saves about half the work.
This is the idea behind FlashAttention (Dao and colleagues, 2022), which is how large models avoid storing the score matrix. Our NumPy version shows the arithmetic, and not the speed. The real gain comes from running the blocks in the fast on-chip memory of a GPU, so the matrix never travels to the slow main memory. The memory for attention then grows with T, not T squared, although the arithmetic is still T squared.
Generation repeats itself
Now the second problem. A language model writes text one token at a time. At each step it runs on all the tokens so far, takes the output for the last position, picks a token, appends it and goes again. At step 100, it processes 100 tokens to find one.
Look at what is repeated. The key and value of token 5 depend only on token 5 and the tokens before it (and, in a deeper model, on the layers below, which also depend only on the past). That is the effect of the causal mask. They were computed at step 5. At steps 6, 7, 8 and so on, they are computed again, and they come out the same. Generating n tokens computes 1 + 2 + ... + n = n(n+1)/2 key and value rows when only n differ.
The fix is the KV cache. Keep the keys and values of all positions so far. At each step compute the query, key and value of the new token only, append the new key and value to the cache, and attend from the new query to the whole cache. Past keys and values are never recomputed. Queries are not cached, since only the newest position's query is ever needed.
python
import numpy as np
from helpers import
from attention import
d, h, steps = 16, 2, 64
dh = d // h
p = init(V, d, seed=0, scale=0.3)
P = sinusoidal(steps + 1, d)
def nextlogitsnocache(tokens):
"""Run the whole sequence again and keep the last position. Count K and V rows computed."""
logits, = forward(p, np.array([tokens]), h, P)
return logits[0, -1], len(tokens)
def projectone(tok, pos):
H = p["E"][tok] + P[pos] # (d,)
return H, (H @ p["Wq"]).reshape(h, dh), (H @ p["Wk"]).reshape(h, dh), (H @ p["Wv"]).reshape(h, dh)
def nextlogitscached(tok, pos, cache):
H, q, k, v = projectone(tok, pos)
cache["K"].append(k); cache["V"].append(v) # remember this position's key and value
K, Vv = np.stack(cache["K"]), np.stack(cache["V"]) # (pos+1, h, dh)
scores = np.einsum("hd,thd->ht", q, K) / np.sqrt(dh) # no mask needed: the cache holds only the past
out = np.einsum("ht,thd->hd", softmax(scores), Vv).reshape(d)
return (H + out @ p["Wo"]) @ p["U"], 1
rng = np.random.defaultrng(0)
tokens = [stoi["."]]
cache = {"K": [], "V": []}
rowsplain = rowscached = 0
same = True
for pos in range(steps):
a, n1 = nextlogitsnocache(tokens)
b, n2 = nextlogitscached(tokens[-1], pos, cache)
rowsplain += n1; rowscached += n2
same = same and np.allclose(a, b)
tokens.append(int(rng.choice(V, p=softmax(a))))
print("same logits at every step:", same)
print("K and V rows computed without cache:", rowsplain, " with cache:", rowscached)
print("generated:", " ".join(vocab[t] for t in tokens[1:9]), "...")
The output:
same logits at every step: True
K and V rows computed without cache: 2080 with cache: 64
generated: fish bus a . slowly slowly drum found ...
The cached and uncached versions give the same logits at all 64 steps, as the first line shows. The second line shows the saving: 2,080 key and value rows without the cache, 64 with it, which is n(n+1)/2 against n. At n = 64, the cache does 32.5 times less projection work, and the ratio grows as (n+1)/2 with the length. (The sampled words are gibberish, because this is a randomly initialised model. The check is for equality of the numbers, not for good text.)
There is no mask in the cached code. The cache contains only the past, so the new query can attend to everything in it. The causal property is built in by what is stored.
What the cache costs: memory
The cache trades arithmetic for memory. It holds, for every token so far, a key and a value in every layer: 2 times the number of layers times the number of key-value heads times the head size, in numbers. For a decoder of a common shape, with 32 layers, 32 heads of 128 numbers each and a 16-bit cache (2 bytes per number):
per token: 2 × 32 × 32 × 128 × 2 bytes = 524,288 bytes, which is 0.5 MiB.
That is a model of a typical size, chosen to show the scale, not a description of any particular product. The cache grows linearly with the length.
Tokens in the sequence · Cache for one sequence1,024 · 0.5 GiB
4,096 · 2 GiB
32,768 · 16 GiB
131,072 · 64 GiB
A server handling a batch of 8 sequences of 4,096 tokens holds 16 GiB of cache, as the last lines of the code printed. The weights of the model are a fixed cost. The cache is a cost per user and per token, and it is often what limits how many people a server can handle at once, and how long their conversations can be.
Making the cache smaller
Because the cache limits serving, much work goes into shrinking it.
Fewer key-value heads. In multi-query attention (Shazeer, 2019), all the query heads share a single key head and a single value head. In grouped-query attention (Ainslie and colleagues, 2023), the query heads are split into groups, and each group shares one key-value head. The queries still have 32 heads, but the cache has 8, or 1. For the example model at 4,096 tokens, 32 key-value heads need 2 GiB, 8 need 0.5 GiB and 1 needs 0.0625 GiB: a reduction of 4 and of 32. The cost is a small loss in quality, which has been judged acceptable in many models.
A smaller number format. Storing keys and values in 8 bits halves the cache again, at some cost in accuracy.
Keeping less. A sliding window lets each token attend only to the last W tokens, so the cache stops growing after W. Some layers use full attention and some a window.
Smarter memory management. A server that reserves the maximum length for every sequence wastes memory. Paged caches (Kwon and colleagues, 2023) allocate the cache in small blocks as it grows, like pages in an operating system, and share the blocks of a common prompt between sequences.
The picture for generation
Putting the two together shows two stages in generating a reply.
Prefill. The model reads the whole prompt in one pass. All positions are processed in parallel, so this stage is limited by arithmetic, and it is where the T-squared attention cost is paid. The keys and values are saved.
Decode. The model produces one token at a time. Each step does little arithmetic: one query against the cache. But it must read the whole cache and all the weights from memory for a single token, so this stage is limited by memory speed. Everything that shrinks the cache makes decoding faster and lets a server serve more people.
This split explains many facts about how language model services behave: a long prompt takes a moment before the first word appears, and then the words arrive at a steady rate. Lesson 9.2 comes back to it.
Key takeaways
Attention compares every position with every other, so its arithmetic grows with T squared and its stored score matrix with T squared per head per layer. A 131,072-token matrix would be 64 GiB for one head of one layer.
The attention arithmetic exceeds the projections once T is greater than twice the width.
Blockwise attention uses an online softmax, with a running maximum, a running sum and a running weighted sum, to produce the exact output while holding only one block of scores. With blocks of 16 it held 256 of 65,536 entries and matched full attention.
Generating naively recomputes keys and values for every earlier token at every step: 2,080 rows for 64 tokens.
A KV cache stores the keys and values of all past positions, so each step computes one row and attends to the cache: 64 rows for 64 tokens, identical outputs. The work saved grows as (n+1)/2.
The cache costs memory: 2 × layers × key-value heads × head size × bytes per number, per token. For 32 layers and 32 heads of 128 numbers in 16 bits, that is 0.5 MiB per token, 2 GiB at 4,096 tokens and 64 GiB at 131,072.
Fewer key-value heads shrink the cache: 32, 8 and 1 key-value heads need 2, 0.5 and 0.0625 GiB at 4,096 tokens.
Generation has two stages: prefill, limited by arithmetic, and decode, limited by memory reads.
Common mistakes
Caching queries. Only the newest position's query is used. Cache keys and values.
Forgetting that the cache grows. Memory per sequence grows linearly with the length, and each user has one.
Computing the cache for a sequence with the wrong positions. The new token's position vector must be its true position, not zero.
Applying the mask twice or not at all in cached code. With a cache that holds only the past, no mask is needed for the new token.
Comparing cached and uncached outputs loosely. They should agree to about 12 digits. If they differ more, there is a bug.
Assuming blockwise attention is faster in NumPy. It saves memory, and speed comes from the hardware it is designed for.
Estimating cache size from the weights. A model's weights and its cache are different budgets. A long conversation can need more cache than the model needs for its weights.
Check yourself
1. How many numbers are in the score matrices of 12 heads for a sequence of 2,048 tokens, in one layer?
12 × 2,048² = 12 × 4,194,304 = 50,331,648 numbers.
2. Why is the attention arithmetic more important for long sequences than the projections?
Attention grows with the square of the length and the projections only with the length. The ratio is T divided by 2d, so once T passes twice the width, attention dominates.
3. Why can the keys and values of past tokens be cached, and not recomputed?
The causal mask means they depend only on the token and earlier tokens, which do not change as the text is extended.
4. How many key and value rows does generating 200 tokens compute without a cache and with one?
Without: 200 × 201 ÷ 2 = 20,100. With: 200.
5. A model has 24 layers, 16 key-value heads of 64 numbers and a 16-bit cache. How large is the cache per token?
2 × 24 × 16 × 64 × 2 = 98,304 bytes, which is 96 KiB.
6. By what factor does grouped-query attention with 4 key-value heads shrink the cache of a model with 32 heads?
32 ÷ 4 = 8 times.
Try this
Set aside two hours. You need Python, NumPy, helpers.py and attention.py.
1. Run the cached generation code. Change steps to 16 and to 256, and print the number of rows computed in each case.
2. Time the cached and uncached generators with time.perfcounter. Plot the time per step against the step number for each. What shape does each have?
3. Run the blockwise attention code with T = 1,024 and blocks of 32, 128 and 512. Check it still matches, and print the largest piece held.
4. Break the online softmax on purpose by skipping the rescaling line. How wrong is the result?
5. Compute the cache size for a model you know the configuration of. How many sequences of 8,000 tokens fit in 24 GiB, after the weights?
6. Change projectone and nextlogitscached to use 2 key-value heads shared by 4 query heads (a grouped-query layer). Check that the output stays the same shape, and compute the cache saving.
A good result is a blockwise attention that matches full attention to many digits, a cached generator that matches the uncached one at every step, and a table of cache sizes for a configuration you chose. This completes Module 3. The next module puts attention into a full transformer block, with residual connections, normalisation and a feed-forward layer.
Read more
Tri Dao, Daniel Fu, Stefano Ermon, Atri Rudra and Christopher Ré, "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness" (2022), describes blockwise attention with an online softmax on a GPU. Noam Shazeer, "Fast Transformer Decoding: One Write-Head Is All You Need" (2019), introduced multi-query attention. Joshua Ainslie and colleagues, "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints" (2023), introduced grouped-query attention. Woosuk Kwon and colleagues, "Efficient Memory Management for Large Language Model Serving with PagedAttention" (2023), describes paged caches.
Tags: Build an LLM KV cache Attention cost Memory Inference