Learn
Architecture

What is KV cache in LLM inference?

The short answer

A KV cache stores the key and value vectors computed for every token already processed, so generation does not recompute them. Each new token attends to the cached keys and values instead of the whole prefix. This turns generation from quadratic per step into linear, at the cost of memory that grows with context length and concurrency.

On this page

What is actually stored

In a decoder-only transformer, each layer projects every token into a query, a key and a value. The query is used once, at the position that produced it. The key and value are needed again by every future token that attends back to that position. Because the causal mask prevents anything from changing after the fact, those key and value vectors are constant once computed - so they can be stored instead of recomputed.

The cache therefore holds, for each layer and each token, one key vector and one value vector per key-value head. Nothing else is cached: queries are transient, attention weights are not stored, and the feed-forward activations are discarded after each token. That is why the size formula is so simple and why it scales with layers, heads, head width, tokens and batch.

The cache is per sequence, not per model. Two users asking the same question get separate caches unless the serving engine explicitly shares a common prefix, which is why concurrency and context length multiply together into your memory bill.

What happens without one

Generation is autoregressive: to produce token t, the model runs attention over tokens 1 to t-1, then samples, then repeats. Without a cache, producing token t costs a full forward pass over t tokens, and producing n tokens costs the sum over t of O(t^2) attention work - O(n^3) in total. At 4,096 tokens that is roughly 2.3e10 pairwise attention operations per layer in total, against 1.7e7 for the cached version at each step.

With a cache, the prefix is processed once during prefill and each subsequent token costs a single forward pass over one new position plus a read of the cache. Total work becomes O(n^2) for prefill plus O(n) per generated token. This is not a micro-optimisation; it is the difference between a model that can write a paragraph in a second and one that cannot finish a sentence.

The cache is also what makes streaming output possible. Once prefill is done, each token arrives after a fixed amount of work rather than a growing one, so the user sees a steady stream instead of accelerating output. Every interactive LLM product depends on this property.

The size formula

Bytes = 2 x layers x kv_heads x head_dim x tokens x batch x bytes_per_element. The leading 2 is for keys and values; everything else is structural. Note what is absent: the number of query heads does not appear, which is exactly why grouped-query attention shrinks the cache so effectively.

A 7B-class model with 32 layers, 32 key-value heads and head_dim 128 stores 2 x 32 x 32 x 128 = 262,144 elements per token - 512 KiB in fp16. At 4,096 tokens that is 2 GiB for one conversation. At 32K it is 16 GiB, which exceeds the weights themselves. A 70B model with 80 layers and 8 key-value heads stores 320 KiB per token, so an 8K conversation costs 2.5 GiB.

Multiply by concurrency and the picture sharpens. Twenty users at 8K tokens on the 7B model need 80 GiB of cache on top of 14 GB of weights - more than a 48 GB card can hold comfortably. Halving the cache with fp8 doubles the number of users, which is why cache quantisation is one of the highest-leverage optimisations in serving.

Why decode is bandwidth-bound

Generating one token from a 7B model requires about 2N = 1.4e10 FLOPs and reads 14 GB of weights. That is roughly one FLOP per byte. An H100 offers around 990 TFLOP/s of bf16 compute and 3.35 TB/s of memory bandwidth, a ratio near 295 FLOPs per byte. The workload sits about 300 times below the balance point, so the GPU spends its time waiting for memory, not doing arithmetic.

The cache adds to that traffic. At 8K tokens the cache is 4 GiB, so the per-token read is 18 GB rather than 14 GB - a 30% penalty that grows with context. At 128K tokens the cache is 64 GiB for one sequence and dominates completely, which is why long-context generation slows down as the conversation grows even though the arithmetic per token barely changes.

Batching is the fix. When 32 sequences decode together, one read of the weights serves 32 tokens, and the arithmetic intensity rises by roughly the batch factor. Throughput improves almost linearly until the cache reads start to dominate, at which point adding more sequences stops helping. That knee is the practical capacity limit of a deployment.

Prefill and decode are different workloads

Prefill processes the entire prompt in parallel. Every position is available, the matrix multiplies are large, and the GPU runs near its compute peak. It is compute-bound, and its cost scales with the square of prompt length for attention plus linearly for the feed-forward. Time to first token is almost entirely prefill.

Decode processes one token at a time. The matrix multiplies are skinny vectors against large matrices, the GPU is memory-bound, and latency per token is dominated by weight and cache reads. Inter-token latency is a decode property, and it is largely independent of prompt length until the cache grows large.

Serving engines interleave the two. Continuous batching admits new requests mid-flight, chunked prefill breaks long prompts into pieces so they do not stall decoding for everyone else, and scheduling policies trade time to first token against inter-token latency. If you have ever seen a long prompt make every other user's stream stutter, that was a scheduler without chunked prefill.

Paging, and why it mattered so much

A naive implementation allocates a contiguous buffer sized for the maximum context of each request. Since actual lengths are unknown in advance and vary widely, most of that buffer sits empty. The vLLM paper measured 60-80% waste in existing systems from this internal fragmentation, plus external fragmentation from variable-sized allocations.

PagedAttention borrows the operating system's answer: split the cache into fixed-size blocks of, say, 16 tokens, allocate them on demand, and keep a per-sequence block table mapping logical positions to physical blocks. Memory is used in proportion to actual tokens rather than worst-case length, and waste falls below 4%.

The block table enables things a contiguous buffer cannot. Sequences that share a prefix can point at the same physical blocks and copy only when one of them diverges, which makes parallel sampling and beam search nearly free in memory. Blocks can be evicted and swapped to host memory like pages, so a preempted request resumes rather than restarts.

Prefix caching and shared context

If two requests begin with the same tokens, the keys and values for that prefix are identical, because causal attention means later tokens cannot influence earlier ones. A serving engine can therefore compute the prefix once and reuse its blocks - the same property that makes prompt caching a product feature at the API level.

The saving is large for agent workloads. A system prompt with tool definitions might be 3,000 tokens; if it is re-sent on every one of 20 tool calls, that is 60,000 tokens of prefill per task. Cache the prefix and the cost collapses to one prefill plus cheap lookups. This is why providers price cached input tokens at a fraction of fresh ones, and why ordering your prompt with the stable part first is a real optimisation.

Sharing is not free of bookkeeping. Cached blocks must be keyed by exact token content, invalidated when the prefix changes, and protected from concurrent writes - the copy-on-write mechanism above. And a cache hit is only as good as its routing: if requests land on different replicas, each computes its own copy. Cache-aware load balancing exists precisely to avoid that.

Quantising and compressing the cache

  • fp8 cache: halves bytes with small quality impact, widely supported and usually the first lever to pull.
  • int8 with per-channel keys and per-token values: better accuracy than naive per-tensor scaling because outlier structure differs between the two tensors.
  • 2-bit and 4-bit research methods: report usable quality at 4-8x compression relative to fp16 on some models, but degrade long-context retrieval faster than short-answer tasks.
  • Token eviction: keep only recent tokens plus a few high-attention ones, bounding memory but losing exact recall.
  • Attention sinks: retaining the first few tokens plus a sliding window preserves fluency surprisingly well, because models dump excess attention on the initial positions.
  • Summarisation: replace old turns with a compressed summary, which trades fidelity for a fixed budget.
  • Layer sharing: reuse keys and values across adjacent layers, cutting the layer factor rather than the precision.

Architectural answers

Grouped-query attention is the mainstream fix: sharing key and value heads across query groups cuts the cache by the group factor, typically 8x, with minimal quality cost. Multi-head latent attention goes further by caching a compressed latent per token and projecting it up when needed; DeepSeek-V2 reported a cache reduction above 90% with better throughput than its dense predecessor.

At the extreme, linear attention and state-space models such as Mamba keep a fixed-size state instead of a growing cache, so memory is constant in sequence length. They trade exact recall of arbitrary earlier tokens for a compressed summary, and hybrid stacks that interleave a few attention layers with many state-space layers try to buy both.

The direction of travel is clear: attention quality is worth keeping, so the industry is compressing the cache rather than eliminating attention. For anyone choosing a model to self-host, the key-value head count and cache dtype are as important as parameter count, because they determine how many users fit on a GPU.

Sizing a real deployment

Start with the card. On an 80 GB GPU, reserve 5-10% for the driver and CUDA context, then subtract weights: 14 GB for a 7B model in fp16, 4 GB in 4-bit. Suppose you allow 70 GB total, leaving about 60 GB. At 512 KiB per token in fp16, that is roughly 120K token-slots - 14 users at 8K context, or 3 at 32K.

Now apply the levers. fp8 cache doubles those numbers. Switching to a model with 8 rather than 32 key-value heads multiplies them by four again. Capping max_model_len at 16K prevents a single long request from evicting everyone else, and setting max_num_seqs bounds concurrency explicitly rather than letting the scheduler discover the limit by thrashing.

Then measure. Watch cache occupancy, preemption counts and time to first token under realistic load. If preemptions are frequent, you are over-subscribed; if occupancy sits at 30%, you have headroom to raise concurrency or context limits. Those two numbers tell you more about a deployment than any synthetic benchmark.

Common mistakes

  • Sizing GPU memory from weights alone, then discovering the cache needs more than the model.
  • Forgetting that batch size multiplies cache usage - throughput testing at batch 1 hides the real constraint.
  • Assuming context length is free because the model supports it; the cost is linear and lands on concurrency.
  • Benchmarking latency with a warm prefix cache and reporting it as cold-start performance.
  • Quantising the cache to 4-bit and evaluating only on short prompts, where degradation is invisible.
  • Expecting prefix caching to work across replicas without cache-aware routing.
  • Confusing the cache with long-term memory: it lives for one request and disappears when the sequence ends.

The mental model to keep

The KV cache is the model's working memory for a single conversation. It exists because attention over a fixed prefix is deterministic, and it is expensive because it grows with every token, every layer and every concurrent user. Everything clever in modern serving - paging, prefix sharing, quantisation, grouped heads - is an attempt to make that memory cheaper without losing what it remembers.

When you evaluate a model or a serving stack, ask three questions: how many bytes per token does the cache cost, how much of it can be shared, and what happens when it runs out. The answers determine your cost per conversation more than the price per million tokens does, and they are the difference between a demo that works and a service that holds up on a Monday morning.

Page feedback

Was this helpful?

A quick signal helps improve these notes.

Report a mistake Straight to the lab inbox

Put it to work

See the models, datasets and gateway this lab runs.