Prove a KV cache preserves the answer
Compare cached and uncached attention on the same inputs, check exactness, and see why this trace is not a speed benchmark.
A KV cache is justified by an identity: for a causal transformer, the keys and values at earlier positions do not change when a new token is appended. Reusing them should produce the same attention output as recomputing the whole prefix. If that identity fails, the cache is a bug, however fast it is.
This example checks the identity on random tensors, at a sequence length large enough for the loop to do real work. It also exposes a trap. The cached path issues one small attention call per token from Python, while the uncached path issues one larger batched call. On a CPU, launch and Python overhead can make the cached version slower even though it performs fewer arithmetic operations. The example therefore teaches two separate questions: is the answer the same, and is the implementation faster?
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch10/kv_cache.py --seq-len 64 --d-head 32 --jsonPython 3.11 or later with PyTorch installed. The tensors are CPU-only and seeded, so no model download, network, GPU or credentials are needed. It finishes in well under a second.
Implementation
KVCache stores one key tensor and one value tensor per position. The cached
function attends a single query to everything appended so far. The uncached
function builds the same causal mask for the whole sequence and attends every
query at once.
class KVCache:
def __init__(self) -> None:
self.keys: List[torch.Tensor] = []
self.values: List[torch.Tensor] = []
def append(self, key: torch.Tensor, value: torch.Tensor) -> None:
self.keys.append(key)
self.values.append(value)
def all_keys(self) -> torch.Tensor:
return torch.stack(self.keys, dim=0)
def all_values(self) -> torch.Tensor:
return torch.stack(self.values, dim=0)
def __len__(self) -> int:
return len(self.keys)
def attention_no_cache(qs: torch.Tensor, ks: torch.Tensor, vs: torch.Tensor) -> torch.Tensor:
# qs,ks,vs: [seq, d_head]
d_head = qs.shape[-1]
scores = (qs @ ks.T) / math.sqrt(d_head)
mask = torch.triu(torch.ones(qs.shape[0], ks.shape[0], dtype=torch.bool), diagonal=1)
scores = scores.masked_fill(mask, float("-inf"))
weights = torch.softmax(scores, dim=-1)
return weights @ vs
def attention_cached_last(q: torch.Tensor, cache: KVCache) -> torch.Tensor:
# q: [1, d_head] or [d_head]; uses all cached keys/values.
d_head = q.shape[-1]
keys = cache.all_keys() # [seq, d_head]
values = cache.all_values()
q2 = q.reshape(1, d_head)
scores = (q2 @ keys.T) / math.sqrt(d_head)
weights = torch.softmax(scores, dim=-1)
return (weights @ values).reshape(d_head)Expected outcome
Observed with the command above (exit 0). The stable fields were:
"seq_len": 64,
"max_abs_error": 4.76837158203125e-07,
"cache_entries": 64,The maximum absolute difference is 4.77e-07, consistent with float32 rounding,
not with a different result. The cache held 64 entries for 64 positions. On this
particular CPU trace the uncached call took about 0.00065 s and the cached loop
about 0.0019 s: the cached path was roughly 2.9 times slower. That number is a
property of this implementation and machine, not evidence against caching. It is
exactly the kind of measurement the chapter warns against generalising.
Mechanism and limitations
Documented: run_comparison seeds torch, creates query, key and value
tensors, computes the full causal attention, then replays it position by
position through the cache and reports the maximum absolute difference and the
number of entries. The test file asserts parity below 1e-5, the uncached output
shape, JSON serialisation and a non-negative cached duration.
Observed: the command exited 0 with max_abs_error 4.76837158203125e-07
and cache_entries 64. The cached loop was slower in this trace. The targeted
test command python -m unittest tests.test_ch10_kv_cache -v ran 5 tests and
reported OK.
Not shown: the memory footprint of a real cache, GPU bandwidth effects, a production cache eviction policy, or speed on a transformer. The tensors are random and the attention is single-head. A correct result at 64 positions does not establish correctness at 100,000 positions, with paged storage, or after a prefix is shared between requests. The timing is not a benchmark and must not be turned into a speedup claim.
Challenge this result
Change attention_cached_last so that it divides the scores by
math.sqrt(d_head) * 2 while leaving the uncached path unchanged. Predict the
reported error, then run it: parity should fail because the two paths no longer
compute the same function. Then restore the scale and mutate one cached key
tensor after append; the cached answer should change while the uncached answer
does not. Explain which of these failures a real serving system could detect from
its output alone.
Source and verification
Canonical source:
examples/ch10/kv_cache.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch10_kv_cache.py
.
Chapter: Key-Value Caching
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15 and
PyTorch 2.6.0+cu124; it is not the book’s recorded model measurement.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.