Run a paged KV block allocator with a free list

Why it matters Paged KV memory managers in LLM servers do this bookkeeping every step, and an allocator that leaks or half-allocates blocks causes out-of-memory errors under load.

A paged KV allocator hands out fixed-size blocks as sequences grow and takes them back when sequences finish. Recently freed blocks are reused first because they are still warm in cache.

Write run_allocator(num_blocks, block_size, ops). The free list is a stack: at the start, popping gives block 0, then 1, then 2 and so on. ops is a list of tuples:
- ("append", seq, n): seq gains n tokens (a new seq starts at 0 tokens). It needs ceil(total_tokens / block_size) blocks in total; pop the missing ones from the free list and add them to the end of its table. If there are not enough free blocks, the whole append fails: nothing changes and seq is added to a rejected list.
- ("free", seq): push all of seq's blocks onto the free stack in table order (so its last block is the next one handed out) and forget seq.

Return (tables, rejected) where tables is a dict seq to list of block ids for live sequences and rejected is the list of seq ids whose appends failed, in order.

Signaturedef run_allocator(num_blocks, block_size, ops)

Example

num_blocks 3, block_size 2, ops [("append", "a", 3), ("append", "b", 1), ("free", "a"), ("append", "c", 2)] gives ({"b": [2], "c": [1]}, []).

Understand the idea

An allocator with a free list is like a stack of clean plates at a buffet. You always take the top plate, and washed plates go back on top. For KV memory, a plate is one block holding block_size tokens. A sequence only takes a new block when its last block is full. Worked example: block size 2, three blocks. Sequence a appends 3 tokens, needs ceil(3 / 2) = 2 blocks and takes 0 and 1. Sequence b takes block 2. Freeing a pushes 0 then 1, so the next sequence gets block 1 first. Rule: need = ceil(total / bs) - held; succeed only if need <= free count. All-or-nothing allocation matters because a request that half grows can neither run nor release memory cleanly. Paged attention servers use exactly this pattern to pack many requests into one GPU.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplerun_allocator(3, 2, [('append', 'a', 3), ('append', 'b', 1), ('free', 'a'), ('append', 'c', 2)])
  • Sample 2: grow in placerun_allocator(4, 4, [('append', 1, 3), ('append', 1, 1), ('append', 1, 1), ('append', 2, 4)])