AI Wiki中文/EN

KV cache: keep yesterday’s keys, compute today’s query

KV 缓存

Verify incremental attention against full prefixes and calculate cache memory and eviction errors.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Do not recompute a prefix that has not changed

A decoder has processed five tokens and now receives the sixth. A simple baseline runs the whole six-token prefix again. A cached decoder computes the new token’s query, key and value at each layer, then combines that query with previously stored keys and values. It avoids rebuilding unchanged prefix states; it still attends to them.

Shazeer describes incremental self-attention and the cost of repeatedly loading its keys and values. The PagedAttention paper, sections 2.1–3.1, separates prompt processing from autoregressive generation and explains why dynamically growing caches create memory-management problems. These are related costs: saving arithmetic does not make storage or memory traffic disappear.

In our two-layer, six-position example, recomputing every prefix processes 42 position–layer pairs; caching processes 12. The resulting vectors agree to floating-point precision. If the cache retains only the latest three entries per layer, the final output changes. “Cache” and “lossless cache truncation” are different claims.

Full caching preserves the computation; eviction and suffix recomputation can produce different states.
Full caching preserves the computation; eviction and suffix recomputation can produce different states.

What is reusable, and under which conditions?

At layer ℓ\ell, let the input state at position tt be htℓ−1h_t^{\ell-1}. With row-vector notation, its projections are:

qtℓ=htℓ−1WQℓ,ktℓ=htℓ−1WKℓ,vtℓ=htℓ−1WVℓ.q_t^\ell=h_t^{\ell-1}W_Q^\ell,\qquad k_t^\ell=h_t^{\ell-1}W_K^\ell,\qquad v_t^\ell=h_t^{\ell-1}W_V^\ell.

The unbounded cache appends the new projected vectors:

K1:tℓ=[K1:t−1ℓ;ktℓ],V1:tℓ=[V1:t−1ℓ;vtℓ].K_{1:t}^\ell=[K_{1:t-1}^\ell;k_t^\ell],\qquad V_{1:t}^\ell=[V_{1:t-1}^\ell;v_t^\ell].

The new attention result uses all stored keys, including the current one:

otℓ=softmax⁡(qtℓ(K1:tℓ)⊤dk)V1:tℓ.o_t^\ell=\operatorname{softmax}\left(\frac{q_t^\ell(K_{1:t}^\ell)^\top}{\sqrt{d_k}}\right)V_{1:t}^\ell.

Why can old entries stay unchanged? With causal attention, appending future tokens does not alter earlier states. Applying that statement layer by layer gives an induction: if lower-layer prefix states are unchanged, their projections and each higher-layer causal output are unchanged too. The argument assumes fixed weights, identical token and position inputs, the same mask and deterministic inference behavior. Training dropout, changed positional conventions, altered prefixes or changed adapters can invalidate reuse. Bidirectional encoder states generally change when new context is appended.

For batch size BB, LL layers, TT stored positions, HKVH_{KV} key–value heads, equal key/value width dd and bb bytes per scalar, logical storage is:

MKV=2BLTHKVdb.M_{KV}=2BLTH_{KV}db.

The factor two counts keys and values. A hypothetical configuration B=1,L=32,T=4096,HKV=32,d=128,b=2B=1,L=32,T=4096,H_{KV}=32,d=128,b=2 requires 2,147,483,648 bytes, exactly 2 GiB. This excludes model weights, activations, allocator overhead, alignment, replicated shards and other serving buffers. It is not a claim about a named model’s actual device allocation.

For a sequence of length TT, the number of projected position–layer pairs when every prefix is recomputed is compared with caching by:

Precompute=LT(T+1)2,Pcache=LT.P_{\mathrm{recompute}}=L\frac{T(T+1)}2,\qquad P_{\mathrm{cache}}=LT.

Here L=2,T=6L=2,T=6 gives 42 and 12. Each counted pair produces all three projections; these are counts, not measured FLOPs or wall-clock speedups. Cached dense decoding still compares each new query with its prefix. Summing those comparisons gives quadratic attention work over the complete sequence, even though repeated projections are removed.

The example layers apply a simple residual nonlinearity:

htℓ=tanh⁡(htℓ−1+otℓ).h_t^\ell=\tanh\left(h_t^{\ell-1}+o_t^\ell\right).

There is no trained embedding, layer normalization, feed-forward block or language-model head. Input rows are fixed numeric states. The purpose is to verify the reuse argument through two contextual layers, not to implement a complete Transformer.

Compare with the full-prefix baseline

The NumPy program runs dense causal attention, incremental attention and a three-entry eviction policy. Each layer has its own cache. The independent checks compare every prefix and alter future inputs to ensure earlier outputs stay unchanged.

"""Two-layer deterministic causal attention; fixed inputs, no training or GPU timing."""
import json
import numpy as np


def softmax(x):
    z = np.exp(x-np.max(x, axis=-1, keepdims=True))
    return z/z.sum(axis=-1, keepdims=True)


def setup(seed=17, length=6, width=4):
    rng = np.random.default_rng(seed)
    x = rng.normal(size=(length, width))
    weights = rng.normal(scale=.3, size=(2, 3, width, width))
    return x, weights


def full(x, weights):
    h = np.asarray(x, dtype=float)
    for wq, wk, wv in weights:
        q, k, v = h@wq, h@wk, h@wv
        scores = q@k.T/np.sqrt(k.shape[-1])
        scores[np.triu_indices(len(h), 1)] = -np.inf
        h = np.tanh(h+softmax(scores)@v)
    return h


def incremental(x, weights, window=None):
    if window is not None and (type(window) is not int or window < 1):
        raise ValueError('Positive integer cache window required')
    caches = [(np.zeros((0, x.shape[1])), np.zeros((0, x.shape[1]))) for _ in weights]
    outputs = []
    for row in x:
        h = row.copy()
        for layer, (wq, wk, wv) in enumerate(weights):
            q, k, v = h@wq, h@wk, h@wv
            oldk, oldv = caches[layer]
            keys, values = np.vstack([oldk, k]), np.vstack([oldv, v])
            if window is not None:
                keys, values = keys[-window:], values[-window:]
            caches[layer] = keys, values
            h = np.tanh(h+softmax(q@keys.T/np.sqrt(len(k)))@values)
        outputs.append(h)
    return np.array(outputs), caches


def cache_bytes(batch, layers, tokens, kv_heads, head_dim, bytes_per_value):
    args = [batch, layers, tokens, kv_heads, head_dim, bytes_per_value]
    if any(type(x) is not int or x < 1 for x in args):
        raise ValueError('Positive integer dimensions required')
    return int(2*np.prod(args, dtype=object))


def main():
    x, w = setup()
    dense = full(x, w)
    cached, stores = incremental(x, w)
    evicted, _ = incremental(x, w, 3)
    print(json.dumps(dict(max_error=float(np.max(abs(dense-cached))),
                         evicted_last_error=float(np.max(abs(dense[-1]-evicted[-1]))),
                         eviction_vs_recomputed_suffix=float(np.max(abs(evicted[-1]-full(x[-3:], w)[-1]))),
                         cache_shapes=[list(k.shape) for k,v in stores],
                         logical_bytes=cache_bytes(1,32,4096,32,128,2),
                         projected_positions=dict(recompute=sum(range(1,len(x)+1))*len(w),
                                                  cached=len(x)*len(w)),
                         outputs=cached.tolist())))


if __name__ == '__main__':
    main()

For the fixed seed, the largest dense-versus-cached difference is about 1.39×10−161.39\times10^{-16}. Each layer ends with key shape 6 by 4 and an equal-shaped value array. That is ordinary floating-point agreement, not a promise of bitwise identity across different kernels or precisions.

Eviction changes the final vector by about 0.161876 in maximum absolute coordinate error. More subtly, its result differs by about 0.148783 from recomputing only the last three input rows. Retained higher-layer cache entries were originally computed using earlier context. Keeping those contextualized entries is not the same computation as starting the suffix from scratch.

The code uses vstack for clarity, so appending copies arrays. A production cache usually needs preallocation or a block allocator to avoid this overhead. The byte calculator describes logical tensor contents, not these Python allocation temporaries. No GPU timing is performed.

A cache needs an identity, not just a token string

Reusing the same word’s cache entry in another sentence is generally invalid. Its higher-layer state depends on preceding tokens, positions, model configuration and attention policy. Prefix sharing requires a matching prefix under a matching computation, rather than a matching last token. The PagedAttention background makes this contextual dependence explicit.

Cache quantization, offloading, sliding windows, grouped heads and paging address different constraints. Quantization can change numeric results; eviction changes available information; paging changes storage organization. Do not attribute all serving improvements to “KV cache” without specifying which operation changed.

The current program does not implement a paged allocator, concurrent requests, beams, rotary-position updates or cache version checks. Its fixed states and weights isolate correctness of incremental attention. A serving implementation also needs tests for request isolation, position offsets, masks and reusing prefixes after a model update.

Check both arithmetic and semantics

  1. In the hypothetical 2-GiB configuration, reduce KV heads from 32 to 8. What is logical storage? Answer: 536,870,912 bytes, or 512 MiB. Everything else is fixed, so storage is divided by four; total serving memory need not shrink by four.
  2. Why does caching not remove all quadratic attention work? Answer: Query tt still reads up to tt keys. Summing these comparisons over the sequence gives a triangular quadratic count, even when each key projection is computed once.
  3. Why can cached eviction disagree with suffix recomputation? Answer: Retained upper-layer states can already encode discarded history. Recomputing the suffix removes that history when constructing those states; the two computations have different inputs internally.
  4. May an entry be shared because two requests end with the same token? Answer: Not in general. Check the preceding prefix, positions, weights and computation settings. Matching the last token alone does not establish matching contextual keys and values.

Reuse creates a storage problem worth solving

Shazeer’s incremental attention motivates reducing how much KV data each decoding step reads. PagedAttention’s background explains why request growth, unknown completion lengths and allocation waste make managing those states a separate systems problem. This chapter verifies the mathematical reuse baseline before introducing more elaborate storage schemes.

Continue with MQA and GQA to change the number of stored KV heads. Their cache savings follow from tensor dimensions; speed and task quality still need measurement under the intended hardware and workload.

Make a prediction, then check

For two cached tensors, what happens to logical KV storage when the KV-head count halves?

Choose one answer

Learning objectives

  • State the conditions for cached decoding to equal prefix recomputation.
  • Calculate logical cache bytes separately from total GPU memory.
  • Explain why eviction and suffix recomputation can disagree.

Prerequisites & connections

Explore related knowledge →

References

  1. Fast Transformer Decoding: One Write-Head is All You Need — v1
    Noam Shazeer · 2019
  2. Efficient Memory Management for Large Language Model Serving with PagedAttention — v1
    Woosuk Kwon; Zhuohan Li; Siyuan Zhuang; Ying Sheng; Lianmin Zheng; Cody Hao Yu; Joseph E. Gonzalez; Hao Zhang; Ion Stoica · 2023

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author read Shazeer v1 incremental attention and PagedAttention v1 PDF3–4/sections2.1–3.1. Six paired equations and four explained exercises. Original two-layer causal attention checked against every full prefix, future invariance, exact logical bytes, eviction and recomputed-suffix counterexample. Engineering article; no GPU allocator, paging kernel or throughput reproduction.

  • Single AI author read Shazeer v1 incremental attention and PagedAttention v1 PDF3–4/sections2.1–3.1. Six paired equations and four explained exercises. Original two-layer causal attention checked against every full prefix, future invariance, exact logical bytes, eviction and recomputed-suffix counterexample. Engineering article; no GPU allocator, paging kernel or throughput reproduction.
  • Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. Twelve final Chinese-mobile/English-desktop screenshots all directly inspected after revisions. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.