One New Token, All the History: How a KV Cache Reuses Each Layer's Results
Given ABC, the model selects D. To predict E, the next round can process ABCD again, or process D with a cache for ABC. Both routes let D read information from ABC; the difference is whether old positions are computed again.
A KV cache stores the keys and values already computed at each layer for this request. Every position uses the same learned projection matrices WQ, WK, and WV. What grows as the sequence gets longer is the number of cached rows.
The complete routes: the same first pass, different later passes
The figure uses a teaching model with two layers, four attention heads, and 32 dimensions per head, with RoPE, RMSNorm, and SwiGLU. Script names and line numbers locate calls in that implementation; the tensors and data flow are the reading guide. The two-dimensional calculation below uses a smaller head, so its shapes must not be mixed with the overview’s.
The first pass through the prompt is prefill. In the figure, all 32 prompt tokens pass through the embedding layer and every block. The resulting tensor has shape [B,32,d_model], where B is the batch size and d_model is the model width.
Applying the output head at every position gives [B,32,vocab_size]. Each row scores possible successors to its own position. To continue the prompt, take the last row and select one new ID per sequence.
Later cached passes process only newly supplied positions: decode. For one sequence:
| Round | Full recomputation | New input to cached route | Cache after this forward pass | Selected ID |
|---|---|---|---|---|
| 1 | ABC | ABC | ABC K/V in every layer | D |
| 2 | ABCD | D | ABCD K/V in every layer | E |
| 3 | ABCDE | E | ABCDE K/V in every layer | F |
Selecting D’s ID does not compute D’s QKV. D acquires its activations when it is embedded and processed in the next round. The final position has already gathered historical information through attention, so using its output does not mean considering only the final input token.
Why historical K/V stays valid: follow causality through the layers
When a full forward pass is repeated on ABCD, C’s query has a dot product with one more key. Call the new score sCD. Because D comes after C, the causal mask replaces sCD with −∞ before softmax. C’s masked row is
[sCA,sCB,sCC,−∞]The extra softmax denominator term is exp(−∞)=0. Existing weights stay unchanged and D receives zero weight. C’s attention output remains:
H_C = a_CA v_A + a_CB v_B + a_CC v_C + 0 × v_DThis extends beyond the first layer. Unchanged old token IDs and positions give unchanged first-layer inputs. The causal mask prevents reading the appended suffix, so old outputs remain unchanged. The next layer receives the same historical representations and produces the same historical K/V. Induction applies to every layer. Hugging Face’s cache explanation likewise describes reuse of historical K/V on a per-layer basis.
The conditions matter: fixed weights, eval mode with Dropout disabled, fixed position rules, and suffix-only extension. LayerNorm/RMSNorm and the MLP operate along each position’s features rather than mixing new positions into old statistics. Changing the prefix, weights, or position rules invalidates the relevant cache. Different floating-point execution paths can introduce small differences; mathematical equivalence does not require bitwise identity.
K/V is also not a permanent vector attached to a vocabulary ID. The same token in different contexts can produce different K/V, particularly in later layers. The reusable object belongs to a particular layer, request, and set of processed positions.
Step 04: a new Q reads both old and new K/V
For one layer and one head:
K_old = [k_A; k_B; k_C] V_old = [v_A; v_B; v_C]Compute q_D, k_D, v_D from D in this round.K_all = [k_A; k_B; k_C; k_D]V_all = [v_A; v_B; v_C; v_D]
A_D = softmax(q_D K_allᵀ / √d)H_D = A_D V_allQ/K has already received the model’s position transformation. D’s new Q still compares with every visible K, and all corresponding V rows can contribute. Supplying one new ID does not restrict attention to one position.
| Work this round | Recompute ABCD | Process D with cache |
|---|---|---|
| Newly computed Q rows | 4 | 1 |
| Newly computed K/V rows | 4 each | 1 each |
| K/V rows used by attention | 4 each | 4 each |
| Score matrix per head | 4×4 | 1×4 |
| Positions processed by MLP | ABCD | D |
Historical Q has finished gathering information for historical positions. Future positions need their own Q to query history, so a standard KV cache stores K/V rather than old Q. D still traverses every block, each with its own historical cache.
Step 05: store by layer, append along the position axis
A tuple can hold each layer’s K/V pair:
cache = ( (layer0_k, layer0_v), (layer1_k, layer1_v),)Each tensor has shape [B,Hkv,S,d]: batch size, KV heads, processed positions, and dimensions per head. The figure uses MHA, so Hkv equals the Q head count. GQA reduces Hkv; see the forward-pass comparison.
With past holding the current layer’s previous cache and new k/v already computed:
k = torch.cat((past[0], k), dim=2)v = torch.cat((past[1], v), dim=2)Old K [1,4,32,32] and new k [1,4,1,32] become [1,4,33,32]. The outer generation loop receives the updated per-layer cache and supplies it in the next round:
# Teaching pseudocode: decoder returns last-position logits and all layer caches.cache = Noneids = prompt_idsfor _ in range(new_tokens): current = ids if cache is None else ids[:, -1:] logits, cache = decoder(current, cache) token = logits[:, -1, :].argmax(dim=-1, keepdim=True) ids = torch.cat((ids, token), dim=1)ids retains the complete output ID sequence; cache retains K/V for computed positions. Actual inference uses eval mode and disables gradient recording, with separate stopping rules for EOS and length limits.
Keeping a reference to each layer’s tensors keeps the cache available for the next round. In this implementation, torch.cat allocates a tensor and copies the old and new rows into it. An implementation with preallocated storage can write the new rows at the next free position.
Step 06: do not reset positions or blindly reuse a square mask
RoPE needs the position offset
With S=32 cached positions, the next token’s zero-based position is 32. Its new input length is one, but its rotation must not use position zero:
start = 0 if past is None else past[0].shape[2]cos = rope.cos[start:start + length]sin = rope.sin[start:start + length]This implementation caches rotated K and unrotated V. Rotate new q/k at their new positions, then append k. Old K is already rotated and must not be rotated again. The RoPE supplement explains the position-dependent angles.
This code assumes the cache retains all history, making its length equal to the next absolute position. A sliding-window implementation that evicts entries needs separate absolute-position tracking.
New query indices include the historical length
For one new token, every cached key and its own key are visible. Now suppose the cache holds positions 0–2 and positions 3 and 4 arrive together. The query at 3 must still be prevented from reading 4. With two queries and five keys, the allowed entries are
key position 0 1 2 3 4query position 3 1 1 1 1 0query position 4 1 1 1 1 1The rule is still key_position ≤ query_position, but query indices include S. Applying a plain upper-left-aligned lower triangle to a 2×5 matrix would incorrectly block much of the history. Check an attention API’s causal alignment for non-square inputs; an explicit offset-aware mask makes the intended visibility easier to inspect.
Step 07: how old V contributes to the new output
The figure’s lower example uses one two-dimensional head. These are teaching values; Q/K has already received position processing:
K_old = [[1,0], [0,1], [1,1]]V_old = [[1,0], [0,2], [1,1]]q_new = [1,0] k_new = [2,1] v_new = [2,0]Appending gives four K/V rows. Dot products with the new query are [1,0,1,2]. Divide by √2 and apply softmax:
A ≈ [0.221181, 0.109057, 0.221181, 0.448581]H[0] = A₀×1 + A₁×0 + A₂×1 + A₃×2 ≈ 1.339523H[1] = A₀×0 + A₁×2 + A₂×1 + A₃×0 ≈ 0.439296The new value contributes zero to the second component. Its entire output of 0.439296 comes from the values at B and C. This is the output of one head, before concatenation, output projection, and the residual connection.
Steps 08–09: count generated tokens, computation, and memory separately
For a prompt of P tokens and N generated tokens without early stopping, there is one prefill and N−1 decode passes. The final selected token is never fed back, so the final sequence contains P+N IDs while the cache contains P+N−1 positions.
The figure uses P=32 and N=16:
Final output length 32 + 16 = 48Cached positions 32 + 15 = 47
Positions processed per layer, recomputation: 32 + 33 + … + 47 = 632Positions processed per layer, cached: 32 + 15 = 47632/47 is a ratio of processed positions, not a measured speedup. Each new Q still accesses growing K/V tensors, and concatenation, memory traffic, and calls have costs. Compare per-round logits and generated IDs under the same weights, inputs, and execution conditions before measuring prefill/decode time. The figure’s measurement procedure promises no fixed speedup for arbitrary models.
For L layers, batch B, Hkv KV heads, head width d, S cached positions, and b bytes per element:
Live K/V bytes = 2 × L × B × Hkv × S × d × bFigure: 2 × 2 × 1 × 4 × 47 × 32 × 4 = 96,256 bytesThis counts live K/V only, excluding model weights, workspaces, temporary concatenation copies, and allocator reservations. GQA reduces Hkv; caching avoids recomputation. These are distinct changes that can work together.
The same position count determines how much context the model sees. With 32 cached positions and one new token, the query can attend to 33 positions. Count the entire prefix when budgeting for the model’s context limit.