KeyDiff: Key Similarity-Based KV Cache Eviction for Long-Context LLM Inference in Resource-Constrained Environments

Junyoung Park, Dalton Jones, Matthew J Morse, Raghavv Goel, Mingu Lee, Chris Lott

TL;DR

KeyDiff is a training-free, attention-free Key-Value (KV) cache eviction method that selects which tokens to keep based purely on the geometric diversity of their key states. By eliminating the need to calculate and materialize full attention matrices, KeyDiff enables strict block-wise streaming on resource-constrained edge devices and seamlessly integrates with hardware-optimized kernels like FlashAttention. This approach reduces end-to-end inference latency by up to 30% while maintaining near-baseline accuracy on long-context and reasoning benchmarks.

What Problem Does This Paper Address?

Deploying Large Language Models (LLMs) for long-context applications—such as document summarization, retrieval-augmented generation (RAG), and complex multi-step reasoning—is severely bottlenecked by the memory footprint of the KV cache, which grows linearly with input length. On resource-constrained edge devices (like smartphones), this memory overhead quickly exceeds hardware limits.

To stay within strict memory bounds, systems use block-wise prompt processing, dividing long inputs into smaller chunks processed sequentially. However, existing KV cache eviction methods (which decide which tokens to throw away to save memory) rely heavily on attention scores. This creates two major flaws:

  1. Context Mismatch: During block-wise processing, attention scores are calculated using only the current block, completely blind to future tokens. This causes the system to prematurely evict tokens that might be highly relevant later in the prompt.
  2. Compute Inefficiency: Tracking attention scores requires materializing the massive attention weight matrix, which breaks compatibility with highly optimized attention kernels like FlashAttention, driving up latency.

Methods

The authors introduce KeyDiff, a cache eviction policy driven entirely by the geometry of the cached keys rather than attention scores.

The core algorithm works as follows:

  • The Geometric Insight: The authors discovered a strong negative correlation between a key's average pairwise cosine similarity to other keys and its ultimate attention score. Keys that are geometrically unique or "distinctive" naturally attract high attention weights.
  • Anchor Vector Optimization: Instead of computing a computationally expensive $O(n^2)$ pairwise similarity matrix for all keys in the cache, KeyDiff uses an efficient $O(n)$ variant. It calculates an anchor vector—the average of all normalized keys currently in the cache.
  • Eviction Criteria: KeyDiff measures the cosine similarity between each key and this anchor vector. It then retains the top-$K$ keys that have the lowest similarity to the anchor, effectively maximizing the diversity of the remaining cache.
Figure 1: An example of block prompt processing with KV cache eviction. The input prompt having length of 7 is segmented by three blocks, and a transformer layer in LLM processes each block by (1) computing key-value states from inputs, (2) computing attention, (3) computing the eviction score, and (4) performing eviction based on the eviction score to satisfy the memory constraints (e.g., at most 4 tokens can reside in the cache). After each block processing, the KV cache is updated and passed to the next round of block processing, satisfying imposed memory constraints on the KV cache.

For tasks demanding high recency bias (like coding or mathematical reasoning), KeyDiff can be augmented with a simple sliding window mechanism to guarantee that the most recent tokens are never evicted.

Datasets

The authors evaluated KeyDiff across several standard benchmarks using Llama and Qwen model families:

  • LongBench: A comprehensive multi-task benchmark suite for long prompts (including datasets like NarrativeQA, Qasper, and HotpotQA).
  • Needle-In-a-Haystack: A stress test evaluating an LLM's ability to retrieve a specific piece of information hidden deep within a massive body of unrelated text.
  • Math500: A reasoning benchmark used to test the distilled DeepSeek-R1 models on complex mathematical problem-solving.

Key Insights and Ideas

  • Diversity as an Attention Proxy: The most profound insight is that key diversity serves as an excellent proxy for global token importance. KeyDiff can identify crucial tokens (including "attention sinks") purely by looking at the geometry of the keys already processed, without needing access to future tokens or query states.
  • Unlocking FlashAttention: Because KeyDiff operates entirely outside the attention mechanism, it completely bypasses the need to materialize the attention matrix $A$. This allows developers to use FlashAttention during the prefill and generation stages, solving a long-standing engineering bottleneck for cache eviction algorithms.
  • The Mechanics of Attention Sinks: Geometrically, most keys and queries in an LLM are approximately collinear with their respective means, but the mean key and mean query point in opposite directions. Tokens that act as attention sinks break this mold; their keys are highly distinctive, allowing them to project closer to the query distribution and command high attention scores.

Key Results

  • Near-Lossless Accuracy: On LongBench, KeyDiff achieved a performance gap of less than 0.04% compared to the non-evicting baseline for Llama 3.1-8B and Llama 3.2-3B when utilizing an 8K cache budget (representing a ~23% reduction in KV cache size).
  • Superior Reasoning Performance: When testing DeepSeek-R1-Distill-Llama-8B on the Math500 benchmark, KeyDiff paired with a sliding window matched or slightly exceeded the non-evicting baseline, outperforming competing methods like SnapKV.
  • 30% Latency Reduction: By enabling FlashAttention integration, KeyDiff reduced time-to-first-token (TTFT) and end-to-end inference latency by up to 30% compared to attention-based token eviction methods.

Limitations and Future Work

Currently, KeyDiff is primarily designed and validated for models utilizing Grouped-Query Attention (GQA), such as the Llama and Qwen architectures. The authors note that a key direction for future work is extending KeyDiff to support other popular attention variants, most notably Multi-Head Latent Attention (MLA), which is heavily utilized in the native DeepSeek model families.

Summary updated

Abstract

We demonstrate that geometrically distinctive keys during LLM inference tend to have high attention scores. Based on the phenomenon we propose KeyDiff, a training-free KV cache eviction method based solely on key similarity. Unlike other KV cache eviction methods, KeyDiff can process arbitrarily long prompts within strict resource constraints and efficiently generate responses. We provide a theoretical basis for KeyDiff by relating key diversity with attention scores. These results imply KeyDiff can efficiently identify the most important tokens to retain. Notably KeyDiff does not rely on attention scores, allowing the use of optimized attention mechanisms like FlashAttention. Under a strict memory allowance, we demonstrate the effectiveness of KeyDiff for the Llama and Qwen model families by observing a performance gap of less than 0.04% with 8K cache budget ($\sim$23% KV cache reduction) from the non-evicting baseline on LongBench for Llama 3.1-8B and Llama 3.2-3B. We also observe near baseline performance for Deepseek-R1-Distill-Llama-8B on the Math500 reasoning benchmark and decrease end-to-end inference latency by up to 30% compared to the other token-eviction methods.
BibTeX
@inproceedings{park2025keydiff,
  author = {Junyoung Park and Dalton Jones and Matthew J Morse and Raghavv Goel and Mingu Lee and Chris Lott},
  title = {{KeyDiff: Key Similarity-Based KV Cache Eviction for Long-Context LLM Inference in Resource-Constrained Environments}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2025},
  url = {https://openreview.net/forum?id=uBaFH7aQnC},
}
Figure