Module 2 · Lesson 2.4 of 2.5

KV-Cache Internals

Module 1 showed why a KV cache saves work during generation. This lesson opens the cache: which tensors it holds, what shape they have, when each entry is written, and which computation it removes (and which it does not).

Learning goal: after this lesson you can state exactly what a KV cache stores per layer and position, write its conceptual shape, trace one decode step from input token to appended cache entry, and count the projection work a cache avoids while attention work still grows.

Running example: the 4-token prompt The sky is blue, followed by a fixed toy continuation and the sun shines .. Here “blue” is already part of the supplied prompt, so it is cached during prefill. The first new answer token is “and”. The trace uses the shared 2-component starting embeddings for The/sky/is and the same projection matrices as Lessons 1 and 2.1; other token embeddings are fixed invented values. This is a 1-layer, 1-head toy.

2.4.1 What exactly is cached?

The KV cache stores each processed position’s key and value vectors, separately for every layer and KV head. Later tokens read these stored vectors instead of recalculating them. The current query is used to calculate the current attention result; old queries and attention weights are not stored in the KV cache.

The cache holds keys and values, per layer, per position

  • K and V for every processed position, in every attention layer. Each layer has its own WK, WV and its own input x, so each layer has its own cache entries. With grouped-query attention (Lesson 2.3) each entry has HKV key heads and HKV value heads.
  • Queries are not cached. In causal decoding a new token is always appended at the end. Later tokens never ask an old position to attend again, so a past query qi is never needed after its own forward pass. Old keys and values, in contrast, are read by every later query.
  • Numeric tensors, not token IDs. An entry is a block of floating-point numbers (for example fp16/bf16), the output of a projection. Storing token IDs would force the model to recompute every layer to get K and V back, which is the work the cache exists to avoid.
  • Tied to position and the entire prefix. With additive absolute positional embeddings, the first-layer input xi combines the token embedding with a position embedding. With RoPE instead, that input need not contain a position embedding: position enters by rotating the projected query and key. In a RoPE-only first layer, the cached rotated key depends on position, while the value projection of the same token does not. In every deeper layer, xi is the output of earlier attention over the whole prefix 1…i. The same token in a different context therefore produces different K/V in layers above 0. A cache entry is only valid for the exact prefix that produced it.
  • Old entries are never recomputed when appending. Under a causal mask, appending token p cannot change any earlier position's inputs, so k1…kp−1 and v1…vp−1 stay exactly as computed.
Current input xThis token’s vector at this layer
↓ three learned projections from the same input
QUsed for this token’s comparisons; not kept in the KV cache
K and VOne new row of each is appended to this layer’s cache
↓ current query reads allowed cached keys and values, including this token’s row
Attention resultThen output projection, residual and feed-forward processing → updated vector for the next layer
Q compares with the allowed K rows; the resulting weights mix the corresponding V rows. K/V stay in this layer’s cache. The completed block’s updated token vector goes to the next layer.

RoPE (deeper topic). Many current models use rotary position embeddings: q and k are rotated by angles that depend on their positions just before the dot product, so their score depends on the relative offset. Values are not rotated. Implementations typically cache keys after rotation, so appending tokens at unchanged positions does not require re-rotating old keys. Details vary by implementation and are outside this lesson; the toy model below does not model RoPE.

2.4.2 The conceptual shape of the cache

Collect the per-layer, per-position, per-head key vectors into one tensor, and the value vectors into another. For one sequence (no batch dimension):

Kcache, Vcache ∈ ℝL × T × HKV × D
L
number of attention layers (each has its own cache)
T
number of positions processed so far (grows by 1 per decode step)
HKV
number of key/value heads (equals the query-head count in MHA, 1 in MQA, in between for GQA)
D
head dimension, the length of one key or value vector. Under this lesson’s equal-width assumption, D = d_head = dk = dv: query, key and value heads all have the same width.

Read it as a hierarchy: the KV cache → one layer → its keys or values → one token position → an HKV × D slice. That slice is everything one position contributes to one layer's keys (or values).

Conceptual, not physical. This order is a way to reason about contents, not a universal memory layout. Hugging Face-style caches typically keep one tensor per layer shaped [B, HKV, T, D]; serving engines such as vLLM store K/V in fixed-size blocks (paged layouts), and attention kernels may require their own orderings. Lesson 4.4 (PagedAttention) shows how a serving engine stores K/V in blocks, and Module 3 (GPU architecture) explains the GPU memory those layouts live in. The element count is the same either way.

One indexed cache slice

Structural example: each K or V tensor has shape [4 layers, 4 token positions, 2 KV heads, 4 components]. Fixing layer ℓ = 1 and position t = 2 leaves both heads and all components: shape [2, 4]. Indices start at 0, so this is the second layer and third token, “is”. A colon keeps the whole axis.

Keys determine query–key scores; values supply the vectors mixed using attention weights. Both slices below belong to the same layer and position. These are placeholder indexing values, not projections from a trained model or the shared 2-component numeric trace.

This is a conceptual layout, not a physical storage order required by an attention kernel.

K_cache[ℓ=1, t=2, :, :] — keys, shape [2, 4]
d0d1d2d3
KV head 00.8-0.9-0.7-0.5
KV head 1-0.8-0.6-0.4-0.2
V_cache[ℓ=1, t=2, :, :] — values, shape [2, 4]
d0d1d2d3
KV head 000.20.40.6
KV head 10.30.50.70.9

Each slice has 2 × 4 = 8 elements, or 16 bytes at FP16 (2 bytes per element). A whole K or V tensor has 4 × 4 × 2 × 4 = 128 elements, or 256 bytes. One position across all 4 layers, both K and V: 2 × 4 × 2 × 4 × 2 = 128 bytes.

2.4.3 Building the cache during prefill

The prompt is fully known before generation starts, so prefill processes all of its positions in one parallel forward pass: K = XWK and V = XWV are single matrix multiplications over all 4 rows of X. The causal mask still applies inside that pass: position i scores only keys 1…i.

  1. All 4 positions compute q, k, v together; 4 key rows and 4 value rows are written to the cache.
  2. Each position attends under the causal mask (table above), giving 1 + 2 + 3 + 4 = 10 query–key scores.
  3. Only the last position's output goes on to the model head as next-token logits. Sampling from them gives the first output token.

Cache after prefill: 4 entries per layer (one per prompt position). The first sampled token is not one of them: it has not been through a forward pass, so it has no key or value yet.

2.4.4 Reusing the cache during decode

Each decode forward pass processes exactly one new position p, the token sampled at the end of the previous pass. In each layer, the current token produces one query, one key and one value per corresponding head. Its query attends to the cached keys plus its new key; the resulting weights mix the matching values.

qp = xpWQ, kp = xpWK, vp = xpWV
op = softmax(qp K0:pT / √d) V0:p, K0:p = [Kcache; kp]
p
zero-based index in these equations; equals the cache length before this pass. The tracer labels token positions starting at 1, so its label is p + 1
Kcache, Vcache
the p cached rows for positions 0…p−1, read, not recomputed
K0:p, V0:p
cached rows plus the new row: p + 1 keys and values
d
head dimension, the same width as D = d_head = dk under this lesson’s equal-width assumption (2 in the toy)

The new query still has to be scored against all p + 1 keys: that is the attention work, and the cache does not remove it. What the cache removes is recomputing k and v for the p old positions.

Decode step tracer

What this shows
The cache right after prefill of The sky is blue. Advance one operation at a time to see the current token’s projections, attention calculation and new cache row.
Try
Press Next operation a few times. Before each press, predict the cache length afterwards and how many keys the new query will score.
What to notice
Rows marked reused are read, never recomputed; one row per step is marked new. The cache length counts processed positions; the token just sampled waits outside the cache until the next pass.

Stages of this forward pass

    Assumptions: one attention layer, one KV head, head dimension 2, no batch dimension; invented toy values.

    2.4.5 With versus without a cache

    Here is the same toy run counted pass by pass. Projected positions means the number of token positions whose K/V projections are computed in that forward pass, per layer (multiply by L for a full model). Without cache assumes each decode pass re-runs the whole sequence processed so far. No timings are shown: counts are exact, durations depend on hardware.

    Cumulative projected positions

    What changes and what does not

    • Avoided recomputation: with a cache each decode pass projects 1 position; without one, pass n projects T + n. Over n decode steps, excluding prefill, the cumulative projected-position count is n with a cache and nT + n(n + 1)/2 without, where T is the prompt length.
    • Remaining attention: the new token's query scores p + 1 keys either way, so at decode step n it scores T + n keys, with or without a cache. (A full re-run without a cache would additionally recompute every earlier position's attention row.)
    • KV reads: the cache turns recomputation into memory reads: pass p reads p cached entries per layer. Lesson 2.5 turns this into bytes and bandwidth.
    • KV memory: the cache holds one entry per processed position per layer, growing linearly with sequence length.

    For a prompt length T and n decode forward passes (excluding prefill), the new queries score nT + n(n + 1)/2 keys in total. At fixed head width and head count, decode attention work scales as O(nT + n2). Doubling n gives about 2× work when T greatly exceeds n, and approaches 4× only when n greatly exceeds T. This counts attention work, not elapsed time; it excludes attention rows recomputed for earlier positions in a full uncached re-run.

    Scale the counts up

    What this shows
    The same counters in closed form for any prompt length T and number of decode steps n, per layer and KV head.
    Try
    Double n with T fixed, then compare a long prompt with a short prompt. The scaling depends on both lengths.
    What to notice
    Across n decode forward passes after a prompt of length T, the new queries attend to nT + n(n + 1)/2 keys in total; reads of old cached entries total nT + n(n − 1)/2. These counts exclude prefill. At fixed head width and head count, decode attention work therefore scales as O(nT + n2). Doubling n gives about 2× when the prompt is much longer than the decode, approaching 4× only when decode length greatly exceeds prompt length. These are work counts, not latency predictions.

    Assumptions: counts only (no timings); one sequence; without cache re-runs the whole processed sequence on every decode pass; attended keys count only the scores computed by queries whose output is needed.

    Knowledge check

    References