InferenceAI

Enter at least two characters to search.

Start free

KV Cache Memory Estimate

mediumInference20 min25 XP

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.

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 WALKTHROUGHone 1K-token request

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

INPUT[1,1024,32,8,128,2]
TASKkv_cache_bytes()
EXPECTED OUTPUT134217728

Start with the input values shown in this example.

Example 1 of 2

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.

Topics

PythonKV CacheGPU MemoryLLM Serving