Education › Inference › Stage 2: LLM inference fundamentals

The KV cache

How the cache grows with context and concurrency, how to size it, and the tricks that shrink it.

Beginner ~30 min read Module 4 of 15

If you remember one thing from this track, make it this: in LLM serving, GPU memory after the weights is KV cache, and KV cache is concurrency. This lesson explains what the cache stores, gives you the formula to size it, works through how many requests a GPU can hold at different context lengths, and covers the techniques engines and model designers use to shrink it: grouped-query attention, paging, prefix sharing, quantization and offloading.

After this module you can
  • Explain what the KV cache stores and why decoding needs it
  • Compute KV-cache bytes per token from a model's architecture
  • Estimate how many concurrent requests fit at a given context length
  • Explain how GQA, paging, prefix caching, FP8 cache and offload reduce memory pressure
  • Recognise the symptoms of a full cache in a running service

What the cache holds

In every attention layer, each token produces a key and a value vector. To generate the next token, the model compares the new token's query with the keys of all previous tokens and mixes their values. Recomputing those keys and values for the whole history at every step would make generation quadratically slower, so the server stores them: that store is the KV cache. Prefill writes it for the prompt; each decode step reads all of it and appends one more token's worth.

The cache is per request and lives as long as the request. It grows linearly with the number of tokens so far, and it is read in full on every decode step, so a long context costs both memory and bandwidth.

Sizing the cache

The formula and a worked example (illustrative architecture)
text
KV bytes per token = 2 x layers x kv_heads x head_dim x bytes_per_value

32 layers, 8 KV heads, head_dim 128, FP16 (2 bytes):
  2 x 32 x 8 x 128 x 2 = 131,072 bytes = 128 KiB per token

Same model with 32 KV heads (no GQA): 512 KiB per token

Now fit it on a GPU. Take an 80 GB card, let the engine use 90% of it (72 GB), and subtract 16 GB of FP16 weights: about 56 GB is left for cache. At 128 KiB per token that is roughly 427,000 tokens of cache in total, shared by every active request.

Average tokens per requestConcurrent requests that fitWith FP8 KV cache
4,000about 106about 213
32,000about 13about 26
128,000about 3about 6

This is why long-context features are expensive: the same GPU serving 128k-token conversations holds a few dozen times fewer users than one serving 4k-token chats. When the cache fills, the engine must queue new requests or preempt running ones, evicting their cache and recomputing it later, which shows up as latency spikes.

Making the cache smaller

  • Grouped-query attention (GQA) and multi-query attention let many query heads share fewer key-value heads. Most modern models use it; it is why kv_heads is often far smaller than the number of attention heads. It is a property of the model, not a setting.
  • Latent and sliding-window attention: some architectures compress keys and values into a smaller latent vector, or only keep a recent window of tokens in some layers, shrinking the cache further.
  • Paged allocation (vLLM's PagedAttention and equivalents) stores the cache in small blocks allocated on demand, so memory is not reserved for the maximum length up front.
  • Prefix caching shares the cache blocks for identical prompt prefixes, such as a long system prompt, across requests.
  • KV-cache quantization stores keys and values in FP8, halving memory with usually small quality impact; validate on your evals.
  • Offloading moves inactive blocks to CPU memory or SSD and brings them back instead of recomputing, useful for long idle conversations.
Tip

The cheapest win is often a lower maximum context length in the engine. If 99% of your requests are under 8k tokens, configuring a 128k maximum mostly wastes headroom; route the rare long requests to a separate deployment.

Spotting a full cache in production

  • The engine's cache-usage gauge (for vLLM, vllm:kv_cache_usage_perc) sits near 1.0.
  • Requests waiting rises while requests running stays flat at a ceiling.
  • A preemption counter climbs and tail latency jumps.
  • Time to first token degrades first, because new requests cannot be admitted.

The fixes come in two groups: more cache (another GPU or replica, tensor parallelism to spread weights, FP8 cache, higher memory-utilisation setting) or less demand per request (lower max context, shorter prompts, prefix caching, smaller max_tokens).

Hands-on practice

Size the cache for a real model

  1. Open the config.json of any open-weight model and find num_hidden_layers, num_key_value_heads, and the head dimension (hidden_size divided by num_attention_heads if head_dim is absent).
  2. Compute KV bytes per token in FP16 and FP8 with the formula from this lesson.
  3. Pick a GPU and compute the memory left for cache after weights at 90% memory utilisation.
  4. Fill in the concurrency table for 4k, 32k and 128k average tokens per request.
  5. If you can run vLLM, start it with that model and compare the KV-cache capacity it logs at startup with your estimate.
  6. Send concurrent long requests until vllm:kv_cache_usage_perc nears 1.0 and observe waiting requests and preemptions.
Cheat sheet

The KV cache — at a glance

Main things to focus on

  • Memory left after weights is KV cache, and KV cache is concurrency.
  • Cache grows linearly with tokens and is read in full every decode step.
  • GQA (fewer KV heads) is why modern models fit more users.
  • Long context divides concurrency; cap the maximum length to what you need.
  • Paging, prefix caching, FP8 cache and offload all stretch the same memory.
  • Full cache shows as waiting requests, preemptions and worse TTFT.

Formulas

KV/token = 2 x layers x kv_heads x head_dim x bytesCache size per token
head_dim = hidden_size / num_attention_headsWhen config.json has no head_dim
cache_mem = gpu_mem x utilisation - weightsMemory available for cache
concurrency ~ cache_mem / (KV/token x avg_tokens)Requests that fit at once

config.json fields

num_hidden_layersLayers (L)
num_key_value_headsKV heads; smaller than attention heads under GQA
num_attention_heads / hidden_sizeUsed to derive head_dim
max_position_embeddingsModel's maximum context

Engine knobs (vLLM)

--max-model-len NCap context to free cache
--kv-cache-dtype fp8Halve cache memory
--gpu-memory-utilization 0.9Share of memory the engine claims
--enable-prefix-cachingShare identical prefixes (on by default)

Symptoms

vllm:kv_cache_usage_perc ~ 1.0Cache full
rising vllm:num_preemptions_totalRequests evicted and recomputed
waiting up, running flatAdmission blocked by memory

Common pitfalls

  • Checking only whether weights fit and forgetting the cache needs room too.
  • Setting the maximum context to the model's limit when real requests are short.
  • Using the number of attention heads instead of KV heads in the formula.
  • Turning on FP8 cache without checking quality on your own evaluation set.
  • Reading a full cache as a compute problem and adding the wrong kind of capacity.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →