P

KV Cache: Definition and Examples

KV Cache (Key-Value Cache) is an optimization mechanism used by language models (LLMs) to store already computed attention layer keys and values, avoiding recomputation for each new generated token.

Full definition

KV Cache, or key-value cache, is a fundamental optimization technique in the operation of large language models based on the Transformer architecture. During text generation, the attention mechanism must compute key vectors (Keys) and value vectors (Values) for each token in the sequence. Without caching, these computations would be fully repeated at every new token produced, which would be extremely resource-intensive.

The principle of KV Cache is simple: once a token has been processed, its key and value vectors are stored in memory. When the model generates the next token, it only needs to compute K and V for that new token, then combines them with the already cached values. This transforms a quadratic operation into a nearly linear one, significantly speeding up generation.

In practice, KV Cache determines the amount of GPU memory required to serve a model. For a model like GPT-4 or Claude, the cache can consume several gigabytes of VRAM per request, especially with long contexts. This is why techniques like Multi-Query Attention (MQA), Grouped-Query Attention (GQA), or cache quantization have been developed to reduce this memory footprint.

For the end user, KV Cache explains why the first token of a response is slower to appear (prefill phase where the entire prompt is processed) while subsequent tokens arrive much faster (decode phase where the cache is reused). It also explains why requests with very long contexts are more expensive and slower.

Etymology

The term combines 'KV' for Key-Value, from the Transformer attention mechanism that projects embeddings into three vectors — Query, Key, and Value — and 'Cache', borrowed from computer science where it refers to a fast memory storing frequently used data to avoid recomputing it.

Concrete examples

Inference optimization — Understanding why a long conversation slows down

If you notice your AI chatbot gets slower as the conversation progresses, it's because the KV Cache grows with each message exchanged. Reducing the context length sent or summarizing previous exchanges can help.

Model deployment — Sizing GPU infrastructure

To estimate VRAM needed for KV Cache: cache_size = 2 × number_of_layers × hidden_size × sequence_length × bytes_precision × batch_size. A Llama 70B in fp16 with 4096 context tokens consumes about 2.5 GB of KV Cache per request.

Prompt engineering — Structuring prompts to optimize costs

Place system instructions and static context at the beginning of the prompt. The KV Cache from prefill is reused across successive requests by some providers (prompt caching), which reduces latency and cost if the start of the prompt remains identical.

Practical usage

In prompt engineering, understanding KV Cache allows you to optimize your prompts for speed and cost. Place static content (system instructions, few-shot examples) at the beginning of the prompt to benefit from prompt caching offered by providers like Anthropic or OpenAI. Also keep in mind that very long contexts increase memory consumption and latency, so summarize or truncate long conversations when possible.

Related concepts

Attention (mechanism)TransformerContext windowPrompt Caching

FAQ

What is the difference between KV Cache and prompt caching?
KV Cache is an internal model mechanism that stores attention keys and values during generation of a single response. Prompt caching is an infrastructure-level optimization that reuses the KV Cache of a common prefix across multiple successive requests, avoiding recomputation of the prefill when the beginning of the prompt is identical.
Why is the first token slower than subsequent ones?
The first token requires the prefill phase: the model must process the entire input prompt and compute all K and V vectors for every token in the context. Once this KV Cache is built, each subsequent token only needs an incremental computation, which is much faster. This is the classic distinction between Time to First Token (TTFT) and inter-token throughput.
Does KV Cache impact response quality?
No, KV Cache is a purely computational optimization. It produces mathematically identical results to a full recomputation at each step. However, some cache compression techniques (such as int8 quantization or eviction of older tokens) can introduce slight approximations, but these are generally imperceptible in practice.

See also

How to use this prompt

  1. Copy the prompt with the button above.
  2. Paste it into ChatGPT, Claude or your favorite AI assistant.
  3. Replace the bracketed variables with your details, then refine the result.

About Prompt Guide

Prompt Guide is a free library of 2500+ ready-to-use prompts for ChatGPT, Claude and other AIs, with guides to learn prompting and tools to build and optimize your own prompts.

More definitions

Get new prompts every week

Join our newsletter.