What is a KV cache?

The data a language model keeps so it does not redo work on tokens it has already read: how it works, how big it gets, and why it fills GPU memory.

Last updated

7 minute read

On this page
  1. How the KV cache works
  2. How big it gets
  3. Prefix caching
  4. Why it fills GPU memory
  5. FAQ

A KV cache is the set of attention keys and values that a transformer language model computes for every token it has already processed, kept in memory so that generating each new token reuses them instead of recomputing them.

Language models write one token at a time. Each new token has to look at every token before it, and in a transformer that looking is done by attention (Vaswani et al., 2017). Attention needs a key and a value vector for every earlier token in every layer. Those vectors do not change once computed, so engines store them. As the Hugging Face Transformers documentation puts it, "a KV cache stores these calculations so they can be reused without recomputing them."

How does the KV cache work?

Serving a request has two phases, and the KV cache connects them.

FIGURE 1. Prefill computes a key and a value for every prompt token in every layer and stores them. Each generated token reads all of them and adds its own. Qwen2.5-7B has 28 layers; other models differ.
Prefill
The engine runs the whole prompt through the model at once, computing a query, a key and a value for every token in every layer. The keys and values go into the KV cache. For long prompts this compute-heavy phase is most of the wait before the first token.
Decode
The model generates one token at a time. Each new token compares its query with every cached key, mixes the cached values and appends its own key and value. Without the cache, every step would recompute keys and values for the whole sequence so far.

The cache belongs to one model and to the exact tokens in the exact order they appeared. Change the first token and every key and value after it changes too.

How big is the KV cache?

For a standard transformer with multi-head or grouped-query attention, the size per token is the product of five numbers:

bytes per token = 2 × layers × KV heads × head dimension × bytes per value

"KV heads" is the number of key-value heads. With grouped-query attention it is smaller than the number of query heads (Ainslie et al., 2023), which is one of the main ways newer models shrink their cache.

Worked example: Qwen2.5-7B-Instruct in BF16

From the model's config.json: 28 hidden layers, 4 key-value heads, and 28 attention heads over a hidden size of 3,584, so a head dimension of 3,584 / 28 = 128. BF16 stores each value in 2 bytes.

FIGURE 2. Prompt length x 57,344 bytes, for the prompt lengths in our SGLang study. The 110k prompt was stored as 3,436 blocks.
  • FP8 KV cache halves every figure above.
  • Multi-latent attention models, such as DeepSeek-V3, store a compressed latent instead of full keys and values, so they need a different formula.
  • The KV cache calculator covers common models and precisions.

What is prefix caching?

Prefix caching keeps the KV cache after a request finishes, so that a later request beginning with the same tokens can reuse it. vLLM splits the cache into fixed-size blocks and identifies each one by a hash of "the tokens in the block and the tokens in the prefix before the block", plus extras such as LoRA IDs and a cache salt for tenant isolation (vLLM design docs). SGLang does the same with a radix tree, RadixAttention (Zheng et al.).

FIGURE 3. Reuse stops at the first block that differs, even when the rest of the text is identical.

Two rules follow from this design:

  • Only an exact prefix from the first token matches. Put the stable parts (system prompt, tool definitions, documents) first and per-user text last.
  • Only whole blocks are reused. Matching works in units of the block or page size, for example 16 or 64 tokens; a partial block at the end is recomputed.

Why does the KV cache fill GPU memory?

The cache grows with every token of every request in flight, and it shares GPU memory with the model weights. The PagedAttention paper that introduced vLLM describes the KV cache memory for each request as "huge" and changing size as requests start and end.

FIGURE 4. Qwen2.5-7B in BF16, if the GPU held nothing else: about 1,395,089 tokens. In practice the weights and working memory come first, so a handful of long prompts fill what is left.

When memory runs out, the engine evicts cached blocks, usually least recently used first, and any later request that needed them pays prefill again. Restarts empty the cache completely, and separate servers each keep their own.

Frequently asked questions

Is the KV cache stored in HBM or VRAM?

Yes, while the model is using it. The KV cache lives in GPU memory (HBM on data-centre GPUs such as the H100, GDDR on cards such as the L40S) because attention reads it on every generated token. When GPU memory runs short, engines can move cached blocks they are not using right now to CPU DRAM, local NVMe, a remote store or object storage, and copy them back when a request needs them. That is KV cache offloading.

Is the KV cache the same as the context window?

No. The context window is the maximum number of tokens a model can attend to, a property of the model (Qwen2.5-7B-Instruct's config sets 32,768 positions). The KV cache is the data the model actually holds for the tokens in a request: its size grows with the number of tokens in use, up to the context window, multiplied by the bytes per token for that model and precision.

What is the difference between a KV cache and prompt caching?

The KV cache is the data: keys and values for tokens already processed. Prompt caching (also called context caching) is a feature built on top of it: when a new request starts with the same tokens as an earlier one, the server reuses the stored KV cache for that prefix instead of recomputing it. Inside engines such as vLLM and SGLang this is called prefix caching. Hosted APIs offer it as a product, for example DeepSeek's context caching on disk, often with a lower price for cached tokens.

Is the KV cache used in training?

Not in the usual sense. In training the model sees each whole sequence at once and computes every position in parallel with a causal mask, so there is no token-by-token generation to speed up and keys and values are not kept between steps. The KV cache is an inference technique. The exception is training that generates text along the way, such as reinforcement learning rollouts, where the generation step uses a KV cache like any other inference.

Can a KV cache be reused with a different model or precision?

No. The keys and values depend on the exact weights, so a cache is only valid for the same model and revision, the same KV precision and the same layout settings (for example block or page size and parallelism). Engines and stores include these in the cache identity; vLLM names its offload directories from a digest of the model, block size, parallelism and dtype.

Why does the KV cache make long prompts slow?

It does the opposite once it exists: it is what makes generating each next token fast. The slow part is building it. Processing a long prompt (prefill) computes keys and values for every token in every layer, and that work grows faster than the prompt length. In our SGLang test on one L40S, building the cache for a 110,016-token prompt took 20.8 s. Keeping the cache and reusing it avoids paying that again.

Bring one workload. We will measure it with you.

Tell us your engine, model, GPUs and where context repeats or gets lost. We reply with what we would measure, what success looks like, and when KVStash is not worth it.

Or write to rudray@kvstash.com