Unit 6 of 9

The KV cache and its memory cost

  • 55 min
  • Includes a browser lab

What you’ll learn

  • Explain which attention results a model can reuse between tokens, and what it still computes at every step.
  • Calculate KV cache memory per token and per request from a model’s config.json.
  • Estimate how many requests fit on one GPU, and name the settings that change that number.
  • Build a KV cache in NumPy and check that it gives the same output as recomputing everything.

Why generation needs a cache

Ask a chatbot to summarize a 2,000-token document and it might write a 500-token summary. It writes that summary one token at a time, and each new token needs a pass through every layer of the model. The question this lesson answers is simple: what does each of those passes have to process?

Without a cache, each pass would feed the whole conversation back into the model: the document plus everything generated so far. With a KV cache, each pass processes only the one new token. The difference is large, as the arithmetic below shows.

Token positions pushed through the model’s layers for a 500-token answer

  1. Prefill: process the prompt once (both methods)2,000 positions
  2. Without a cache: 499 more passes over the growing sequence2,001 + 2,002 + ... + 2,499 = 1,122,750 positions
  3. Total without a cache2,000 + 1,122,750 = 1,124,750 positions
  4. With a cache: 499 more passes of one position each2,000 + 499 = 2,499 positions

ResultAbout 450 times less work with a cache

Almost every inference engine keeps a KV cache for this reason. The cost is memory: the cache grows with every token a request holds, and on a busy server it is usually what runs out first. By the end of this lesson you will be able to calculate that memory for a real model and estimate how many requests fit on a GPU.

What the cache stores and why reuse is safe

Each attention layer turns every token into three vectors: a query, a key, and a value. A token’s query asks, in effect, “which earlier tokens matter to me?” Every earlier token’s key answers how well it matches, and its value is the information it contributes. Attention compares the new token’s query with all the keys it may see, then takes a weighted mix of their values.

Two facts make caching possible. First, the model’s weights do not change during inference. Second, in a causal model a token may only look at itself and the tokens before it. Together they mean that the key and value computed for token 3 depend only on tokens 1 to 3, so adding token 4 later cannot change them. Once computed, they are final.

No cacheThe␣sky␣is␣bluekeys and values recomputed for all 4 tokensWith cacheThe␣sky␣is␣blueread from the cachecomputed oncerecomputed this stepread from the cachecomputed this step
At step 4, a model without a cache recomputes keys and values for every token. With a cache it computes them only for the newest token and reads the rest.

The cache holds one key vector and one value vector per token, per layer. It stores nothing else. Here is what still happens at every decode step, cache or not:

  • The new token passes through every layer, including the large feed-forward (MLP) blocks.
  • Each layer computes the new token’s query, key, and value, and appends the key and value to the cache.
  • The new query is compared against every cached key, so attention reads the whole cache for that request.

The last point matters later. Caching removes repeated computation, but it does not make long contexts free: a request with 100,000 cached tokens still reads all 100,000 keys and values at every layer, for every new token.

Go deeperWhy earlier keys and values never change

Follow token 3 through layer 1. Its key is its layer-1 input multiplied by the fixed matrix W_k. That input depends only on token 3’s embedding and position, so the key is fixed as soon as the token exists.

In layer 2, token 3’s input is layer 1’s output for token 3. Because of the causal mask, that output was built only from tokens 1 to 3. By induction, every layer’s key and value for token 3 depend only on tokens 1 to 3. A later token can read them, but it can never change them.

The argument breaks for bidirectional models such as BERT, where every token attends to every other token in both directions. Adding a token changes everyone’s outputs, which is one reason encoder models are not used for token-by-token generation.

KV Cache Explained · Watch on YouTube

Prefill fills the cache, decode extends it

A request uses the cache in two phases. You met prefill and decode in the first lesson; here is what each does to the cache.

  1. Prefill writes the prompt

    The engine runs all prompt tokens through the model in one parallel pass. Every layer stores a key and a value for every prompt token. The last position’s output also gives the scores for the first generated token.

  2. Decode reads the cache

    The newest token enters the model alone. At each layer, its query is compared with every key in that layer’s cache.

  3. Decode appends to the cache

    The newest token’s own key and value are added at every layer, so the cache grows by exactly one position per layer per step.

  4. Finishing frees the cache

    When the request ends, because it produced an end token, hit its length limit, or was cancelled, the engine releases its cache so another request can use the memory.

layertoken position0123451K,VK,VK,VK,VK,VK,VK,VK,VK,VK,VK,VK,V2K,VK,VK,VK,VK,VK,VK,VK,VK,VK,VK,VK,V3K,VK,VK,VK,VK,VK,VK,VK,VK,VK,VK,VK,V4K,VK,VK,VK,VK,VK,VK,VK,VK,VK,VK,VK,Vstored during prefillappended by the latest decode step
The cache has one row per layer and one column per token position. Each decode step appends a new column across every layer.

The two phases stress the hardware differently. Prefill does a lot of math on many tokens at once. Decode does little math per step but has to read the model’s weights and the request’s whole cache every time. That difference comes back in the batching and serving lessons.

Estimate KV cache memory

To size the cache you need four numbers from the model’s config.json and the precision you store the cache in. For every token, every layer stores a key and a value, and each of those has one vector per KV head:

KV cache bytes per token
bytes per token = 2 × layers × KV heads × head size × bytes per value
                  (2 = one key and one value)

In config.json these are num_hidden_layers, num_key_value_heads, and head_dim. If head_dim is missing, divide hidden_size by num_attention_heads. Bytes per value is 2 for BF16 or FP16, the usual choice, and 1 for an FP8 cache.

KV cache per token for Llama 3.1 8B in BF16

  1. Layers, KV heads, and head size from config.json32 layers, 8 KV heads, 4,096 / 32 = 128
  2. Values stored per token in one layer2 × 8 × 128 = 2,048 values
  3. Bytes per token in one layer2,048 × 2 bytes = 4,096 bytes
  4. Bytes per token across all 32 layers4,096 × 32 = 131,072 bytes

Result128 KiB per token

Multiply by the number of tokens a request holds, prompt and output together. A single 8,192-token conversation needs 8,192 × 128 KiB = exactly 1 GiB. A full 128K-token context needs 16 GiB, for one request.

That KV head count is a design choice with a large effect. Older models such as Llama 2 7B gave every query head its own key and value head. Newer models use grouped-query attention (GQA): several query heads share one key and value head. Llama 3.1 8B shares each KV head among 4 query heads, which cuts its cache to a quarter of what it would be otherwise.

0200400600Llama 2 7B, 32 KV headsLlama 2 7B, 32 KV heads: 512 KiB512 KiBLlama 3.1 70B, 8 KV headsLlama 3.1 70B, 8 KV heads: 320 KiB320 KiBLlama 3.1 8B, 8 KV headsLlama 3.1 8B, 8 KV heads: 128 KiB128 KiBLlama 3.1 8B, FP8 cacheLlama 3.1 8B, FP8 cache: 64 KiB64 KiB
KV cache per token, calculated from each model’s published configuration. Grouped-query attention and an FP8 cache both shrink it.
Where the per-token numbers come from (BF16 unless noted)
ModelLayersKV headsHead sizePer token
Llama 2 7B3232128512 KiB
Llama 3.1 8B328128128 KiB
Llama 3.1 8B, FP8 cache32812864 KiB
Llama 3.1 70B808128320 KiB

This formula counts the tensors themselves. Real engines add a little bookkeeping, and they allocate the cache in fixed-size blocks, so a request’s last block is usually only partly full. The estimate is still the right starting point for capacity planning.

How many requests fit on one GPU

A serving engine splits GPU memory into three parts: the model weights, working memory for computation, and the KV cache. Whatever is left after the first two becomes the cache, and the cache decides how many requests can be active at once.

Here is an illustrative budget for Llama 3.1 8B on an 80 GB H100, with the engine allowed to use 90% of GPU memory and the rest kept free as a safety margin. In vLLM this share is --gpu-memory-utilization; version 0.28.0 defaults it to 0.92.

02040608080 GB GPU80 GB GPU: Weights, 16 GBWeights80 GB GPU: Working memory, 4 GB80 GB GPU: KV cache, 52 GBKV cache80 GB GPU: Kept free, 8 GB80 GBWeightsWorking memoryKV cacheKept freeIllustrative values, not measurements.
An illustrative memory budget for Llama 3.1 8B in BF16 on one 80 GB GPU. The KV cache gets what the weights and working memory leave.

From memory budget to concurrent requests

  1. Memory the engine may use80 GB × 0.9 = 72 GB
  2. Weights: 8.03 billion parameters × 2 bytesabout 16 GB
  3. Working memory for activations and CUDA graphs (a rough allowance)about 4 GB
  4. Left for the KV cache72 − 16 − 4 = 52 GB
  5. Tokens that fit at 128 KiB per token52,000,000,000 / 131,072 ≈ 396,700 tokens
  6. 8,192-token requests that fit396,700 / 8,192 ≈ 48

ResultAbout 48 requests of 8K tokens at the same time

Notice what the answer is measured in. The GPU does not hold a number of requests; it holds a number of tokens. The same 52 GB fits 193 requests of 2K tokens or 12 requests of 32K tokens. When you plan capacity, start from the token lengths your traffic actually has, prompts and outputs together.

0501001502002K tokens each2K tokens each: 193 requests193 requests8K tokens each8K tokens each: 48 requests48 requests32K tokens each32K tokens each: 12 requests12 requests128K tokens each128K tokens each: 3 requests3 requestsIllustrative values, not measurements.
The same 52 GB cache, measured in requests. Capacity falls in proportion to request length.

When a burst of long requests fills the cache, the engine cannot start new ones. They wait in a queue, and time to first token climbs even though the GPU’s compute is not busy. Some engines also pause (preempt) running requests to make room and resume them later. Both show up as latency, not as errors, which is why cache usage is one of the first metrics to watch on a serving dashboard.

Try it: build a KV cache in NumPy

The script below runs one attention layer over six tokens twice: once recomputing every key and value at each step, and once with a cache. It then checks that both give identical outputs and counts how many key and value projections each method computed. You need Python 3.9 or later and NumPy.

kv_cache_demo.py
import numpy as np

rng = np.random.default_rng(0)
d_model, n_tokens = 16, 6
x = rng.standard_normal((n_tokens, d_model))  # one embedding per token
w_q, w_k, w_v = (rng.standard_normal((d_model, d_model)) / 4 for _ in range(3))


def attend(query, keys, values):
    scores = keys @ query / np.sqrt(d_model)
    weights = np.exp(scores - scores.max())
    return (weights / weights.sum()) @ values


# Without a cache: every step projects keys and values for the whole sequence.
projections, full = 0, []
for t in range(1, n_tokens + 1):
    keys, values = x[:t] @ w_k, x[:t] @ w_v
    projections += t
    full.append(attend(x[t - 1] @ w_q, keys, values))

# With a cache: project each token's key and value once, then append them.
k_cache, v_cache, cached = np.empty((0, d_model)), np.empty((0, d_model)), []
for t in range(n_tokens):
    k_cache = np.vstack([k_cache, x[t] @ w_k])
    v_cache = np.vstack([v_cache, x[t] @ w_v])
    cached.append(attend(x[t] @ w_q, k_cache, v_cache))

print("outputs match:", np.allclose(full, cached))
print("key/value projections without a cache:", projections)
print("key/value projections with a cache:   ", n_tokens)
print("cache shape per tensor:", k_cache.shape)
print("bytes for K and V:", k_cache.nbytes + v_cache.nbytes)
You should see
outputs match: True
key/value projections without a cache: 21
key/value projections with a cache:    6
cache shape per tensor: (6, 16)
bytes for K and V: 1536

Read the output in three parts. outputs match: True shows that the cache changes how much work is done but not the result. The projection counts show the saving: 1 + 2 + 3 + 4 + 5 + 6 = 21 without a cache, one per token with it. The cache ends with six rows, one per token, which is the shape shown in the grid above.

Next, turn the memory formula into a tool you can point at any model. This script reads the relevant fields from a config.json and prints per-token and per-request sizes:

kv_budget.py
def kv_bytes_per_token(config, bytes_per_value=2):
    layers = config["num_hidden_layers"]
    kv_heads = config.get("num_key_value_heads", config["num_attention_heads"])
    heads = config["num_attention_heads"]
    head_dim = config.get("head_dim", config["hidden_size"] // heads)
    return 2 * layers * kv_heads * head_dim * bytes_per_value


# The relevant fields from meta-llama/Llama-3.1-8B/config.json
llama_31_8b = {
    "num_hidden_layers": 32,
    "num_attention_heads": 32,
    "num_key_value_heads": 8,
    "hidden_size": 4096,
}

per_token = kv_bytes_per_token(llama_31_8b)
print(f"{per_token:,} bytes per token ({per_token // 1024} KiB)")
for tokens in (2_048, 8_192, 131_072):
    print(f"{tokens:>7,} tokens: {tokens * per_token / 2**30:5.2f} GiB")

budget = 52e9  # bytes left for the cache on one GPU, from the budget above
for tokens in (2_048, 8_192, 32_768):
    fits = int(budget // (tokens * per_token))
    print(f"{tokens:>6,}-token requests that fit: {fits}")
You should see
131,072 bytes per token (128 KiB)
  2,048 tokens:  0.25 GiB
  8,192 tokens:  1.00 GiB
131,072 tokens: 16.00 GiB
 2,048-token requests that fit: 193
 8,192-token requests that fit: 48
32,768-token requests that fit: 12

Download the config.json of a model you use and replace the dictionary with its values. Models that set head_dim explicitly are handled too.

Common mistakes

Symptoms you may see, their usual cause, and the fix
SymptomLikely causeFix
Your estimate is 4 times too high for Llama 3You used num_attention_heads (32) instead of num_key_value_heads (8).Use the KV head count. It is the one that sets the cache size.
Your estimate is half of what the engine reportsThe factor of 2 for keys and values is missing.Every token stores a key and a value at every layer.
The server runs out of cache although prompts are shortCapacity was planned from prompt length only.Count prompt plus maximum output tokens for each request.
Your own decode loop produces garbage after the first tokenThe new token was given position 0 instead of its real position.The new token’s position is the current cache length. Rotary and learned position embeddings both depend on it.
Memory use creeps up until requests start queuingFinished or cancelled requests never release their cache.Free the cache on every exit path, including errors and client disconnects.
Numbers disagree by about 7%GB and GiB were mixed.1 GiB is 1.074 GB. Pick one unit and convert once.

How real engines manage the cache

Everything above assumed one contiguous cache per request. Production engines build a lot on top of that to fit more requests and to reuse work across requests. You will meet each technique in detail in the engine courses.

  • Paging. vLLM stores the cache in fixed-size blocks (16 tokens by default) and gives a request a new block only when it needs one, so no memory is reserved for tokens that may never be generated. See PagedAttention.
  • Prefix sharing. Requests that start with the same tokens, such as a shared system prompt, can point at the same cache blocks instead of computing and storing them again. See RadixAttention.
  • Lower precision. An FP8 cache halves memory per token. vLLM exposes it as --kv-cache-dtype fp8. Measure quality on your own prompts before and after.
  • Preemption. When the cache is full, an engine can pause a running request, free its cache, and recompute it later. Latency rises, but nothing crashes.
  • Offloading. Some systems move cache blocks that are not in use to CPU memory or SSD and bring them back on a later hit. NVIDIA Dynamo and SGLang both support this.
  • Model architecture. Grouped-query attention shares KV heads, and multi-query attention keeps just one. DeepSeek-V2 and V3 use multi-head latent attention, which caches one compressed vector per token per layer. Sliding-window attention, used by the first Mistral 7B release, keeps only the most recent 4,096 positions per layer.

When you operate a serving engine, watch three signals: how full the cache is, how often requests are preempted, and how often prefixes are reused. A cache that sits near 100% with rising preemptions means the GPU is holding more tokens than it can fit. The fix is fewer or shorter concurrent requests, a smaller cache format, or more GPU memory.

Go deeperWhy decode speed depends on memory bandwidth

Each decode step reads every model weight once, and every active request’s entire cache once. On an H100 SXM with 3.35 TB/s of memory bandwidth, reading 16 GB of Llama 3.1 8B weights takes about 4.8 ms. That puts a ceiling of roughly 200 tokens per second on a single request, no matter how fast the math units are.

Batching many requests shares that weight read: one pass over the weights serves every request in the batch. The cache does not share this way. With 32 active requests of 8,192 tokens, each step also reads 32 × 1 GiB, about 34 GB of cache, which is twice the weights. At long contexts and large batches, the cache, not the weights, sets the speed of decode. This is why smaller KV formats and fewer KV heads help speed as well as capacity.

One decode step, 32 requests of 8K tokens, idealized

  1. Weight reads16 GB / 3.35 TB/s ≈ 4.8 ms
  2. Cache reads34.4 GB / 3.35 TB/s ≈ 10.3 ms
  3. Lower bound for the stepabout 15 ms for 32 new tokens

ResultAt most about 2,100 tokens per second in total

Real engines land below this bound, because no kernel reaches full bandwidth and there is other work in each step. The bound still tells you where the time goes.

Cheat sheet

  • The KV cache stores one key and one value per token, per layer, per KV head. Nothing else.
  • Reuse is exact: in a causal model, adding a token never changes earlier keys and values.
  • Decode still computes the new token through every layer and reads the whole cache at every step.
  • Bytes per token = 2 × layers × KV heads × head size × bytes per value.
  • Llama 3.1 8B in BF16: 128 KiB per token, 1 GiB per 8,192 tokens.
  • Plan capacity in tokens (prompt plus output), not in requests.
  • Use num_key_value_heads, not num_attention_heads.
  • A full cache shows up as queuing and preemption, not as errors.

Walkthrough

Follow one request through its KV cache

Request traceReady

Browser lab

Watch one token enter the cache

One request, float32, 2 heads.

Prefill · step 0 stored new
K012
V012
Readout3 positions · 768 bytes across 2 layers. Cumulative positions processed: 3 cached vs 3 recomputed.

Predict total K/V storage after the next token.

Knowledge check

With a KV cache, does the newest query ignore old keys?

Choose one answer

Sources and further reading

Finished this unit?