Simulate KV memory preemption with recompute

Why it matters Preemption policy decides tail latency under memory pressure in every paged-attention server, and getting the queue order wrong starves old requests.

When a busy server runs out of KV blocks mid-decode, it preempts a running request: frees its blocks and puts it back in the queue to recompute its KV later. Generated tokens are kept, only the cache is rebuilt.

Write simulate_preemption(requests, total_blocks, block_size, max_batch). requests is a list of (rid, prompt_len, out_len), all waiting at the start in that order. A request holding t tokens (prompt plus generated) uses ceil(t / block_size) blocks. Each step (numbered from 1):
1. Admit: while the waiting queue is non-empty and fewer than max_batch are running, look at the head. If ceil((prompt + generated) / block_size) blocks are free, allocate them and append it to the running list; otherwise stop admitting.
2. Grow: go through running requests in running-list order. If the next token needs one more block and none is free, preempt the last request in the running list (free its blocks, put it at the front of the waiting queue) and try again; stop if the request preempted itself.
3. Every request still running generates one token. A request that reaches out_len generated tokens finishes: free its blocks and record the step.
Raise ValueError if any single request needs more than total_blocks blocks at its full length. Return (finish, preemptions) where finish is a dict rid to finish step and preemptions is the total count.

Signaturedef simulate_preemption(requests, total_blocks, block_size, max_batch)

Example

requests [("a", 3, 3), ("b", 3, 3)], total_blocks 4, block_size 2, max_batch 2 gives ({"a": 3, "b": 5}, 1).

Understand the idea

Preemption is like a crowded parking lot where cars grow longer as they drive. When there is no space for the next car to grow, the attendant asks the most recently arrived car to leave and come back first in line later. With recompute, the car comes back and rebuilds its KV cache from the prompt plus the tokens it already produced. Worked example: 4 blocks of 2 tokens, two requests of prompt 3 each take 2 blocks. In step 2 request a needs a third block for its 5th token but nothing is free, so b (newest) is preempted and goes to the front of the queue. Rule: blocks(t) = ceil(t / bs); evict the tail of the running list until the grower fits. Serving engines choose recompute when re-running prefill is cheaper than copying KV to CPU memory.

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

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

  • Sample 1: examplesimulate_preemption([('a', 3, 3), ('b', 3, 3)], 4, 2, 2)
  • Sample 2: no pressuresimulate_preemption([('a', 2, 2), ('b', 1, 3)], 10, 2, 4)