Sub topic 2
What the provider actually stores: reusable attention state
This chapter assumes you know what tokens and context windows are and can read short Python. You don't need to know transformer math in detail. The chapter explains the one piece you need: what a provider keeps between your requests when it "caches a prompt".
The short answer
A provider does not store your prompt text for reuse, and it does not store the model's answer. It stores intermediate numbers the model computed while reading your prompt. These numbers are called the key/value (KV) state of the attention layers. When a later request starts with the same tokens, the provider loads that state instead of computing it again. It then processes only the new tokens.
Where the key/value state comes from
A transformer language model is a stack of layers. Each layer contains attention, which lets every token look at the tokens before it. For each token and each layer, the model computes three vectors from that token's current representation:
- A query, which asks "what am I looking for?"
- A key, which says "this is what I contain."
- A value, which is the information that gets passed along if the key matches a query.
A token's query is compared against the keys of all earlier tokens. The result weights the values of those tokens. Only the keys and values of earlier tokens are needed to process a later token. The queries of earlier tokens are never needed again.
That asymmetry is why caching works. Keys and values are worth keeping because every later token reads them. Queries are used once and thrown away.
Why the state depends only on the prefix
Language models used for text generation apply a causal mask. A token can attend to itself and to earlier tokens, never to later ones. Two consequences follow:
- The key and value for token 40 in layer 12 are a function of tokens 0 through 40 and the model weights. Nothing after token 40 can change them.
- If two prompts share their first 40 tokens exactly, they produce identical key/value state for those 40 positions.
The second point is the foundation of prompt caching. The next chapter builds on it to explain why only an identical prefix can hit. The toy below shows the dependency structure. Each position's "state" is a hash of everything before it plus the current token. Real states are tensors, not hashes, but they depend on earlier tokens in the same way.
import hashlib
def state_chain(tokens):
"""Toy per-position state: each value depends on all earlier tokens."""
states = []
prev = b""
for token in tokens:
prev = hashlib.sha256(prev + token.encode()).digest()
states.append(prev.hex()[:8])
return states
base = state_chain(["SYSTEM", "RULES", "DOC", "Q1"])
new_q = state_chain(["SYSTEM", "RULES", "DOC", "Q2"])
edited = state_chain(["SYSTEM", "RULES v2", "DOC", "Q2"])
print([x == y for x, y in zip(base, new_q)]) # [True, True, True, False]
print([x == y for x, y in zip(new_q, edited)]) # [True, False, False, False]In the first comparison, only the last position differs. The first three states can be reused. In the second comparison, the edit at position 1 changes the state at positions 1, 2 and 3, even though DOC and Q2 are identical in both prompts. A later token's state carries information about everything before it.
What a cache hit skips
Generating a response has two phases:
- Prefill. The model processes the whole prompt in parallel and builds the key/value state for every prompt token. Cost grows with prompt length.
- Decode. The model produces output tokens one at a time. Each new token reads the stored keys and values and adds its own.
Within a single request, every serving system already keeps the KV state so that decode doesn't recompute the prompt for each output token. Prompt caching extends the same idea across requests. The provider keeps the state from prefill for a while. If a new request begins with the same prefix, the provider loads the stored state and runs prefill only on the remaining tokens.
The output is meant to be the same either way, because the loaded state is the state the model would have computed. Tiny numerical differences can occur between runs on different hardware or batch sizes. These differences exist even without caching.
What is and isn't stored
| Item | Stored for reuse? | Notes |
|---|---|---|
| Key and value tensors for prefix tokens | Yes | Per layer, per attention head |
| Prompt text | Not as the thing that gets reused | The provider needs some way to match your prefix, such as a hash of the tokens. Check its data-retention documentation for details. |
| Model output | No | Caching does not return a stored answer. The model still generates a fresh response. |
| Query vectors | No | Used once during prefill |
| State for tokens after the cached prefix | Only if a later breakpoint or rule covers them | Depends on the provider's caching mode |
The third row matters for how you think about correctness. A prompt cache is not a response cache. Changing the question at the end still produces a new, fully computed answer. Only the shared beginning is skipped.
How big the stored state is
The stored state is large. For each token, the provider keeps a key and a value for every layer and every key/value head. The size per token is:
2 × layers × kv_heads × head_dim × bytes_per_value
The 2 is for keys plus values. The function below computes this for a configuration you supply. The numbers in the example are illustrative and describe no specific model.
def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_value=2):
return 2 * layers * kv_heads * head_dim * bytes_per_value
def kv_gib(tokens, **config):
return tokens * kv_bytes_per_token(**config) / 2**30
config = dict(layers=32, kv_heads=8, head_dim=128, bytes_per_value=2)
print(kv_bytes_per_token(**config)) # 131072 bytes, which is 128 KiB per token
print(round(kv_gib(10_000, **config), 2)) # 1.22 GiB for a 10,000-token prefixA single 10,000-token prefix occupies over a gibibyte of accelerator or host memory in this configuration. Providers serve many customers on limited hardware, so this size explains several rules you will meet in later chapters: short lifetimes, minimum prompt lengths, and the price difference between reading and writing cache entries. Newer attention designs shrink the state by using fewer key/value heads or compressing it, but the per-token cost never drops to zero.
Edge cases that follow from the mechanism
- State is tied to one model version. Keys and values are produced by specific weights. A different model, or a new snapshot of the same model, cannot use another model's state. Switching models resets your cache.
- Position matters. Most modern models encode position by rotating query and key vectors according to where the token sits. The same words at a different offset produce different keys. Moving a block of text earlier or later in the prompt makes it a miss, even if the block itself is unchanged.
- Matching happens on tokens, not on how you see the text. Two strings that look the same to you can tokenize differently if, for example, a trailing space or an invisible character differs. A change you can't see is still a change.
- Everything before the match point must be identical. Because each state depends on all earlier tokens, a match cannot skip over a difference. The earlier toy showed this.
- Non-text inputs count too. Images, tool definitions and other content that the provider converts into tokens produce state in the same way. A change to any of them changes everything after it.
What to carry into the next chapter
Three facts from this chapter drive the rest of the tutorial:
- The provider stores key/value tensors computed during prefill.
- Those tensors for a given position depend on every token up to and including that position.
- The tensors are large, so providers keep them for a limited time and only for prompts long enough to be worth the effort.
The next chapter turns the second fact into the matching rule you work with every day: only an identical prefix can hit.
Exercise
A request has a 6,000-token prefix followed by a 40-token question. A second request has the same 6,000 tokens, except that the 5th token is different, followed by the same 40-token question. Using the model's causal attention, explain how many of the 6,040 token positions can reuse stored state from the first request, and why.
Show answer
Only the first 4 positions can reuse stored state. The key and value at each position depend on all tokens up to and including that position. Position 5 differs, so its state differs. Every later position attends to position 5 through the layers, so their states differ too, even though their tokens are identical. The remaining 6,036 positions must be prefilled again.
Exercise
Using the formula 2 × layers × kvheads × headdim × bytespervalue, compute the stored state per token for a model with 40 layers, 8 key/value heads, head dimension 128, and 2 bytes per value. Then compute the size in GiB of a 20,000-token prefix.
Show answer
Per token: 2 × 40 × 8 × 128 × 2 = 163,840 bytes (160 KiB). For 20,000 tokens: 163,840 × 20,000 = 3,276,800,000 bytes, which is about 3.05 GiB.