6.1.13 · D1Scaling & Efficient Architectures

Foundations — KV-cache optimization

2,968 words13 min readBack to topic

Before you can understand why we cache K and V (and not Q), you must know what every letter and picture in the parent note actually means. This page builds them in order, each one leaning on the previous. Nothing is assumed.

Related maps: 6.1.13 KV-cache optimization (Hinglish) · parent KV-cache optimization · prerequisites 6.1.1-transformer-architecture, 6.1.4-multi-head-attention.


1. A token and its embedding — the atom of everything

The picture: imagine a row of boxes, one per word: "The cat sat". Each box is replaced by an arrow of numbers pointing in "meaning space". Position is "The", is "cat", and so on.

Why the topic needs it: the whole cost story is "what happens per token". If you don't know that each token becomes a vector , you can't count what gets computed for it.

Figure — KV-cache optimization
Figure 1 — three word-boxes "The", "cat", "sat" at positions , each with a downward arrow into a bracketed list of numbers: the embedding vector of length .

The number of components in one embedding arrow is the model dimension . Big models use (GPT-2 small) up to thousands. That single number shows up everywhere in the cost formulas, so pin it down now.

Notation
is the embedding vector for the token at position ; is how many numbers it holds.

2. Q, K, V — three questions asked of every token

Attention (built in 6.1.4-multi-head-attention) turns each token's embedding into three new vectors by multiplying it by three fixed number-grids (matrices) called , , .

The picture — a library: every past book has a spine label (its Key) and contents (its Value). The new token walks in with a search slip (its Query). It compares its slip against every spine label, then pulls contents from the books that match best.

Figure — KV-cache optimization
Figure 2 — two past-token "books" each showing a green Key label and a blue Value content, plus one orange new-token "search slip" with dashed red arrows comparing it against each Key.

Why the topic needs it — and this is the heart of caching: a past token's label and contents never change once written. But every new token brings a fresh search slip . That asymmetry is exactly why we cache K and V but recompute Q.

Recall Why can't we cache Q?

Because Q is the new token's question, which is different for every step. K and V are old tokens' fixed answers. ::: Correct.

What is ?
A fixed matrix of shape (learned in training, frozen during generation) that maps an embedding to its Key vector .

3. The multiply that ranks the books — and the dot product

To measure how well a search slip matches a spine label, attention uses the dot product: multiply matching components and add them up. A big dot product = strong match.

Pinning down the shapes (this is where novices get lost): at generation step there is one new query, a row vector and there are cached keys stacked into a matrix, one key per row:

To dot the query against every key at once, we need each key laid out as a column. The transpose does exactly that — it turns the stack of rows into a block of columns:

Now the shapes line up for a matrix multiply: one score per past token. The inner dimensions must match and cancel — that is the whole reason we transpose.

The picture: the query arrow's shadow cast onto each key arrow — the longer the shadow, the higher the score.

Figure — KV-cache optimization
Figure 3 — an orange query vector and three key vectors from the origin; dotted projection lines show (green) aligns most with , giving the highest dot-product score.

In the parent note's single-layer worked example (generating the 3rd token, 4 heads, ), produces exactly 3 scores — one per past position — matching the row of length we derived above.

Why divide by ?
To keep the scores from growing huge as grows, which would make the next step (softmax) too spiky. It's a stabiliser.

4. Softmax — turning scores into a choice

The picture — a pie chart of attention: bigger raw score → bigger slice, and all slices sum to one whole pie. The exponential exaggerates the leader so the strongest match dominates but nothing is fully ignored.

Figure — KV-cache optimization
Figure 4 — left: a bar chart of three raw scores; right: the same scores after softmax shown as a pie whose three slices sum to 1, the largest score taking the biggest slice.

Why the topic needs it — and where V's shape enters: these weights multiply the cached Values to blend them into one output. Stack the Value vectors the same way we stacked Keys: The softmax output is a row of weights, shape . Multiplying shapes: The inner cancels, so a weight row times the Value stack yields one length- output vector — a weighted blend of all the Values. So the full attention formula

reads left-to-right as: score the labels → turn into a piemix the contents.


5. Heads, , and — splitting the work

One attention isn't enough, so the model runs several in parallel — each is a head.

What counts as a "layer"? A transformer stacks identical blocks on top of each other; each block is a layer (6.1.1-transformer-architecture builds these). One layer contains its own attention (with its own ) plus a feed-forward network. GPT-2 small has such layers; a GPT-3-style model has . Let = number of layers. Every layer keeps its own separate KV-cache, which is why full-model memory multiplies by .

Why the topic needs it: cache memory is counted per head, per layer, per token. Now that , and are all defined, the memory formula reads:

The is because we store two things: the Key stack and the Value stack.


6. Multi-Query Attention — where the -fold saving comes from

The memory derivation, made explicit:

With heads, MQA stores less KV-cache, because K and V are each stored once (at length ) instead of times. Quality typically drops only 1–2%.


7. Autoregressive generation and the causal mask

The picture — a lower-triangular grid: row (the attending token) can fill in columns (itself and the past) but the upper-right triangle (the future) is blacked out.

Figure 5 — an grid indexed by attending position (rows) and key position (columns); green cells hold (allowed), red upper-right cells hold (future blocked).

Why the topic needs it: because the mask guarantees a token only ever attends to positions , and those past K,V are frozen — that is the exact license to cache them. Even with a cache you must still add the mask, or the model would illegally read future positions.


8. Big-O, , and the cost we're fighting

Why the topic needs it: the entire motivation is a cost comparison. The projection cost per token is per layer (a matrix times a length- vector, summed over heads gives ). Big-O hides the constant factors (layers) and the per-head split, so the clean formulas below are per-layer projection costs; multiply by layers for the full model:

For a 100-token sequence, that's roughly less projection work. The parent note's GPT-2-small worked example (which does include the layer factor on both sides, so it cancels) measures a real speedup for — a bit under the ideal because attention itself still costs a little each step, but the same order of magnitude.

Meaning of vs ?
Per-layer projection cost: the first is quadratic in length (naive), the second linear (cached). Their ratio is , the speedup. Multiply either by layers for the whole model.

The two classic mistakes (why they're wrong, in one line each)


Prerequisite map

Token and embedding x_t

Q K V projections

Model dimension d

Dot product Q times K transpose

Softmax weights

Attention output

Heads h and head dim d_k

Autoregressive generation

Causal mask

Cost in Big-O with length L

KV-cache optimization

Each foundation feeds the next; together they justify why caching K and V (not Q) is safe and cheap. Deeper follow-ups: 6.2.3-inference-optimization, 6.1.11-sparse-attention, 6.3.1-model-quantization, 7.2.1-llm-deployment, 5.4.2-beam-search.


Equipment checklist

Test yourself — cover the right side.

What is ?
The embedding (vector of numbers) for the token at position .
What does mean?
The model dimension — how many numbers are in one embedding.
Q, K, V in one word each?
Query = what I seek; Key = my label; Value = my content.
What shape is each projection matrix ?
— it maps a length- embedding to a length- vector.
Which of Q, K, V get cached, and why?
K and V — they belong to past tokens and never change; Q is fresh each step.
What are the shapes in at step ?
is , is , so is and the scores are .
Why does softmax() give a length- output?
A weight row times the Value stack cancels the inner , leaving .
What does softmax do?
Turns raw scores into positive weights that sum to 1 (a pie of attention).
Relationship , , ?
.
What is precision in the memory formula?
Bytes per stored number — fp16 is , fp32 is .
Total KV-cache footprint formula?
(K+V, all layers, all tokens).
Why the factor of 2 in the cache memory formula?
Two stacks are stored: K and V.
What is a "layer" and why does it matter for the cache?
One transformer block (attention + feed-forward); each of the layers holds its own KV-cache, so memory scales with .
What does MQA change structurally, and by how much does the cache shrink?
All heads share one K and one V (stored at size , not ), shrinking the cache by a factor .
What are the dimensions of the causal mask, and how is it applied?
An matrix added to the raw scores before softmax; for and for .
Naive vs cached per-layer generation cost, and the speedup?
vs ; speedup (multiply by for full model).