KV cache

In one sentence

During generation, store every token's attention keys and values so each new token reuses them instead of recomputing the prefix; the price is GPU memory that grows with context length × concurrent requests.

Analogy: Keeping running notes while reading a book instead of re-reading from page 1 before every new sentence: much faster, but the notebook keeps growing and has to fit on your desk.

Prefill fills the cache once; each decode step adds one entry and reads all of them, so memory and bandwidth grow with context.

How it works

  • Past tokens' K and V never change in a causal model, so each is computed once and appended.
  • Prefill caches the whole prompt; each decode step then does new work for just one token.
  • Size per token = 2 × layers × KV heads × head_dim × bytes: 128 KiB for Llama-3.1-8B fp16.
  • At 128k context one sequence needs ~16 GiB, so the KV cache, not the weights, sets your batch size.
  • Shrink it with GQA (4×), FP8 KV (2×), PagedAttention against fragmentation, and prefix caching across requests.

Check yourself

Answer to mark it learned; your answers aren't scored.

Every request shares a 6k-token system prompt, and prefix caching kept time-to-first-token low. After a release that adds Current time: <timestamp> as the prompt's first line, cache hits drop to ~0 and TTFT jumps. Why?

Go deeper

GPU memory: weights + KV cache Interactive lab
Full explanation

The KV cache stores the attention keys and values of every token already processed, so generating the next token doesn't recompute them.

In Self-attention, each new token's query is compared with the keys of all previous tokens and mixes their values. In a causal model those K and V vectors never change once computed, so the server computes them once (for the whole prompt during prefill, then one token per step during decode) and appends them to the cache. Each decode step then does new work for one token, not the whole sequence.

The cost is memory, linear in context length:

bytes per token = 2 (K and V) × layers × kv_heads × head_dim × bytes per value

Llama-3.1-8B (32 layers, 8 KV heads, head_dim 128, fp16): 2×32×8×128×2 = 128 KiB per token. A full 128k context is ~16 GiB, as much as the model's weights, for one sequence. Multiply by concurrent requests and the KV cache, not the weights, sets your batch size and throughput.

That's why most of GPU memory math is KV math, and why so many tricks target it: GQA shares KV heads (8 instead of 32 above, 4× less), PagedAttention & vLLM removes fragmentation, FP8 KV halves it, and prefix caching reuses the KV of a shared prompt prefix across requests, the mechanism behind Prompt caching.

Code KV cache sizing calculator
pythonKV cache sizing calculator
def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_value=2):
    # 2 = one K and one V vector per layer per KV head; fp16/bf16 = 2 bytes
    return 2 * layers * kv_heads * head_dim * bytes_per_value

MODELS = {  # (num_hidden_layers, num_key_value_heads, head_dim) from config.json
    "Llama-2-7B (MHA)": (32, 32, 128),
    "Llama-3.1-8B (GQA)": (32, 8, 128),
    "Llama-3.1-70B (GQA)": (80, 8, 128),
}

def kv_gib(model, context_tokens, concurrent_seqs=1, bytes_per_value=2):
    per_token = kv_bytes_per_token(*MODELS[model], bytes_per_value)
    return per_token * context_tokens * concurrent_seqs / 2**30

for name, cfg in MODELS.items():
    kib = kv_bytes_per_token(*cfg) / 1024
    print(f"{name}: {kib:.0f} KiB/token, {kv_gib(name, 128 * 1024):.0f} GiB per 128k seq")
# Llama-2-7B (MHA): 512 KiB/token, 64 GiB per 128k seq  (4x: no GQA)
# Llama-3.1-8B (GQA): 128 KiB/token, 16 GiB per 128k seq
# Llama-3.1-70B (GQA): 320 KiB/token, 40 GiB per 128k seq

# Capacity planning: 32 users x 8k tokens on Llama-3.1-8B
print(kv_gib("Llama-3.1-8B (GQA)", 8192, 32))     # 32.0 GiB in bf16
print(kv_gib("Llama-3.1-8B (GQA)", 8192, 32, 1))  # 16.0 GiB with FP8 KV
Real example

You serve Llama-3.1-8B in bf16 on one 80 GB H100. Weights take ~16 GB; after runtime overhead and headroom, say ~55 GB is left for KV. At 128 KiB/token that's ~420k cached tokens in total: ~50 concurrent chats at 8k context, but only ~3 at the full 128k. A product decision to "give everyone 128k context" cuts concurrency per GPU ~16× for that traffic. FP8 KV doubles both numbers; a model with 32 KV heads instead of 8 would cut them 4×.

Trade-offs +3 · −3

+ You gain

  • Each decode step computes K and V for one new token instead of the whole sequence: what makes generation practical.
  • Enables prefix caching: a shared system prompt or document is prefilled once and reused across requests.
  • Pure systems optimization: identical outputs, no quality trade-off unless you quantize it.

− You pay

  • Memory grows linearly with context × concurrent sequences, capping batch size and throughput.
  • Decode becomes memory-bandwidth-bound: every step reads the weights plus the whole cache.
  • Needs a smart allocator and scheduler (paging, eviction, preemption) or memory is wasted and requests stall.

Use it when

Always on for autoregressive decoding. The real decisions are sizing and managing it: capacity planning, max context per tier, picking GQA/MLA models, FP8 KV, and prefix caching for shared prompts.

Avoid it when

Single-pass workloads with no generation (embeddings, classifiers, rerankers) don't need it. And don't hold 128k windows open per user "just in case": long-context KV is exactly what you pay for.

Numbers to know 5
  • Per token: 2 × layers × kv_heads × head_dim × bytes per value.
  • Llama-3.1-8B fp16: 128 KiB/token → ~16 GiB at 128k tokens, about the size of its weights.
  • Llama-3.1-70B fp16: 320 KiB/token → ~40 GiB per 128k-token sequence.
  • GQA with 8 KV heads instead of 32: 4× smaller cache; FP8 KV: another 2×.
  • vLLM paper: earlier servers used only ~20–38% of KV memory for real tokens; PagedAttention wastes under 4%.
Common pitfalls 4
  • Sizing GPUs by model weights alone; at long context and real concurrency the KV cache is the bigger number.
  • Using the query head count instead of num_key_value_heads, overestimating GQA models 4–8×.
  • Breaking prefix caching with a timestamp or user ID at the top of the prompt; only an identical prefix hits.
  • Raising max context per request without re-testing concurrency and p99 latency.
Interview questions 2

Answer out loud first, then reveal.

Estimate the KV cache for 100 concurrent users on a 70B model with 8k context.Show answer

I use 2 × layers × KV heads × head_dim × bytes. Llama-3.1-70B has 80 layers, 8 KV heads thanks to GQA, and head_dim 128, so in bf16 that's 320 KiB per token. 8k tokens is ~2.5 GiB per user, so 100 users need ~250 GiB of KV on top of ~140 GB of weights: ~410 GB in total. That's one 8×H100 node with tensor parallelism, not two or four GPUs. Then I'd check whether real contexts average far below 8k and whether FP8 KV halves the cache.

How does the KV cache relate to the prompt caching providers sell?Show answer

Prompt caching is KV-cache reuse across requests. If two requests start with exactly the same tokens (system prompt, tool definitions, a long document), the server keeps the KV for that prefix and skips its prefill, the compute-heavy part of a long prompt. Providers pass on the saving: Anthropic bills cache reads at 10% of the input price on most models, less on some newer ones. The design rule follows: stable content first, volatile content last, and never a timestamp at the top, because one changed token invalidates everything after it.