Causal Self-Attention with a KV Cache
Key idea: during generation, keys and values of past tokens never change, so cache them; each new token computes only its own query/key/value and attends over the cache — O(T) work per step instead of recomputing O(T²) attention. The result must equal full causal attention.
import numpy as np
def causal_attention(x, Wq, Wk, Wv): # x: (T, d) -> (T, d_v), single head
q, k, v = x @ Wq, x @ Wk, x @ Wv
s = q @ k.T / np.sqrt(k.shape[-1])
s = np.where(np.tril(np.ones(s.shape, bool)), s, -np.inf) # token t sees 0..t
w = np.exp(s - s.max(-1, keepdims=True))
return (w / w.sum(-1, keepdims=True)) @ v
class KVCache:
def __init__(self):
self.k, self.v = [], []
def step(self, x_t, Wq, Wk, Wv): # x_t: (d,) — only the newest token
q = x_t @ Wq
self.k.append(x_t @ Wk)
self.v.append(x_t @ Wv)
K, V = np.stack(self.k), np.stack(self.v)
s = K @ q / np.sqrt(K.shape[-1])
w = np.exp(s - s.max())
return (w / w.sum()) @ V
rng = np.random.default_rng(0)
T, d = 6, 8
x = rng.normal(size=(T, d))
Wq, Wk, Wv = (rng.normal(size=(d, d)) / np.sqrt(d) for _ in range(3))
full = causal_attention(x, Wq, Wk, Wv)
cache = KVCache()
incremental = np.stack([cache.step(x[t], Wq, Wk, Wv) for t in range(T)])
assert np.allclose(full, incremental)
print("ok, cache holds", len(cache.k), "keys; memory per token per layer = 2 * d values")
Real KV-cache memory: 2 · layers · kv_heads · head_dim · bytes per token — which is why GQA/MQA (fewer KV heads) and paged allocation matter.