867. Fix the KV cache that grows the wrong axis
Why it matters KV caching is the core trick of fast LLM decoding. Concatenating on the head axis silently creates extra heads instead of extra tokens.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
append_kv(cache_k, cache_v, new_k, new_v) should append new keys and values to a per-layer KV cache along the sequence axis.
Inputs:
- cache_k and cache_v are lists or ndarrays of shape (heads, seq, d), or None for an empty cache.
- new_k and new_v have shape (heads, t, d) for t new tokens.
Return a tuple (k, v) of ndarrays of floats with shape (heads, seq + t, d). With an empty cache, return the new arrays as floats.
def append_kv(cache_k, cache_v, new_k, new_v)Example 1
Input: append_kv([[[1.0, 1.0]]], [[[2.0, 2.0]]], [[[3.0, 3.0]]], [[[4.0, 4.0]]])
Output: ([[[1.0, 1.0], [3.0, 3.0]]], [[[2.0, 2.0], [4.0, 4.0]]])
Example 2
Input: cache_k = None, cache_v = None, new_k = [[[1.0]], [[2.0]]], new_v = [[[3.0]], [[4.0]]]
Output: ([[[1.0]], [[2.0]]], [[[3.0]], [[4.0]]])
Constraints
new_vhas shape(heads, t, d)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Print the output shape for the two-head test.
Hint 2
Which axis is the sequence?
Hint 3
Concatenate on axis=1.
Common mistakes
- Using axis=-1, which grows the head dimension.
- Stacking with
np.stack, which adds a new axis. - Mutating the input lists.
Understand the idea
The cache layout is (heads, seq, d). A new token adds one position for every head, so it must go on axis 1. Axis 0 would produce a (2 * heads, seq, d) array, which still has a valid shape for some code paths and only fails later in attention. With one head the bug is easy to miss, so test with several heads.
Shapes and data flow
cache: (H, S, d). new: (H, t, d). Output: (H, S + t, d).