cd /news/large-language-models/what-does-the-kv-cache-actually-save · home › topics › large-language-models › article
[ARTICLE · art-177227] src=dev.to ↗ pub= topic=large-language-models verified=true sentiment=↑ positive

What Does the KV Cache Actually Save?

A developer published a walkthrough explaining what the KV cache actually saves during autoregressive LLM inference, showing that cached attention reuses previously computed keys and values rather than recomputing the whole prefix. A worked example with a 1,000-token prompt and 200-token reply puts the cost at 219,900 key/value pair computations per layer and KV head without caching versus 1,199 with it, and an accompanying Python demo verifies that cached attention matches rebuilding the prefix.

recommendation

Cache keys and values across decoding steps instead of recomputing the prefix; causal attention guarantees earlier positions' K/V pairs stay valid, cutting pair computations roughly 180x in the 1,000+200-token example.

more in playbook: Inference and self-hosting
by read4 min views6 publishedNov 27, 2026

Start with the same sentence from the first two posts: A triangle has…

The model picks " three". Then it picks " sides". Then ".".

In Why Does the First LLM Token Take Longer?, we saw that prefill processes the prompt and produces the scores for the first output token. Now you’ve just picked " three" and need to decide what comes next. How much work can you reuse from processing A triangle has?

Imagine keeping a stack of index cards as you read. Each card has a label you can match against a question and a note you can use in your answer. When a new question arrives, you can search the same stack and use a different mix of notes.

An attention layer works with three sets of numbers:

Each new position brings its own query. Earlier queries already did their work. The earlier keys and values still have a job because the new query uses them to decide what information to draw from the sequence. That’s why this is called a KV cache.

Reuse works because of causal attention. Each position can attend only to itself and earlier positions. Appending " three" can’t change what has was allowed to see, so the keys and values already computed for those earlier positions are still valid. Hugging Face guide to the KV cache

These are simplified token boundaries. Watch when each chosen token enters the cache.

Process [A] [ triangle] [ has] → pick " three"
Process [ three]               → pick " sides"
Process [ sides]               → pick "."
Prediction Rebuild every K/V pair Compute with a cache
Pick " three" 3 prompt pairs 3 prompt pairs
Pick " sides" 4 pairs 1 new pair for " three"
Pick "." 5 pairs 1 new pair for " sides"
Total pairs computed 12 5

On the last row, the model creates one new pair and uses all five for attention. The cache saves the work of running the earlier positions through the model again. The new query still scores the available keys.

Scale that up to a 1,000-token prompt and a 200-token reply. Counting through the prediction of the 200th token, rebuilding the prefix takes 219,900 pair computations per layer and KV head (1,000 + 1,001 + … + 1,199). Caching takes 1,199 ( 1,000 + 199). Those counts track how many pairs the model computes. The cached pairs are still used during attention.

A real model computes keys and values from each position’s representation at each layer. In deeper layers, that representation can already contain information from earlier tokens. Causal attention keeps later tokens from changing that earlier work.

The demo uses one scalar key and value per position so the arithmetic is easy to follow. It supplies the chosen token IDs and checks that cached attention produces the same result as rebuilding the prefix.

from math import exp, isclose

def project(token_id):
    return token_id + 1, token_id * 2

def attend(query, pairs):
    weights = [exp(query * key) for key, _ in pairs]
    weighted_sum = sum(
        weight * value for weight, (_, value) in zip(weights, pairs)
    )
    return weighted_sum / sum(weights)

prefix = []
cache = []
rebuilt_count = 0
cached_count = 0

for new_ids in ([1, 2, 3], [4], [5]):
    prefix.extend(new_ids)
    rebuilt = [project(token_id) for token_id in prefix]
    new_pairs = [project(token_id) for token_id in new_ids]
    cache.extend(new_pairs)

    query = prefix[-1] / 10
    assert isclose(attend(query, rebuilt), attend(query, cache))

    rebuilt_count += len(rebuilt)
    cached_count += len(new_pairs)

assert (rebuilt_count, cached_count) == (12, 5)
print("K/V pairs computed without cache:", rebuilt_count)
print("K/V pairs computed with cache:   ", cached_count)

Try it. Add [6] to process the period and make one more prediction. The uncached path computes six more pairs. The cached path computes one. Change the final assertion to (18, 6) and check that the attention results still match.

The trade-off is memory. With full attention, a longer sequence leaves more keys and values to store and more data for each new query to use. That raises the next practical question. How much GPU memory does the KV cache take as a conversation grows?

Adapted from Why Cache Keys and Values?, which includes an interactive stepper that shows the cache growing one token at a time. AI assisted with drafting this adaptation.

── more in #large-language-models 4 stories · sorted by recency
── more on @hugging face 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/what-does-the-kv-cac…] indexed:0 read:4min 2026-11-27 · —