DEV Community

jidonglab
jidonglab

Posted on

KV Cache Math: Llama 3.1 8B Needs 16 GiB for One 128K Request

My 8B model weighed 16 GB. My GPU had 24 GB. I did the math a junior engineer does, decided I had 8 GB of headroom, and typed vllm serve meta-llama/Llama-3.1-8B-Instruct.

vLLM refused to start.

ValueError: The model's max seq len (131072) is larger than the maximum
number of tokens that can be stored in KV cache (...). Try increasing
`gpu_memory_utilization` or decreasing `max_model_len` when initializing
the engine.
Enter fullscreen mode Exit fullscreen mode

The number in the parentheses was a little over 40,000. The model wanted 131,072. The thing eating my "8 GB of headroom" was the KV cache, and the KV cache math is the single most useful napkin calculation you can learn if you self-host LLMs. One 128K-token request on Llama 3.1 8B needs 16 GiB of KV cache on its own. That is more than the whole budget I had left.

TL;DR

  • KV cache bytes per token = 2 × layers × KV heads × head_dim × bytes per element. For Llama 3.1 8B in FP16 that is 131,072 bytes, exactly 128 KiB per token.
  • One 128K-token sequence = 16 GiB of KV cache. Weights (~15 GiB) plus that will not fit on a 24 GB card, so vLLM refuses to boot at the default max_model_len.
  • The KV cache is shared across all concurrent requests. 5 GiB of free cache is about 40K tokens total: one 32K request, or five 8K requests, not both.
  • Fixes, in order: set --max-model-len to what you actually use, try --kv-cache-dtype fp8 (halves the cache), and raise --gpu-memory-utilization carefully.
  • Grouped-query attention (GQA) is why this is survivable at all. Llama 2 7B, without GQA, needed 4x more cache per token.

What is the KV cache, in one paragraph?

The KV cache stores the key and value vectors for every token the model has already seen, in every layer, so it does not recompute them for each new token. Generating token 5,001 means attending to tokens 1 through 5,000, and their keys and values sit in GPU memory waiting. Without the cache, every generated token would reprocess the whole prompt. With it, memory grows linearly with context length, and that growth is the bill nobody puts on the spec sheet.

How do you calculate KV cache size per token?

Multiply 2 (one K, one V) by the number of layers, the number of KV heads, the head dimension, and bytes per element. Every number comes straight out of the model's config.json.

def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_elem=2):
    return 2 * layers * kv_heads * head_dim * bytes_per_elem

# Llama 3.1 8B: 32 layers, 8 KV heads, head_dim 128, FP16
per_tok = kv_bytes_per_token(32, 8, 128)
print(per_tok)                     # 131072 bytes = 128 KiB
print(per_tok * 131072 / 2**30)    # 16.0 GiB for one 128K sequence
print(per_tok * 32768 / 2**30)     # 4.0 GiB for one 32K sequence
Enter fullscreen mode Exit fullscreen mode

The config fields you want are num_hidden_layers, num_key_value_heads, and head_dim (or hidden_size / num_attention_heads when head_dim is missing). Note it is KV heads, not attention heads. Llama 3.1 8B has 32 query heads but only 8 KV heads. Plug in 32 and you will overestimate by 4x.

Here is the same formula on a few common configs, FP16 cache:

Model Layers KV heads head_dim Per token One 32K seq
Llama 2 7B 32 32 128 512 KiB 16 GiB
Llama 3.1 8B 32 8 128 128 KiB 4 GiB
Mistral 7B 32 8 128 128 KiB 4 GiB
Qwen2.5 7B 28 4 128 56 KiB 1.75 GiB
Llama 3.1 70B 80 8 128 320 KiB 10 GiB

Look at Llama 2 7B. Same layer count and head size as Llama 3.1 8B, four times the cache. That gap is grouped-query attention, and it is the reason long context on consumer GPUs went from fantasy to merely annoying.

Why does vLLM refuse to start with the default max_model_len?

vLLM checks at startup that at least one full-length sequence fits in the KV cache, and Llama 3.1 8B advertises 131,072 tokens of context. The budget works out like this on a 24 GB card:

24 GiB total VRAM
× 0.90 gpu_memory_utilization (default)     = 21.6 GiB usable
− ~15.0 GiB weights (8.03B params × 2 bytes)
− ~1.5 GiB activations, CUDA graphs, misc    (varies by version)
= ~5 GiB left for KV cache
÷ 128 KiB per token                          ≈ 40,000 tokens
Enter fullscreen mode Exit fullscreen mode

40K tokens of capacity against a 131K-token requirement. vLLM is doing you a favour by failing loudly here. The alternative is a server that boots, accepts a long document, and falls over in production.

The thing that bit me was the mental model. I thought of "the model" as the memory cost. For serving, the model is the fixed cost and the KV cache is the variable cost, and the variable cost scales with tokens in flight across all users, not with requests.

Why does throughput collapse when concurrent requests grow?

Because every in-flight token from every request competes for the same KV cache pool. vLLM's PagedAttention splits that pool into blocks (16 tokens each by default) and hands them out on demand, which kills fragmentation but does not create memory.

With ~40K tokens of cache:

  • 1 request at 32K context: fits, with room for a few short ones
  • 5 requests at 8K each: fits, barely
  • 10 requests at 8K each: does not fit

When it does not fit, the scheduler preempts sequences. In vLLM's default recompute mode, a preempted request has its blocks freed and its prompt re-prefilled later. Your latency graph grows a long tail, GPU utilization looks fine, and nobody can explain why p99 doubled. Check the logs for preemption warnings before you blame the network.

Remember output tokens count too. A 6K prompt with max_tokens=2048 will hold up to 8K tokens of cache by the time it finishes.

How do you fix KV cache out-of-memory in vLLM?

Set max_model_len to the context you actually serve, then shrink the cache per token, then (last) squeeze more memory out of the GPU. This is the config I landed on:

vllm serve meta-llama/Llama-3.1-8B-Instruct \
  --max-model-len 16384 \
  --kv-cache-dtype fp8 \
  --gpu-memory-utilization 0.92
Enter fullscreen mode Exit fullscreen mode

1. --max-model-len. This is the boring fix and the right one. My longest real prompt plus output was under 12K tokens. Advertising 128K just reserved a promise I could never keep. At 16K, one full sequence needs 2 GiB in FP16, and the startup check passes with room for concurrency.

2. --kv-cache-dtype fp8. Stores K and V in one byte instead of two. Per-token cost drops from 128 KiB to 64 KiB, which doubles your token capacity. This is lossy. Most chat workloads won't notice, but run your own eval set before and after, especially for long-context retrieval tasks where small attention errors add up. Hardware and backend support varies, so check your vLLM version's docs.

3. --gpu-memory-utilization. Raising 0.90 to 0.92 on a 24 GiB card gives about 0.5 GiB more cache, roughly 4K more tokens in FP16. Push it to 0.98 and you will eventually meet an OOM from something that isn't the cache. Leave headroom if anything else touches the GPU, including your desktop.

Two more levers worth knowing:

  • Weight quantization frees cache space. An AWQ or GPTQ 4-bit 8B model drops weights from ~15 GiB to roughly 5 GiB, and almost all of that freed memory goes to KV cache. Different quality trade-off, same eval rule.
  • Prefix caching shares blocks. With --enable-prefix-caching, requests that start with the same system prompt share those KV blocks instead of storing copies. A 3K-token system prompt across 10 concurrent users is 30K tokens of cache without sharing and 3K with it.

How do you estimate KV cache before buying a GPU?

Use the formula with your real numbers: peak concurrent requests × (prompt + max output tokens) × bytes per token. Then add weights and 10-15% slack.

def kv_budget_gib(concurrent, ctx_tokens, layers, kv_heads, head_dim, bytes_per_elem=2):
    return concurrent * ctx_tokens * kv_bytes_per_token(
        layers, kv_heads, head_dim, bytes_per_elem) / 2**30

# 20 users, 8K tokens each, Llama 3.1 8B, FP16 cache
print(kv_budget_gib(20, 8192, 32, 8, 128))      # 20.0 GiB
# Same with FP8 cache
print(kv_budget_gib(20, 8192, 32, 8, 128, 1))   # 10.0 GiB
Enter fullscreen mode Exit fullscreen mode

That first number surprised me. Twenty users at 8K context need more memory for their KV cache than the model needs for its weights. On a 24 GB card it is impossible in FP16 and tight in FP8. On a 48 GB card it is comfortable. That is a hardware decision you want to make with a calculator, not with a crash log.

So why does Llama 3.1 8B need 16 GiB of KV cache for one 128K request?

Because the KV cache stores a key and a value vector for every token in every layer: 2 × 32 layers × 8 KV heads × 128 dimensions × 2 bytes = 128 KiB per token in FP16, and 131,072 tokens × 128 KiB = 16 GiB. Add ~15 GiB of weights and a single full-context request needs over 31 GiB, which is why vLLM refuses to start on a 24 GB GPU with the default max_model_len. Cap --max-model-len to your real context, use --kv-cache-dtype fp8 to halve the per-token cost, and size your GPU by total tokens in flight across all users, not by model size.


Written by the developer behind Preterview, an interview prep platform.

Top comments (0)