InferenceAI

Enter at least two characters to search.

Start free

Paged KV Block Allocation

mediumInference20 min25 XP

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.

INTERACTIVE ENGINEERING · TEACHING MODEL

KV caching

Decode tokens while keeping keys and values aligned in a bounded window.

Retained token positions

Token 1K1V1
EmptyKV
EmptyKV
EmptyKV
Retained pairs1
Evicted pairs0

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

Core calculation
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.

Open the full explainer and practice links

Examples

EXAMPLE WALKTHROUGHblock boundaries

A guided view of the published example, not a trace of your code.

INPUT[[1,16,17,0],16]
TASKrequired_kv_blocks()
EXPECTED OUTPUT[1,1,2,0]

Start with the input values shown in this example.

Example 1 of 2

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.

Topics

PythonPaged AttentionGPU Memory