Skip to content
AgenticAIWiki
  1. Learn
  2. Part 1
  3. 10. Inside the transformer
  4. 10.5

Lesson 10.5 · 5 of 7 · 7 min read · Reviewed 24 Nov 2026

The KV cache and why long prompts cost memory

By the end, you can

  • Explain what the KV cache stores and why it speeds up generation.
  • Estimate KV cache memory from layers, KV heads, head size, precision and tokens.
  • Name the main ways serving systems shrink or share the cache.

A decoder writes one tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. at a time (lesson 2.2). To write token 1,001, the newest token’s query must be compared with the keys of all 1,000 earlier tokens, and their values mixed (lesson 10.1). Those earlier keys and values don’t change: token 37’s key is the same whether you are writing token 500 or token 1,000. So servers compute each one once and keep it. That store is the KV cacheKV cache: Stored attention keys and values for tokens already processed, so they are not recomputed for each new token..

What it buys

Without a cache, step 1,001 would re-run every earlier token through every layer just to rebuild their keys and values. With a cache, each step runs only the new token through the model and reads the rest from memory. This is what makes decoding practical, and it explains the two phases from lesson 9.4:

  • PrefillPrefilling: Writing the first part of the assistant’s reply yourself so the model continues from there. reads the prompt in parallel and fills the cache.
  • Decode adds one token’s keys and values per step and reads the whole cache each time.

What it costs: the formula

For every token, every layer stores one key and one value vector per KV head:

bytes per token = 2 x layers x kv_heads x head_dim x bytes_per_number
cache size      = bytes per token x tokens in context x concurrent requests

A worked example

An illustrative 8-billion-parameter model: 32 layers, 8 KV heads (it uses grouped-query attentionAttention: The mechanism that lets each token weigh every other token in the context when building its representation., lesson 10.2), head size 128, 16-bit numbers (2 bytes).

Quantity Working Result
Per token 2 x 32 x 8 x 128 x 2 bytes 128 KiB
One 32k-token request 32,768 x 128 KiB 4 GiB
Ten such requests at once 10 x 4 GiB 40 GiB
Same model with 32 KV heads (no GQA) 4 x 4 GiB per request 16 GiB each
Weights at 16-bit, for comparison 8 billion x 2 bytes about 16 GB

Ten long conversations need more than twice the memory of the model itself. This is the real reason long prompts are expensive to serve: not only compute, but memory that stops the server holding more users.

How systems shrink or share it

Technique Idea Effect
Multi-query and grouped-query attention Share K and V across query heads Cache divided by the group size
KV cache quantisation Store keys and values in 8 or 4 bits 2x to 4x smaller, small quality risk
Paged memory (vLLM’s PagedAttention) Allocate the cache in small blocks, like virtual memory Less waste, more requests per GPU
Sliding-window attention Keep only the last W tokens in some layers Cache capped at W tokens for those layers
Prefix (prompt) caching Reuse the cache for a prompt prefix many requests share Prefill skipped for the shared part

Prefix caching is what hosted prompt cachingPrompt caching: Reusing the processed form of a repeated prompt prefix across requests, which cuts cost and latency. features build on (chapter 70): a long system promptSystem prompt: Instructions passed in the top-level system field that set the model’s role, rules and context for the whole conversation. or document is processed once, and later requests that start with exactly the same tokens reuse its cache. That is why those features need the cached part to be an identical prefix.

Common mistakes

  • Budgeting GPU memory for the weights only. Leave room for the cache at your real context length and concurrency.
  • Assuming the cache shrinks when the answer is short. It holds the whole prompt too; a 30k-token prompt fills it before the first output tokenOutput tokens: The tokens the model generates in its reply, including any tool calls and thinking..
  • Changing the start of a prompt and expecting cache hitsCache hit: A request whose prompt prefix was found in the cache, so it is read cheaply instead of processed again.. Any change early in the prefix makes every later key and value different.

Key points

  • When generating, each new token needs the keys and values of every earlier token, so they are stored instead of recomputed: that store is the KV cache.
  • Cache size = 2 (keys and values) x layers x KV heads x head size x bytes per number x tokens; it grows linearly with context length and with concurrent requests.
  • A long prompt can need more memory for its cache than a small model needs for its weights, which limits how many users a server can hold.
  • Grouped-query attention, cache quantisation, paged memory and prefix caching all cut or share the cost.
Hands-on labRuns in the Playground

Size the KV cache for a long prompt

Calculate KV cache memory from a model's shape and find how many long requests fit on one accelerator.

You will have: A calculator that prints cache per token and per request, compares multi-head, GQA and multi-query, and gives a maximum request count.

Steps

  1. Fill in kv_bytes_per_token: 2 x layers x KV heads x head size x bytes per number.
  2. Run it and check the per-token and per-request numbers against the lesson.
  3. Compare the three attention variants at 32k tokens.
  4. Read the capacity check: how many 32k requests fit beside the weights on 80 GiB?
  5. Change the context to 128k tokens and see how the request count falls.

Done when

  • Per token prints 128.0 KiB and per request 4.00 GiB.
  • Multi-head needs 16.00 GiB per request; multi-query 0.50.
  • At 16-bit, 16 requests of 32k tokens fit.

Open in the Playground No API key needed.

Starter code (Python)
KIB, GIB = 1024, 1024 ** 3

def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_number=2):
    # TODO: one key and one value per KV head, per layer: 2 * layers * kv_heads * head_dim * bytes
    return 1

def kv_cache_gib(layers, kv_heads, head_dim, tokens, requests=1, bytes_per_number=2):
    return kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_number) * tokens * requests / GIB

# Illustrative 8B-class model: 32 layers, 32 query heads, head size 128.
LAYERS, HEAD_DIM = 32, 128
per_tok = kv_bytes_per_token(LAYERS, 8, HEAD_DIM)
print(f"{per_tok / KIB:.1f} KiB per token (GQA, 8 KV heads)")
print(f"{kv_cache_gib(LAYERS, 8, HEAD_DIM, 32768):.2f} GiB per request at 32k tokens")

print("\nvariant        KV heads  GiB per 32k request")
for name, kv in [("multi-head", 32), ("GQA", 8), ("multi-query", 1)]:
    print(f"{name:14}{kv:>9}{kv_cache_gib(LAYERS, kv, HEAD_DIM, 32768):>20.2f}")

# How many 32k-token requests fit on an 80 GiB accelerator after 16 GB of 16-bit weights?
weights_gib = 8e9 * 2 / GIB
free = 80 - weights_gib
for bits, b in [(16, 2), (8, 1)]:
    per_req = kv_cache_gib(LAYERS, 8, HEAD_DIM, 32768, bytes_per_number=b)
    print(f"cache at {bits}-bit: max requests at 32k: {int(free // per_req)}")
Show a solution
KIB, GIB = 1024, 1024 ** 3

def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_number=2):
    return 2 * layers * kv_heads * head_dim * bytes_per_number   # 2 = one key + one value

def kv_cache_gib(layers, kv_heads, head_dim, tokens, requests=1, bytes_per_number=2):
    return kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_number) * tokens * requests / GIB

# Illustrative 8B-class model: 32 layers, 32 query heads, head size 128.
LAYERS, HEAD_DIM = 32, 128
per_tok = kv_bytes_per_token(LAYERS, 8, HEAD_DIM)
print(f"{per_tok / KIB:.1f} KiB per token (GQA, 8 KV heads)")
print(f"{kv_cache_gib(LAYERS, 8, HEAD_DIM, 32768):.2f} GiB per request at 32k tokens")

print("\nvariant        KV heads  GiB per 32k request")
for name, kv in [("multi-head", 32), ("GQA", 8), ("multi-query", 1)]:
    print(f"{name:14}{kv:>9}{kv_cache_gib(LAYERS, kv, HEAD_DIM, 32768):>20.2f}")

# How many 32k-token requests fit on an 80 GiB accelerator after 16 GB of 16-bit weights?
weights_gib = 8e9 * 2 / GIB
free = 80 - weights_gib
for bits, b in [(16, 2), (8, 1)]:
    per_req = kv_cache_gib(LAYERS, 8, HEAD_DIM, 32768, bytes_per_number=b)
    print(f"cache at {bits}-bit: max requests at 32k: {int(free // per_req)}")
Quick checkAn illustrative model has 32 layers, 8 KV heads and a head size of 128, stored at 2 bytes per number. Roughly how many GiB of KV cache does one 32,768-token request need?
GiBCounts if within ±15%. You can type 1.2k, 3M or 2.5e6.
How sure are you?
Enter a number and how sure you are