KV Caching
Interactive Tutorial
Progress 1 / 9

Late nights fueled by code,
A technical ballet unfolds,
Heart and work in one ode.

Do you think this haiku was written by a human or a language model?

As of 2024, both OpenAI and Anthropic charge 10x less for cached input tokens. Anthropic claims caching can reduce latency by up to 85%.

But what exactly gets cached? Let's find out.

How LLMs Generate Text

LLMs predict the next word in a sequence. Try it yourself:

Prompt
Mary had a little ___

How many times does the LLM need to run to generate "lamb"?

The Expensive Part: Attention

Inside the LLM, the attention mechanism determines how much each token should influence the next prediction.

Attention Weights
Mary
had
a
little
?
Mary
had
a
little
?
Computed
Masked (future)

To predict the next word after "little", how many attention scores must we compute?

Inside Attention: Q, K, V

Attention uses three matrices derived from your input:

Q
Query
"What am I looking for?"
K
Key
"What do I contain?"
V
Value
"What info do I carry?"
# For each token, compute Q, K, V
Q = embeddings @ W_Q
K = embeddings @ W_K
V = embeddings @ W_V
# Attention scores
scores = Q @ K.T
output = softmax(scores) @ V

When we add a NEW token to the sequence, which matrices change?

The KV Cache

Since K and V for old tokens never change, we can cache them!

Token Generation with Cache
Mary
K Cache
K[Mary]
V Cache
V[Mary]
1
Cache entries
0%
Compute saved

💡 Key Insight

With KV caching, we only compute K and V for the new token, then append to the cache.

The Math: Why 10x Cheaper

Let's compare compute costs. Adjust sequence length:

Sequence Length 1000
Without Cache With KV Cache
FLOPs per token 8.2B 8.2M
Growth Rate O(L²) O(L)
1000x
Compute Savings

Why do providers charge ~10x less (not 1000x less)?

Prompt Caching Across Requests

Providers also cache across requests!

Multiple Users, Same System Prompt
System Prompt (4000 tokens)
"You are a helpful assistant..."
User 1: "What is 2+2?"
4010
Total
0
Cached
0%
Savings

💡 This is why prompt caching matters!

100 users sharing the same prompt = pay full price once, then 10x cheaper for 99.

🧪 Quick Test

Let's check your understanding with 3 key questions.

Score: 0 / 3
QUESTION 1 OF 3

What exactly gets cached in "KV caching"?

🎉 Summary

What exactly gets cached?

The K and V matrices from the attention mechanism.

K = embeddings @ W_K # Cached!
V = embeddings @ W_V # Cached!

Why does it work?

K and V for a token only depend on that token's position, not future tokens.

Where do the savings come from?

  1. Within generation: Don't recompute K, V for past tokens
  2. Across requests: Share cache for same prompt prefix
10x
Cheaper
85%
Faster
O(L)
vs O(L²)

💡 Bonus: Temperature doesn't invalidate the cache!

Temperature only affects the final token selection. The KV cache is computed before that step.

🎓 You've completed the KV Caching tutorial!