Paged KV Block Allocation
A paged-attention server stores each request's KV state in fixed-size blocks. Implement required_kv_blocks(token_counts, block_size). Return one block count per request, using ceiling division for each nonnegative token count. A zero-token request uses zero blocks. block_size is positive. Calculate requests independently because partially filled blocks cannot be shared between them.
Explore the underlying concept with illustrative inputs. This experiment is separate from the problem’s test cases.
KV caching
Decode tokens while keeping keys and values aligned in a bounded window.
Retained token positions
Dense example: 1 request × 1 tokens × 32 layers × 8 KV heads × 128 dimensions × 2 bytes × 2 (K and V) = 0.125 MiB.
Change the experiment
keys = (keys + [new_key])[-capacity:]
values = (values + [new_value])[-capacity:]Try it yourself
Set a capacity of two and decode five tokens. Which pairs remain, and how many were evicted?
1 tokens decoded. 1 cached pairs; 0 evicted.
Cached keys and values avoid recomputing their projections for earlier tokens. Attention still reads the retained cache.
Playback pauses in hidden tabs and offscreen. With reduced motion enabled, use the timeline or Next step.Examples
A guided view of the published example, not a trace of your code.
[[1,16,17,0],16][1,1,2,0]Start with the input values shown in this example.
Input: token_counts = [1,16,17,0], block_size = 16
Output: [1,1,2,0]
Explanation: block boundaries
Input: token_counts = [8,8], block_size = 16
Output: [1,1]
Explanation: no block sharing
Hint 1
Apply ceiling division to each request separately.