Work out how many tokens fit in GPU memory for the KV cache
Serving capacity is often set by KV cache memory, not by compute. Every token stores one key and one value vector per layer per key/value head.
Write kv_cache_bytes(tokens, layers, kv_heads, head_dim, bytes_per_value=2): 2 (key and value) x tokens x layers x kv_heads x head_dim x bytes_per_value.
Write max_tokens(free_bytes, layers, kv_heads, head_dim, bytes_per_value=2): the largest whole number of tokens whose cache fits in free_bytes.
def kv_cache_bytes(tokens, layers, kv_heads, head_dim, bytes_per_value=2)Example
32 layers, 8 KV heads, head_dim 128, 2 bytes each is 131,072 bytes (128 KiB) per token.
Understand the idea
Every token an LLM keeps in context stores a key vector and a value vector in every layer for every key/value head. So the memory per token is a simple product, and dividing free memory by it tells you how many tokens fit. Like working out how many boxes fit on a shelf when you know each box size. Worked example from the prompt: 2 (key and value) x 32 layers x 8 KV heads x 128 head_dim x 2 bytes = 131,072 bytes per token. With 1 GiB free (1,073,741,824 bytes) you can hold 1,073,741,824 // 131,072 = 8,192 tokens. Smaller case: 2 layers, 1 KV head, head_dim 4, 2 bytes gives 2x2x1x4x2 = 32 bytes per token; with 100 bytes free, 100 // 32 = 3 tokens. Rule: bytes = 2 x tokens x layers x kv_heads x head_dim x bytes_per_value; max tokens = free // per-token bytes. Serving teams use this to set batch sizes and context limits.
Similar problems
Part of the advanced LLM architecture track.