Track shared KV blocks with copy-on-write for beam search
Why it matters Copy-on-write block sharing is what makes beam search and n parallel samples cheap in paged-attention servers.
Beam search and parallel sampling fork a sequence many times. With paged KV, forks share their blocks and only copy a block when one of them writes into a shared, partly filled block. This is copy-on-write.
Write cow_blocks(prompt_len, block_size, ops). Sequence 0 starts with prompt_len tokens in ceil(prompt_len / block_size) fresh blocks. Each block has a reference count. ops is a list of:
- ("fork", src, new): new gets the same block list and token count as src; every shared block's refcount goes up by 1.
- ("append", seq): seq writes one token. If its token count is a multiple of block_size (including 0), allocate a fresh block. Otherwise, if its last block has refcount > 1, copy it: allocate a fresh block, decrease the old block's refcount, replace the last entry, and count one copy. Then the token count goes up by 1.
- ("free", seq): decrease the refcount of each of its blocks; a block whose count reaches 0 is released.
Return (peak, copies, in_use): the highest number of live blocks at any moment, the number of copies, and the number of live blocks at the end.
def cow_blocks(prompt_len, block_size, ops)Example
prompt_len 3, block_size 2, ops [("fork", 0, 1), ("append", 0), ("append", 1), ("append", 1)] gives (4, 1, 4).
Understand the idea
Copy-on-write is like several students sharing one printed handout. Nobody photocopies it until someone wants to scribble on a page that others are still reading. For a KV cache, forks of a beam share all the prompt blocks. Full blocks are read-only forever, so they are shared safely. Only the last, partly filled block is a problem, because two forks want to write different next tokens into the same free slot. Worked example: prompt 3 tokens, block size 2, so blocks A (full) and B (one token). Fork gives both sequences [A, B] with B's refcount 2. Sequence 0 appends: B is shared, so it gets a copy C. Now sequence 1 owns B alone and can write without copying. Rule: copy only if (tokens % bs != 0) and ref[last] > 1. This keeps beam search memory close to one prompt plus small per-beam tails.