Debarshi Das

Explainer

KV cache size per token: one formula does not fit every model

The KV cache formula, computed from real configs for 12 model types, and what it means for capacity, prefix hits and handoff.

By Debarshi Das. Published .

21 min read

  • LLM inference
  • KV cache
  • Disaggregated serving
  • GPU infrastructure
  • Attention

The key-value (KV) cache holds the keys and values that attention has already computed, so a model does not compute them again for every new token. Its size per token is usually given as one formula: 2 × layers × KV heads × head dimension × bytes per element. For Qwen3-8B in BF16 that is 2 × 36 × 8 × 128 × 2 = 147,456 bytes, or 144 KiB, for every token of every request.

That formula is correct for Qwen3-8B. For many models released since 2024 it is wrong, each in a different way, and the error flows into every number built on it: how many requests fit on a GPU, whether a prefix cache hits, and how long the handoff takes between prefill and decode workers. This essay computes the cache for twelve model types from their published configurations, and shows where the formula breaks.

Qwen3-8B weights, 15.3 GiB, beside one request's KV cache at 128K tokens, 18 GiB, which stands taller.Hover a part to see its name
Qwen3-8B: at 128K tokens (with YaRN), one request's cache outweighs the model itself.

How big is the KV cache per token?

Five numbers decide it. Attention stores a key and a value (the 2) for every layer, for every KV head, across the head's dimension, at the size of one element.

KV bytes per token=2×layers×KV heads×head dimension×bytes per element\begin{aligned} \text{KV bytes per token} &= 2 \times \text{layers} \times \text{KV heads} \\ &\quad \times \text{head dimension} \times \text{bytes per element} \end{aligned}

For Qwen3-8B in BF16:

2×36×8×128×2=147,456 bytes=144 KiB2 \times 36 \times 8 \times 128 \times 2 = 147{,}456 \text{ bytes} = 144 \text{ KiB}
Keys and values for one Qwen3-8B token as two blocks of 8 KV-head units; a screen reads 147,456 bytes.Hover a part to see its name
Five numbers multiply to 147,456 bytes per token. Precision is the only one you can change freely.

Precision is the factor an operator controls. An FP8 cache holds the same tokens in half the memory, 73,728 bytes per token for Qwen3-8B. NVFP4 stores 4-bit values plus one FP8 scale for every 16 of them, so it takes 41,472 bytes, about 28 percent of BF16. The other four come from the model.

The per-token number grows quickly into the numbers that matter.

A tray of 64 blue requests of 8,192 tokens, 1.125 GiB each; a screen reads 72 GiB.Hover a part to see its name
Each token adds 144 KiB. One 8K request holds 1.125 GiB; 64 of them hold 72 GiB.

Why a long request can outweigh the model

Qwen3-8B has about 8.2 billion parameters, or 15.3 GiB of weights in BF16. Its native context is 32,768 tokens, where one request's cache is 4.5 GiB. With YaRN scaling to 131,072 tokens, one request's cache is 18 GiB: larger than the model that produced it.

How many requests fit on one GPU

Capacity is what remains after the weights. An H100 80GB reports about 79.6 GiB. With vLLM's gpu_memory_utilization set to 0.9 (its default before v0.20; 0.92 since), the engine takes 90 percent of that: about 71.6 GiB. Other engines count differently. SGLang computes mem_fraction_static at startup from the GPU and its settings. TensorRT-LLM's free_gpu_memory_fraction (default 0.9) is a share of the memory left after the weights. The weights take 15.3 GiB. The remainder, about 56 GiB, also holds activations and CUDA graph buffers, so at most about 50 requests of 8K tokens fit at once, not the 64 that 72 GiB would suggest.

An H100 memory column holds the weights and 50 requests under the 90% line; 14 more stand outside in ember.Hover a part to see its name
On one 80 GB GPU, after the weights, at most about 50 such requests fit, not 64.

Two more effects change the real number. Engines allocate the cache in fixed blocks of tokens, so the last block of every request is partly empty. Tensor parallelism also splits KV heads across GPUs only while there are enough heads to split.

Two requests in 16-token blocks, 5 and 3 blocks; the last block of each has its empty slots marked.Hover a part to see its name
Memory is handed out in fixed blocks, so each request's last block is partly empty.
Sixteen GPUs in two rows, one KV head on each; the eight on the front row are copies, shown in ember.Hover a part to see its name
Eight KV heads split across up to eight GPUs. At sixteen, every head is held twice.

Here is the formula as code. It reads a model's config.json from Hugging Face and prints the first answer. The sections that follow show when that answer is wrong.

Python
import json
import sys

config = json.load(open(sys.argv[1]))
config = config.get("text_config", config)  # Multimodal configs nest the text model.
element_bytes = 2  # BF16. Use 1 for FP8.

if "kv_lora_rank" in config:  # Latent attention (MLA): one shared row per token per layer.
    per_layer = (config["kv_lora_rank"] + config["qk_rope_head_dim"]) * element_bytes
elif config.get("multi_query"):  # Older configs, such as Falcon-7B, mark one shared KV head.
    head_dim = config["hidden_size"] // config["num_attention_heads"]
    per_layer = 2 * 1 * head_dim * element_bytes
else:
    # Falcon-40B and its relatives name the KV heads num_kv_heads.
    heads = config.get("num_key_value_heads") or config.get("num_kv_heads") or config["num_attention_heads"]
    head_dim = config.get("head_dim") or config["hidden_size"] // config["num_attention_heads"]
    per_layer = 2 * heads * head_dim * element_bytes

print(per_layer * config["num_hidden_layers"], "bytes per token, if every layer keeps a full cache")

Which model types break the formula

Fewer KV heads: MHA, GQA and MQA

Older models gave every query head its own key and value head: multi-head attention (MHA). Grouped-query attention (GQA) lets several query heads share one KV head. Multi-query attention (MQA) lets all of them share a single one. The formula still holds; only the head count changes.

One token's cache for three models at one scale: 32, 8 and 1 KV-head units, 512, 144 and 8 KiB.Hover a part to see its name
Fewer KV heads, smaller cache: 512 KiB, 144 KiB and 8 KiB per token.

Llama-2-7B, with 32 KV heads, stores 524,288 bytes per token: 3.6 times Qwen3-8B. A concurrency estimate reused across these designs is off by that factor.

Why MLA does not split across GPUs

DeepSeek-V3 uses multi-head latent attention (MLA). It stores one compressed row per token per layer: a 512-wide latent and a 64-wide position part. In decode, every query head reads that same row directly. Across 61 layers in BF16 that is 70,272 bytes per token, less than half of Qwen3-8B for a model about 80 times larger.

One latent row stacked 61 layers high beside a grid of query heads; a screen reads 70,272 bytes per token.Hover a part to see its name
MLA stores one shared row per token per layer, and every head reads it: 70,272 bytes per token.

The row belongs to no single head, so tensor parallelism cannot split it by head. Under tensor parallelism alone, each GPU holds the whole row, and per-GPU cache does not shrink as GPUs are added. Decode context parallelism (vLLM's --decode-context-parallel-size) shards the cache across tokens instead. In practice, MLA models usually run with data-parallel attention (SGLang's --enable-dp-attention, or data and expert parallelism in vLLM), which keeps each request's cache on one GPU and avoids the copies.

Eight GPUs in a row, each holding MLA's whole row; one is the original and seven are copies in ember.Hover a part to see its name
MLA's single row cannot be split by head, so under tensor parallelism eight GPUs hold eight copies.

DeepSeek-V3.2 adds sparse attention: a small indexer chooses which earlier tokens each new token reads. That reduces the work per step, not the storage. Every token is still stored, plus an indexer key: 78,324 bytes per token in BF16, a little more than DeepSeek-V3. In FP8 the number depends on the GPU. On Hopper, vLLM's FlashMLA sparse backend stores the fp8_ds_mla row: the latent in FP8, the position part kept in BF16, and four scale values, for 48,068 bytes per token. On Blackwell, vLLM prefers FlashInfer's sparse backend, which keeps a standard FP8 row: 43,188 bytes. Plain MLA, such as DeepSeek-V3, stores a standard FP8 row on both: 576 bytes per layer, 35,136 bytes per token. An engine that packs the FP8 row differently stores a slightly different number.

64 DeepSeek-V3.2 tokens, each a row and a small key, all stored; only 1 row in 64 is read.Hover a part to see its name
Sparse attention reads fewer tokens but still stores all of them, plus a small extra key: 78,324 bytes per token in BF16.

Sliding windows

In gpt-oss-120b, half of the 36 layers attend only to the last 128 tokens. Those layers stop growing once the window is full, at 4.5 MiB per request in total. The other 18 layers grow at 36,864 bytes per token. The formula counts every layer as full, so it overstates the cache by about two times at long context.

A stack of 36 layers: 18 long blue cache bars, and 18 window layers whose bars the formula fills out in ember.Hover a part to see its name
gpt-oss-120b: half its layers keep only the last 128 tokens. Counting them as full overstates the cache.

Mixture of experts

A mixture-of-experts (MoE) model routes each token through a few of many feed-forward experts. The experts hold most of the weights, but they keep no cache. The cache is set by attention alone. Qwen3-30B-A3B, a model nearly four times larger than Qwen3-8B, stores 98,304 bytes per token, less than Qwen3-8B.

A 48-layer stack of attention and larger expert blocks; a blue cache column of 96 KiB stands beside attention only.Hover a part to see its name
Experts do not touch the cache: Qwen3-30B-A3B holds 96 KiB per token, less than Qwen3-8B.

Hybrids keep a fixed state

Hybrid models replace most attention layers with layers that keep a fixed-size state instead of a growing cache: Mamba layers in Nemotron-H, linear attention in Qwen3-Next. RWKV-6 keeps no attention cache at all. What a request holds is no longer one thing: a small cache that grows, plus a state that does not.

Nemotron-H-8B's 52 layers: 24 short blue state blocks, 4 long blue cache bars, and MLP layers with nothing beside them.Hover a part to see its name
Nemotron-H-8B: its 24 Mamba layers keep a fixed state per request, beside a small cache that grows in its 4 attention layers.

Of Nemotron-H-8B's 52 layers, 4 are attention layers and 24 are Mamba layers; the rest hold nothing per request. Its cache grows at 16,384 bytes per token. With the state in BF16, the state is 49.4 MiB per request and equals 3,162 tokens of its own cache. For short requests the state is most of its memory. At 8K tokens the request holds 177.4 MiB, still 6.5 times less than Qwen3-8B. vLLM keeps Nemotron-H's state space model (SSM) state in FP32 by default, for accuracy. Then the state is 97.4 MiB and equals 6,234 tokens of cache, and an 8K request holds 225.4 MiB, 5.1 times less than Qwen3-8B.

A fixed 49.4 MiB state block beside a KV cache that grows past it, to 128 MiB at 8,192 tokens on Nemotron-H-8B.Hover a part to see its name
With the state in BF16: below about 3,200 tokens the fixed state is most of its memory; at 8K it uses 6.5x less.

Sharing and images

Cross-layer attention (CLA) lets adjacent layers read one cache. Sharing between pairs halves it, and the paper also tests groups of three. YOCO (You Only Cache Once) goes further: half of its layers read a single shared cache, and the other half keep a cache of constant size, a short window in its sliding-window variant. Vision-language models turn an image into ordinary cache positions: a 1024 by 1024 pixel image becomes 1,024 tokens, 144 MiB on Qwen3-VL-8B.

Six stacked layers with three blue cache bars, each between the two layers of a pair that share it.Hover a part to see its name
Cross-layer sharing lets adjacent layers read one cache: half the size when pairs share.
A flat image cut into a 32 by 32 grid beside a tall blue KV cache column of 1,024 tokens, 144 MiB.Hover a part to see its name
A 1024 by 1024 pixel image becomes 1,024 tokens: 144 MiB of cache.

All twelve, side by side

KV cache per token and fixed state per request, BF16 unless stated, computed from each model's config.json.

ModelType

Bytes per token

Fixed state per request
Llama-2-7BMHA524,288none
Qwen3-8BGQA147,456none
Qwen3-VL-8BGQA, images as tokens147,456none
Qwen3-30B-A3BGQA, mixture of experts98,304none
DeepSeek-V3MLA70,272none
DeepSeek-V3.2MLA, sparse78,324none
gpt-oss-120bGQA, sliding window36,8644.5 MiB once the window is full
Qwen3-Next-80B-A3BLinear attention hybrid24,57637.7 MiB
Nemotron-H-8BMamba hybrid16,38449.4 MiB in BF16 (97.4 MiB in vLLM's default FP32)
Falcon-7BMQA8,192none
CLA modelsShared across layers2 times less (pairs), up to 3none
RWKV-6Recurrent0about 33 MiB for the 7B model (FP32 state)
Ten models' per-token caches as cubes at one scale, from Llama-2-7B to RWKV-6, with ember cubes for fixed state.Hover a part to see its name
Every model type, sorted by cache per token, with fixed state shown separately.

Every number here is computed from public configurations, not measured. Every cache figure is BF16, so the rows compare designs, not precisions; BF16 bytes per token are model math, the same on every engine. Nemotron-H's state is shown in BF16, where vLLM's default keeps it in FP32. RWKV-6's state is shown in FP32, as its row says. Real engines add block padding, a memory reserve, CUDA graph buffers and, for FP8, scale tensors. Treat the table as the floor a measurement starts from. The data is available as CSV.

Why a hybrid model's prefix match is fragile

A prefix cache lets a new request reuse the cache of an earlier request that started with the same tokens, such as a long system prompt. The shared part is not computed again.

Three shared blocks stored once, with request A and request B each going on from them on their own blocks.Hover a part to see its name
Two requests that start the same share their first blocks, and that part is not computed again.

A hybrid model cannot reuse its attention cache alone. It also needs the fixed state as it was at the end of the shared part. vLLM saves that state only at a few block boundaries, and its blocks for hybrid models are large: 528 tokens for Qwen3.5-4B in BF16. In plain single-node vLLM, if the saved state is missing, the engine discards the attention match too. A KV connector that accepts partial hybrid hits can keep it.

Request B computes all blocks again: no saved state at the end of the 2 matching blocks, so the match is lost.Hover a part to see its name
On a hybrid model the blocks match, but the saved state is missing, so the attention match is lost too (single-node vLLM).

vLLM issue #45238 shows how sharp the geometry is. With Qwen3.5-4B, 528-token blocks and prompts of about 2,200 tokens, a build from before vLLM's Marconi-style admission policy (#37898) kept saved states at tokens 1,584 and 2,112. With a 1,600-token shared prefix, the state at 1,584 fell inside the shared part, and 52 of 64 requests hit. With a 1,500-token shared prefix, both fell in the unique part, and none hit. #37898 saves a state at the last block boundary inside a shared prefix once it has been seen, here token 528. The issue's author re-measured with it: 40 of 64 requests hit, but cache hits covered only 25.5 percent of the queried prompt tokens, against 54.0 percent with the longer prefix. The total loss is gone, but much of the reuse is still lost, and nothing in vLLM's metrics shows why. --prefix-match-unit can add saved states inside a short prefix, but it is off by default.

Two prompts in 528-token blocks: the state at 1,584 is inside a 1,600-token shared part, but past a 1,500 one.Hover a part to see its name
Shorten the shared part by 100 tokens and the saved states land past it: on the June 2026 build, hits fell from 52 of 64 to 0 (vLLM #45238).

Prefix caching on hybrids also has a cost when nothing hits. vLLM issue #60008 measured 13.4 to 16.2 percent lower output throughput (medians of six rounds; the issue's title says 11 to 16) on one NVFP4 Mamba hybrid on four GB200 GPUs. Prefix caching was on and nothing hit, on a vLLM build with changes not yet merged. Later comments report a prototype that closes most of the gap. Both issues were open when this essay was published.

Two servers, same load: with prefix caching on and zero hits, the output column stops 13.4 to 16.2 percent lower.Hover a part to see its name
With no hits at all, prefix caching cost 13.4 to 16.2 percent throughput on one hybrid setup (vLLM #60008).

Images add one more rule. Two requests with the same text and different images must not share a cache, so the cache key must include the image.

Two request trays with the same text and different images, each with its own key, and two rows in a prefix cache.Hover a part to see its name
Same words, different images: the cache key must include the image.

What crosses the wire between prefill and decode

In disaggregated serving, one group of GPUs runs prefill and another runs decode, so the cache moves between them once per request. Its size is the per-token number times the prompt length, plus any fixed state.

Prefill and decode GPU boards joined by one 400G cable; three models' caches rest on decode trays; 11.5 ms.Hover a part to see its name
What crosses the wire for an 8K-token prompt, model by model.

One request's cache and state at 8K tokens, BF16, and its transfer time at ideal line rate: 50 GB/s per 400 Gb/s NIC (400 GB/s for eight), 450 GB/s per direction for NVLink 4.

Model

At 8K tokens

One 400G NIC

Eight 400G NICs

NVLink 4

Llama-2-7B4.0 GiB86 ms10.7 ms9.5 ms
Qwen3-8B1.125 GiB24 ms3.0 ms2.7 ms
Qwen3-30B-A3B768 MiB16 ms2.0 ms1.8 ms
DeepSeek-V3549 MiB11.5 ms1.4 ms1.3 ms
gpt-oss-120b292.5 MiB6.1 ms0.8 ms0.7 ms
Qwen3-Next-80B-A3B229.7 MiB4.8 ms0.6 ms0.5 ms
Nemotron-H-8B177.4 MiB3.7 ms0.5 ms0.4 ms

Real transfers are slower than line rate.

The layout on each side matters as much as the size. When prefill and decode use different numbers of GPUs, KV heads must be regrouped in flight. For MLA, every decode GPU needs the whole row, so the same bytes are sent to each one.

Prefill on 4 GPUs sends MLA's row to 8 decode GPUs; every decode GPU holds the whole row, seven are repeats.Hover a part to see its name
Different GPU counts on each side regroup the heads in flight; MLA sends its whole row to every GPU.

When reloading beats recomputing

A cache that does not fit in GPU memory can move to host memory, a local SSD or a remote store, and come back when a request needs it.

A GPU and three tiers, each holding more blocks; the DRAM and SSD blocks are back, the remote block is on its way.Hover a part to see its name
Each tier holds more and returns it more slowly.

Moving it back is worth it only when it is faster than computing it again. Reload time is the cache size divided by the tier's bandwidth, plus a fixed cost to start the transfer. Recompute time is the prefill time for those tokens: the model's compute per token times the tokens, plus an attention term that grows with the square of the length and matters mostly past tens of thousands of tokens. So the comparison is bytes per token against compute per token. The fixed start cost favors recomputing very short prompts. A slower tier or a larger cache per token favors recomputing. A model with a small cache and heavy compute per token, such as an MLA mixture of experts, favors reloading. Where the line falls depends on numbers that only your hardware gives.

Short prompt: the GPU recomputed its block. Long prompt: the reloaded cache arrived first and recompute stopped.Hover a part to see its name
Reload wins when moving the bytes is faster than computing them again.

For the same reason, sparse attention does not make reloading a whole offloaded prefix cheaper: it reads fewer tokens per step, but the prefix must carry all of them.

Questions to ask any new model's config

Before you size a deployment for a new model, answer these from its config.json and its paper:

  1. What attention type does each layer use: full, sliding window, linear, Mamba or none?
  2. How many KV heads does each attention layer have, and is the head dimension stated separately?
  3. Does it store a latent row (MLA) instead of separate keys and values?
  4. Which layers have a window, and how long is it?
  5. Is there a fixed state per request, and how large is it in the dtype the engine uses?
  6. Do any layers share a cache?
  7. At your tensor-parallel size, is the cache split, or copied to every GPU?

The KV cache calculator runs these numbers for your model, context, GPUs and link.

Ten hypothetical 128K requests at one scale, from 64 GiB on Llama-2-7B to a 33 MiB ember cube on RWKV-6.Hover a part to see its name
Back to the start: a hypothetical 128K-token request, every model type side by side, even those whose context is shorter.

Questions engineers ask

Does an FP8 KV cache halve memory?

It halves the bytes per token, from 2 to 1 per element. Scale tensors add a small amount, and accuracy needs its own check for each model.

Why does my engine report fewer tokens than the formula?

The formula ignores block padding, the memory reserve, activations and CUDA graph buffers. Use the formula as the upper bound and the engine's startup log as the measurement.

Is the KV cache the same as the prefix cache?

No. The KV cache holds one request's keys and values. A prefix cache keeps those blocks after the request ends, so a later request with the same start can reuse them.

References

Choose a style to copy