{"slug": "what-does-the-kv-cache-actually-save", "title": "What Does the KV Cache Actually Save?", "summary": "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.", "body_md": "Start with the same sentence from the first two posts: `A triangle has…`\n\nThe model picks `\" three\"`. Then it picks `\" sides\"`. Then `\".\"`.\n\nIn *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`?\n\nImagine 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.\n\nAn attention layer works with three sets of numbers:\n\nEach 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**.\n\nReuse 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](https://huggingface.co/docs/transformers/en/cache_explanation)\n\nThese are simplified token boundaries. Watch when each chosen token enters the cache.\n\n```\nProcess [A] [ triangle] [ has] → pick \" three\"\nProcess [ three]               → pick \" sides\"\nProcess [ sides]               → pick \".\"\n```\n\n| Prediction | Rebuild every K/V pair | Compute with a cache | \n|---|---|---|\n| Pick `\" three\"` | 3 prompt pairs | 3 prompt pairs | \n| Pick `\" sides\"` | 4 pairs | 1 new pair for `\" three\"` | \n| Pick `\".\"` | 5 pairs | 1 new pair for `\" sides\"` | \n| **Total pairs computed** | **12** | **5** | \n\nOn 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.\n\nScale 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.\n\nA 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.\n\nThe 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.\n\n``` python\nfrom math import exp, isclose\n\ndef project(token_id):\n    return token_id + 1, token_id * 2\n\ndef attend(query, pairs):\n    weights = [exp(query * key) for key, _ in pairs]\n    weighted_sum = sum(\n        weight * value for weight, (_, value) in zip(weights, pairs)\n    )\n    return weighted_sum / sum(weights)\n\nprefix = []\ncache = []\nrebuilt_count = 0\ncached_count = 0\n\nfor new_ids in ([1, 2, 3], [4], [5]):\n    prefix.extend(new_ids)\n    rebuilt = [project(token_id) for token_id in prefix]\n    new_pairs = [project(token_id) for token_id in new_ids]\n    cache.extend(new_pairs)\n\n    query = prefix[-1] / 10\n    assert isclose(attend(query, rebuilt), attend(query, cache))\n\n    rebuilt_count += len(rebuilt)\n    cached_count += len(new_pairs)\n\nassert (rebuilt_count, cached_count) == (12, 5)\nprint(\"K/V pairs computed without cache:\", rebuilt_count)\nprint(\"K/V pairs computed with cache:   \", cached_count)\n```\n\n**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.\n\nThe 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?**\n\n*Adapted from [Why Cache Keys and Values?](https://int8ai.com/llm-foundations/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.*", "url": "https://wpnews.pro/news/what-does-the-kv-cache-actually-save", "canonical_source": "https://dev.to/int8ai/what-does-the-kv-cache-actually-save-3856", "published_at": "2026-11-27 10:38:55+00:00", "updated_at": "2026-11-27 10:45:54.396304+00:00", "lang": "en", "topics": ["large-language-models", "artificial-intelligence", "machine-learning", "ai-infrastructure"], "entities": ["Hugging Face"], "also_reported_by": [], "takeaway": "Caching keys and values cuts a 1,000-token prompt with a 200-token reply from 219,900 to 1,199 key/value pair computations per layer and KV head, because causal attention keeps earlier positions' keys and values valid.", "recommendation": {"advice": "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.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/what-does-the-kv-cache-actually-save", "markdown": "https://wpnews.pro/news/what-does-the-kv-cache-actually-save.md", "text": "https://wpnews.pro/news/what-does-the-kv-cache-actually-save.txt", "jsonld": "https://wpnews.pro/news/what-does-the-kv-cache-actually-save.jsonld"}}