User Agents

Web browsers and everyday web tech, explained

KV Cache Explained: How It Speeds Up LLMs

· 6 min read · Cookies and Cache

In this article
  1. Background: The Need for Speed in LLM Inference
  2. How the KV Cache Works
  3. Visualizing the KV Cache
  4. Memory Trade-Offs and Limitations
  5. Alternatives and Optimizations
  6. Common Misconceptions
  7. Frequently Asked Questions

KV cache, or Key-Value cache, is a memory optimization technique used in large language models (LLMs) to store intermediate attention computations, significantly reducing redundant processing during text generation. By reusing previously computed key and value vectors for earlier tokens, the model avoids recalculating them at each step, accelerating inference while maintaining accuracy.

Background: The Need for Speed in LLM Inference

Large language models like GPT, Llama, or PaLM generate text one token at a time. At each step, they use a mechanism called self-attention to weigh the importance of all previous tokens when predicting the next one. This process is computationally expensive, especially as the sequence grows longer. Without optimization, generating a 100-token response would require recalculating attention over all prior tokens at every single step—leading to O(n²) complexity, where n is the sequence length.

This inefficiency becomes a major bottleneck in real-time applications such as chatbots, code assistants, or translation tools, where low latency is critical. The KV cache addresses this by caching the key and value vectors from earlier attention layers, allowing the model to skip recomputation and focus only on the new token.

How the KV Cache Works

In transformer-based models, each token’s representation passes through multiple attention heads in each layer. For each head, three vectors are computed: Query (Q), Key (K), and Value (V). The attention score between two tokens is derived from the dot product of their Q and K vectors, then used to weight the V vectors.

During autoregressive generation (one token at a time), the Q vector for the current token must interact with the K and V vectors of all prior tokens. Instead of recalculating K and V for every past token at each step, the KV cache stores them after their first computation. On the next iteration, the model retrieves these cached vectors instead of regenerating them.

The process unfolds as follows:

  1. The first token is processed normally; its K and V vectors are computed and stored in the cache.
  2. For the second token, the model computes its Q vector and retrieves the first token’s K and V from cache to compute attention.
  3. The second token’s own K and V vectors are appended to the cache.
  4. This repeats for each new token, with only the current token’s Q vector being newly computed, while all prior K and V vectors are pulled from memory.

This reduces the computational load from O(n²) to roughly O(n), making long-form generation much more efficient. The cache is typically stored in GPU memory (or CPU memory if offloaded) and organized by layer, attention head, and sequence position.

Visualizing the KV Cache

A KV cache visualizer is a tool that graphically represents how the cache evolves during text generation. These tools help developers and researchers understand memory usage, attention patterns, and performance bottlenecks. They typically show:

  • How many tokens are cached at each layer
  • Memory footprint over time
  • Which tokens are reused and when they’re accessed
  • Cache hit/miss patterns in systems with memory offloading

For example, a visualizer might display a heatmap showing attention weights between current and cached tokens, or a timeline of cache growth as a sentence is generated. Some tools integrate with frameworks like Hugging Face Transformers or vLLM to capture real-time cache behavior. These visuals are especially useful for debugging long-context issues or optimizing memory management in production systems.

Memory Trade-Offs and Limitations

While the KV cache dramatically speeds up inference, it comes at the cost of increased memory usage. Each cached key and value vector consumes storage proportional to the model size and sequence length. For a 7B-parameter model with 32 layers and 32 attention heads, the cache can require several gigabytes of VRAM for long sequences.

Common limitations include:

  • Memory exhaustion: Long prompts or extended generations can fill GPU memory, causing out-of-memory errors.
  • Context window limits: Most models cap context length (e.g., 8K or 32K tokens), partly due to KV cache size constraints.
  • Cache invalidation: In interactive settings (e.g., chat), if a user edits earlier input, the cache becomes stale and must be partially or fully discarded.

Some systems use paged attention (as in vLLM) to manage the cache more efficiently by breaking it into blocks, similar to virtual memory paging. This allows swapping less-used cache blocks to CPU memory or disk, improving throughput in multi-request scenarios.

Alternatives and Optimizations

When full KV caching isn’t feasible, several alternatives help balance speed and memory:

  • Sliding window attention: Only the most recent N tokens are cached, discarding older ones. Used in models like Mistral 7B.
  • Grouped query attention: Reduces the number of key/value heads, shrinking cache size with minimal accuracy loss.
  • Quantization: Storing cached vectors in lower precision (e.g., FP16 or INT8) cuts memory use by up to 50%.
  • Speculative decoding: Uses a smaller model to draft tokens, then verifies them with the larger model, reducing total attention computations.

Some experimental approaches include attention sinks, where early tokens are permanently cached and always attended to, improving coherence in long conversations without unbounded memory growth.

Common Misconceptions

One widespread misunderstanding is that the KV cache stores raw text or full token representations. In reality, it only stores the key and value vectors from attention layers—intermediate mathematical representations, not human-readable data.

Another misconception is that KV caching changes the model’s output. It does not. The cache is an implementation detail that affects performance, not prediction. As long as the cache is correctly maintained, the model produces identical results to a version without caching.

Some also believe that KV caching is optional or only used in certain frameworks. In fact, virtually all modern LLM inference engines—including Hugging Face transformers, vLLM, TensorRT-LLM, and ONNX Runtime—use KV caching by default because the performance gains are too significant to ignore.

Frequently Asked Questions

Does KV cache affect model accuracy?

No, the KV cache does not alter model accuracy. It is a computational optimization that stores intermediate values used in attention calculations. As long as the cache is correctly implemented, the model produces the exact same output as it would without caching.

Why is it called 'KV' cache?

"KV" stands for Key and Value, the two vectors in the attention mechanism that are cached. The Query vector is computed fresh for each new token, while the Key and Value vectors from prior tokens are stored and reused, hence the name.

Can KV cache be disabled?

Yes, but it’s strongly discouraged. Disabling KV cache forces the model to recompute all prior attention vectors at each step, drastically slowing down generation—often by 10x or more for longer sequences.

How much memory does KV cache use?

Memory usage depends on model size, sequence length, and precision. For a 7B model in FP16, caching 2K tokens typically uses 2–4 GB of VRAM. The formula is approximately: 2 × num_layers × num_heads × head_dim × seq_len × bytes_per_param.

Is KV cache the same as model caching?

No. Model caching usually refers to storing the entire model weights in memory. KV cache specifically refers to caching the Key and Value vectors during inference. It is a runtime optimization, not a model-level one.

Do all LLMs use KV cache?

Virtually all modern LLMs use KV caching during autoregressive generation. It’s a standard feature in inference frameworks. Even models with specialized attention mechanisms (e.g., Mamba, RWKV) use analogous caching strategies tailored to their architecture.