Allocate KV cache memory in pages, like vLLM

Paged attention splits the KV cache into fixed-size blocks, the way an operating system splits memory into pages. A request only grabs a new block when its current one is full, so memory is not reserved for tokens that never arrive.

Write allocate_blocks(requests, block_size, num_blocks). requests is a list of (request_id, num_tokens) in arrival order. Physical blocks are numbered 0 to num_blocks - 1 and are handed out lowest number first.

For each request, in order, give it ceil(num_tokens / block_size) blocks. If there are not enough free blocks left, skip that request entirely (it waits) and move on to the next.

Return a dict {request_id: [block numbers]} for the requests that fit.

Signaturedef allocate_blocks(requests, block_size, num_blocks)

Understand the idea

Paged attention stores each request's KV cache in small fixed-size blocks instead of one big reserved chunk, similar to how an operating system gives memory in pages. A request needs just enough blocks to hold its tokens, rounded up. Blocks are handed out from a free list, lowest number first, and a request that cannot get all its blocks is skipped without taking any, so a smaller later request may still fit. Worked example: block_size 4, num_blocks 4. Request A has 6 tokens, needing ceil(6/4) = 2 blocks, so it gets [0, 1]. Request B has 9 tokens, needing 3 blocks, but only 2 are free, so B is skipped. Request C has 3 tokens, needing 1 block, so it gets [2]. Result: {A: [0, 1], C: [2]}. Rule: blocks needed = (tokens + block_size - 1) // block_size; allocate only if that many are free. vLLM uses this idea to serve many more requests on the same GPU.

Part of the advanced LLM architecture track.

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

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

  • Sample 1: two requests fitallocate_blocks([("a", 20), ("b", 5)], 16, 4)
  • Sample 2: exact multipleallocate_blocks([("a", 32)], 16, 4)