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).
def 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)