KV Cache Memory Estimate
A serving team needs to admit requests without exhausting GPU memory. Implement kv_cache_bytes(batch, tokens, layers, kv_heads, head_dim, bytes_per_value). Return the integer number of bytes for a dense KV cache. Each layer stores one key and one value for every token, request, KV head, and head dimension. Return 0 if any dimension is zero. All inputs are nonnegative integers.
Formula: batch * tokens * layers * kv_heads * head_dim * bytes_per_value * 2.
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,1024,32,8,128,2]134217728Start with the input values shown in this example.
Input: batch = 1, tokens = 1024, layers = 32, kv_heads = 8, head_dim = 128, bytes_per_value = 2
Output: 134217728
Explanation: one 1K-token request
Input: batch = 4, tokens = 512, layers = 24, kv_heads = 4, head_dim = 64, bytes_per_value = 2
Output: 25165824
Explanation: batched grouped-query attention
Hint 1
A token has both a key and a value at every layer.
Hint 2
Use KV heads, not query heads.