04KV cache for incremental decoding (PyTorch)

hardtorch
50:00

04 KV cache for incremental decoding (PyTorch)

Four levels in solution.py. Read one level at a time and run only its tests until they pass: pytest problems/04_kv_cache -k level1. Earlier levels must keep passing.

CachedAttention(n_embd, n_head) is causal multi-head self-attention that can decode incrementally. Same layout as problem 02: self.qkv = nn.Linear(C, 3 * C) split q, k, v, heads (B, n_head, T, C // n_head), and self.proj.

forward(x, cache=None) -> (y, cache):

  • x is (B, T_new, C): the new tokens only.
  • cache is None or a tuple (k, v), each (B, n_head, T_past, head_dim): the keys and values of every earlier token.
  • The new tokens sit at positions T_past .. T_past + T_new - 1. They attend to every past token and causally to each other.
  • Return y (B, T_new, C) and the cache grown to T_past + T_new.

Level 1. No cache yet: forward(x) is causal multi-head attention, and it returns the keys and values it computed, (B, n_head, T, head_dim) each, as the cache.

Level 2. One token at a time: after a prompt, feed one token per call with the cache, and the outputs side by side equal one full pass. The cache grows on the time axis.

Level 3. Chunks: feed several new tokens per call with a cache. The causal mask has to shift by T_past.

Level 4. CachedAttention(n_embd, n_head, n_kv_head=None): grouped-query attention with a smaller cache. self.qkv makes C + 2 * n_kv_head * head_dim outputs, the queries, then the keys, then the values, and the cache holds only the n_kv_head key/value heads, (B, n_kv_head, T, head_dim). Query head h reads key/value head h // (n_head // n_kv_head). n_kv_head=None means n_head, the layout above. Raise ValueError when n_kv_head doesn't divide n_head.

Things to get right: the causal mask offset when the cache is not empty (the classic bug), which axis to concatenate on, repeating the key/value heads only when you attend, never in the cache, and the memory math: the cache holds 2 * n_layer * n_kv_head * head_dim * T * bytes_per_value per sequence, which is why grouped-query attention, paged attention and quantized caches exist.

solution.py
Run the tests to see which pass.