Write new keys and values into a preallocated batched KV cache

Why it matters Every decode step of a batched LLM server writes one key and value per sequence into a preallocated cache, so this indexing is on the hot path.

Serving engines allocate one big KV cache buffer up front and then write each new token's key and value into the next free slot of every sequence, instead of growing arrays with concatenate.

Write kv_write(cache_k, cache_v, lengths, k_new, v_new, active=None). cache_k and cache_v have shape (B, H, T, D). lengths (B,) holds how many slots each sequence has filled. k_new and v_new have shape (B, H, D). For every active sequence b, write k_new[b] and v_new[b] at time slot lengths[b] for all heads and add 1 to its length. active is an optional (B,) boolean array; inactive rows (finished or padding sequences) are left untouched. If an active row is already full (lengths[b] == T), raise ValueError. Do not modify the inputs: return new arrays (cache_k, cache_v, new_lengths).

Signaturedef kv_write(cache_k, cache_v, lengths, k_new, v_new, active=None)

Example

B=2, H=1, T=3, D=2 zero caches, lengths [0, 2], k_new [[[1, 2]], [[3, 4]]] gives cache_k[:, 0] = [[[1, 2], [0, 0], [0, 0]], [[0, 0], [0, 0], [3, 4]]] and new lengths [1, 3].

Understand the idea

Think of the KV cache as a notebook with T empty lines per sequence. Each decode step, every sequence writes one new line: its key and value for the token it just produced. Because sequences in a batch started at different times, sequence 0 may be on line 3 while sequence 1 is on line 7, so each row needs its own write position. Worked example: lengths are [0, 2] and T is 3. Sequence 0 writes at slot 0 and becomes length 1; sequence 1 writes at slot 2 and becomes length 3, which is now full. Rule: cache[b, :, lengths[b]] = new[b], then lengths[b] += 1, skipping rows that are not active and refusing to write past T. Real servers preallocate this buffer once because growing arrays every token would copy the whole cache again and again.

Shapes and data flow

cache (B, H, T, D)  k_new (B, H, D)  write cache[b, :, lengths[b], :] = k_new[b]  (H, D)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: example(lambda r: (r[0][:, 0], r[2]))(kv_write(np.zeros((2, 1, 3, 2)), np.zeros((2, 1, 3, 2)), [0, 2], [[[1, 2]], ...
  • Sample 2: values tookv_write(np.zeros((2, 1, 3, 2)), np.zeros((2, 1, 3, 2)), [0, 2], [[[1, 2]], [[3, 4]]], [[[10, 20]], [[30, 4...
  • Test 3: inactive row(lambda r: (r[0][:, :, :, 0], r[2]))(kv_write(np.zeros((3, 2, 2, 1)), np.zeros((3, 2, 2, 1)), [1, 0, 2], [[...
  • Test 4: full raises_raises(lambda: kv_write(np.zeros((1, 1, 2, 1)), np.zeros((1, 1, 2, 1)), [2], [[[1]]], [[[1]]]))