# What Is the KV Cache?

> What the KV cache stores, why it makes each new word faster, what it costs in GPU memory and how teams shrink it, for your AI interview.

**In short:** The KV cache stores the keys and values the model has already worked out for earlier tokens, so each new word reuses them instead of recalculating them. It speeds up generation, and the price is GPU memory, which grows with every token in the conversation.

AI and LLM interview question Q055, Transformer architecture. Intermediate, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-the-kv-cache

## Say it in 30 seconds

The KV cache is a store inside the model. When it writes a word, it looks back at every earlier word, and the cache keeps the keys and values it already worked out for them. So each new word only needs its own pair worked out. Without the cache, the model would redo that work for the whole conversation on every word. The price is GPU memory, which grows with every token, so long claim files need planning.

## Say it in 2 minutes

A language model writes one token at a time. To choose each new token, it looks back at every token so far through the attention step. For each earlier token, in each layer, it has already worked out two small lists of numbers, a key and a value. If it threw those away, every new word would mean rebuilding them all.

The KV cache keeps them. Each new word works out only its own key and value, adds the pair to the store, and reads the whole store to pick the next word. Hugging Face's guide says the stored pairs are reused without recomputing them. Without the cache, every step recomputes the previous keys and values, so the work per word grows with the whole conversation.

The cost is memory. The cache grows in a straight line with length, for every layer and head, and by default it sits on the GPU while the reply is written. A long claim file can fill a card. Teams pick models built with shared heads, store fewer bits, move part of the cache to the CPU or page it the way an operating system pages memory, and each option trades something away.

So my answer: the KV cache is a reuse store. It speeds up generation because each step does only its own new work. It costs GPU memory, which I would plan for, measure and shrink when it gets tight.

## What is the KV cache, in plain words?

A language model writes one token at a time. A token is a chunk of text, often a word or part of one. To pick the next token, the model looks back at every token so far, in a step called attention. The model does this work on a GPU, the graphics chip that does most of the heavy maths, and a CPU, the main processor, can take some of its memory.

Each token gets two small lists of numbers in every layer of the model: a key, which helps the model decide how much attention each earlier token gets, and a value, which carries the information passed on. The KV cache is the store that keeps these keys and values for the tokens already processed.

Picture a claims clerk reading a 40-page claim file on a call. She writes a short note on each page. When the customer asks something new, she reads her notes rather than rereading all 40 pages. The KV cache is that pile of notes. In a real case, an insurer's claims assistant answers questions about a 6,000-token claim file, and the notes stop it from rereading the file for every word of the reply.

- **Token:** A chunk of text the model reads and writes, often a word or part of one.
- **Key and value:** Two lists of numbers the model works out for each token, in each layer.
- **Layer and head:** A layer is one stage of the model's processing. A head is one of several attention lookups run side by side inside a layer.
- **Attention:** The step where the model looks back at earlier tokens to decide what comes next.
- **Decoding:** Writing the reply one token at a time, after the input has been read.

## Why does the KV cache speed up generation?

Without a cache, every new token means recomputing the keys and values for every token before it. The work for each step grows as the conversation grows, and the model repeats the same sums over and over.

With the cache, each step works out a key and a value for the newest token only. It adds that pair to the store, then reads the whole store to choose the next token. Older pairs are never worked out again.

*Diagram, One new word, with the cache: Each new word adds one key and value pair to the cache. Attention reads the stored pairs, old and new, to pick the next word. The older pairs are not worked out again.*
1. The newest word goes in, and the model works out its key and value.
2. That new pair is added to the stored pairs. Nothing older is touched.
3. To pick the next word, attention reads the whole store once.

The code below counts the work for a 6,000-token claim file and a 300-token reply. It counts key and value work only. Read the gap as the point: without the cache, the work keeps repeating over the same file.

```python
# A claims assistant reads a 6,000-token claim file, then writes a 300-token reply.
PROMPT = 6000
REPLY = 300

# Without a cache, each new reply token redoes the key and value work for everything so far.
no_cache = sum(PROMPT + t for t in range(REPLY))
# With a cache, the key and value work is done once per token and then reused.
with_cache = PROMPT + REPLY

print(f"Key and value work, no cache: {no_cache:,}")
print(f"Key and value work, cache:    {with_cache:,}")
print(f"About {round(no_cache / with_cache)} times more key and value work without the cache")

# Cache memory: 2 (keys and values) x 32 layers x 8 heads x 128 values x 2 bytes (16-bit).
bytes_per_token = 2 * 32 * 8 * 128 * 2
print(f"Cache size for the whole conversation: {bytes_per_token * with_cache / 1e9:.1f} GB")
```

Output:

```text
Key and value work, no cache: 1,844,850
Key and value work, cache:    6,300
About 293 times more key and value work without the cache
Cache size for the whole conversation: 0.8 GB
```

> **Tip:** Say it in one line: the cache trades memory for speed. That tells an interviewer you see both sides of the deal.

## What does the KV cache cost in memory?

The cache is not free. It stores a key and a value for every token, in every layer and every head, and by default it stays on the GPU while the reply is written. Hugging Face's guide warns about exactly this, and the vLLM researchers describe the same problem for serving many users.

> "holding the key-value cache in memory can become very memory expensive for long input sequences or multi-turn chat." (Hugging Face)
>
> "the key-value cache (KV cache) memory for each request is huge and grows and shrinks dynamically." (The vLLM researchers)

Hugging Face gives the count as two times the sequence length, times the number of attention heads, times the head size, times the number of layers. Plug in a made-up model with 32 layers, 8 key-value heads of 128 values each, and 16-bit numbers. Each token then costs about 131 KB. Our 6,300 tokens need about 0.8 GB for one conversation, and that is before a second user arrives.

*Diagram, The cache grows with every token: The store grows with every token, for every layer and head. When the GPU is full, teams pick a model built with shared heads, store fewer bits or move part of the cache to the CPU. Each fix has a cost.*
1. Every token adds a key and a value to the store.
2. Each pair takes room in every layer and every head, so the total grows with each word.
3. A full GPU forces one of these fixes, and each one has a cost.

The memory grows in a straight line with length. For models with sliding-window layers, those layers stop growing once they reach their maximum size. Hugging Face says the maximum memory increases linearly with the number of generated tokens. Default self-attention memory is different: it grows quadratically with input length, which means doubling the length makes it four times bigger. That is the attention score table, a separate topic from this cache.

## How do teams fit the cache into less GPU memory?

1. **Share the key and value heads:** Multi-query attention uses a single key-value head shared by all query heads. The grouped-query paper says MQA can lead to quality degradation, so grouped-query attention keeps a few shared pairs as a middle ground. Hugging Face says either GQA or MQA is strongly recommended for chat-style use. Once a model is trained, its architecture is difficult to change, so this is a choice made at build time.
2. **Store fewer bits:** Hugging Face's QuantizedCache stores the keys and values at a lower precision, meaning fewer bits per number, so each one takes less space. It can slow generation when the context is short.
3. **Move part of it to the CPU:** Offloading keeps only the current layer's cache on the GPU. Hugging Face says you may notice a small drop in generation speed.
4. **Page the memory:** The vLLM paper is inspired by paging in operating systems and reports near-zero waste in KV cache memory.

For a chat assistant or a claims bot that handles long inputs, Hugging Face recommends grouped-query or multi-query attention when the model writes one token at a time (autoregressive decoding). That is the practical answer for long conversations.

### How would you cut the cost for a claims assistant that runs out of GPU memory?

First I would measure. The cache size depends on the number of tokens, so I would check the typical claim file length and the longest reply. Then I would pick the cheapest fix that fits: fewer heads in the model if we can change it, the cache stored at lower precision if quality holds, or paged memory in the serving system. I would test answers on real claim files, because Hugging Face notes that output with a cache can differ a little.

> **Tip:** A good answer names the trade-off each fix brings: possible slowdown for fewer bits, a small drop in speed for offloading, and a model built with shared heads, which is fixed at training time.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] What the cache stores: the keys and values of earlier tokens, in every layer.
- [ ] Why it is faster: each new word does work only for itself.
- [ ] The cost: GPU memory that grows with the length of the conversation.
- [ ] The fixes: shared heads, fewer bits, offloading and paged memory.
- [ ] The trade-off: memory for speed, and output that may differ slightly.
- [ ] A real case with numbers, marked clearly as an estimate.

**Common traps**

- Trap: "The cache makes the model remember things." Better: It is working space for the current conversation. What the model knows lives in its weights.
- Trap: "A cache always gives exactly the same answer." Better: Hugging Face recommends it because it leads to identical results, but notes the output may be slightly different. The cause is the matrix multiplication kernels on the GPU.
- Trap: "Just buy a bigger GPU." Better: That works for a while, but the cache grows with every token. Plan the length limit and the fixes too.

## Can you spot the wasted work?

**Spot the reused work:** Which call reuses the work already done for earlier tokens?

A. out = model(file_tokens + reply_so_far)
B. out = model(new_token)
C. out = model(new_token, cache=cache)
D. out = model(file_tokens, reply_so_far)

**Answer:** C. Passing the cache lets the model reuse the stored keys and values, so it works out only the new token. The first call redoes the whole file every step, and the second drops the claim file from the context entirely.

**Quick check:** A claims bot runs out of GPU memory on long chats. Which change shrinks the cache without retraining the model?

A. Store the cache at fewer bits per value
B. A longer system prompt
C. A higher temperature
D. A longer reply limit

**Answer:** A. Storing fewer bits per value makes each stored pair smaller. A longer system prompt, a longer reply and a higher temperature all make the cache bigger or leave its size unchanged.

## Can you answer these from memory?

**Flash cards**

- **What is the KV cache?** A store of the keys and values already worked out for earlier tokens, reused at each step.
- **Why is it faster?** Each new word works out only its own key and value, instead of redoing every earlier word.
- **What does it cost?** GPU memory. It grows in a straight line with the number of tokens, for every layer and head.
- **Is its growth quadratic?** No, linear. The cache adds one pair per token, so its size is a straight line.
- **Three ways to shrink it?** Share key-value heads, store fewer bits, or move part of it to the CPU.
- **Does a cache change the answer?** Possibly a little, because of the matrix multiplication kernels on the GPU. The output may differ slightly.

## Likely follow-up questions

- Q056 Why is attention quadratic in sequence length? https://designervenkat.online/interview/ai/why-is-attention-quadratic-in-sequence-length
- Q058 Multi-query vs grouped-query attention? https://designervenkat.online/interview/ai/multi-query-vs-grouped-query-attention
- Q065 Prefill vs decode phases? https://designervenkat.online/interview/ai/prefill-vs-decode-phases
- Q319 What is PagedAttention / vLLM? (full answer coming)
- Q311 What is quantization? https://designervenkat.online/interview/ai/what-is-quantization
- Q326 Prompt cache vs semantic cache vs KV cache? (full answer coming)

## Learn it in depth

- [Attention Mechanisms](https://designervenkat.online/learn/machine-learning/attention-mechanisms)
- [Inference Engineering](https://designervenkat.online/learn/ai-engineering/inference-engineering)
