Model Tells You Where to Merge: Adaptive KV Cache Merging for LLMs on Long-Context Tasks

Zheng Wang, Boxiao Jin, Yuming Chang, Zhongzhi Yu, Minjia Zhang · Submission to ICLR 2025 · Rejected

TL;DR

KVMerger is an adaptive Key-Value (KV) cache compression framework that merges similar key-value states rather than permanently evicting them. By exploiting the localized token similarity introduced by Rotary Position Embeddings (RoPE), it clusters adjacent key states and merges them using a Gaussian kernel weighted function, cutting KV cache memory by up to 60% while matching full-cache accuracy on long-context benchmarks.

What Problem Does This Paper Address?

Serving Large Language Models (LLMs) over long contexts creates a massive memory bottleneck. The KV cache—which stores intermediate attention keys and values for past tokens to prevent redundant recalculations—scales linearly with context length and batch size.

Existing solutions have notable shortcomings:

  • Quantization compresses numerical precision but is complementary rather than a complete fix.
  • Eviction methods (e.g., $H_2O$) drop "unimportant" tokens based on past attention scores. However, permanently dropping tokens risks deleting critical context needed later in extended sequences.
  • Previous merging methods (such as CaM) typically evict key states and only merge value states, or rely heavily on prior eviction heuristics, still leading to significant information loss.

Methods

KVMerger formulates cache compression as a constrained clustering and weighted merging process:

  1. Greedy Clustering for Merging Set Identification: Adjacent key states exhibit high local similarity. KVMerger scans consecutive tokens backwards from the most recent sequence positions and groups contiguous key states whose cosine similarity exceeds a fixed threshold (e.g., 0.75). Attention sinks and "heavy-hitter" tokens (tokens with top-ranked aggregated attention scores) are protected from merging.

  2. Pivotal State Selection: Within each identified merging cluster, the token with the highest aggregated attention score is designated as the cluster's pivot.

  3. Gaussian Kernel Weighted Merging: Instead of uniform averaging (which distorts representation space), remaining keys and values in the cluster are merged into the pivot state via Gaussian kernel weights: $$w_i \propto \exp\left(-\frac{\|k_p - k_i\|^2}{2\sigma^2}\right)$$ where the bandwidth $\sigma$ is dynamically set to the average Euclidean distance between the pivot $k_p$ and member tokens $k_i$. Value states are merged using the exact same weights derived from the keys.

[Key Cache] ---> [Identify Clusters (Cosine Sim > θ)] 
            ---> [Pick Pivot (Max Attention Score)] 
            ---> [Gaussian Kernel Merging (Keys & Values)]

Datasets

The authors evaluated KVMerger across multiple benchmarks and models (Llama2-7B-chat, Llama2-13B-chat, and Mistral-7B-Instruct-v1.0):

  • LongBench: 9 multi-task long-context datasets (2WikiMQA, GovReport, NarrativeQA, Passage Retrieval, MultiFieldQA, TREC, MultiNews, TriviaQA, Qasper).
  • ZeroScrolls: 7 summarization and query tasks (GovReport, SummScreenFD, QMSum, SQuALITY, Qasper, NarrativeQA, BookSumSort).
  • Needle-in-a-Haystack: Synthetic retrieval test evaluating key fact retrieval across depths ranging from 5% to 95% and lengths up to 4,500 tokens.
  • SynthWiki: Used for analyzing exploratory token-level similarity distributions.

Key Insights and Ideas

  • Why Keys Are Similar but Values Are Not: Rotary Position Embedding (RoPE) rotates key and query vectors based on absolute position. Because nearby tokens experience small angular differences, adjacent key vectors remain tightly aligned in cosine space. Value vectors lack RoPE, explaining why localized token similarity exists strongly in key states but not in value states.
  • Persistent KV Cache Sparsity: When applying a fixed similarity threshold, the layer-wise compression ratio remains remarkably stable across different samples and completely different tasks for a given model. This allows practitioners to set predictable memory budgets without per-task tuning.
  • Gaussian Weighting vs. Mean Averaging: Ablations demonstrate that uniform averaging drastically hurts downstream accuracy (dropping LongBench average from 24.20 to 21.84 on Llama2-7B-chat), whereas distance-sensitive Gaussian weighting protects the pivot token from outlier noise.

Key Results

  • LongBench Performance:
  • On Llama2-7B-chat, full cache scores 35.22. At a 50% cache budget, KVMerger achieves 35.02 (outperforming $H_2O$'s 34.00 and CaM's 33.67). At a 35% cache budget, KVMerger maintains 34.50 (vs. $H_2O$'s 33.49 and CaM's 33.36).
  • On Mistral-7B-Instruct (using Grouped-Query Attention), $H_2O$ degrades to 13.48 under a 35% budget, whereas KVMerger holds strong at 35.04 (near the full-cache baseline of 38.44).
  • ZeroScrolls & Retrieval: KVMerger closely tracked full-cache performance across all ZeroScrolls tasks and maintained high retrieval accuracy across nearly all document depths and context lengths in the Needle-in-a-Haystack test.
  • Memory Footprint: Reduces KV cache storage by up to 60% under a 35% cache budget while lowering overall peak inference memory.

Limitations and Future Work

  • Strict Contiguity Constraint: To preserve locality, KVMerger only clusters immediately consecutive tokens. Tokens with semantic similarity located far apart in the context window are currently ignored for merging.
  • Hardware/Latency Overhead: While the paper measures KV cache footprint and peak GPU memory reduction, it does not detail end-to-end inference wall-clock latency or kernel execution overhead introduced by online clustering and Gaussian weighting during decoding.
  • Future Directions: Expanding merging policies across non-adjacent tokens or cross-layer dimensions, and implementing optimized custom CUDA/Triton kernels for merging routines.

Summary updated

BibTeX
@misc{wang2024model,
  author = {Zheng Wang and Boxiao Jin and Yuming Chang and Zhongzhi Yu and Minjia Zhang},
  title = {{Model Tells You Where to Merge: Adaptive KV Cache Merging for LLMs on Long-Context Tasks}},
  year = {2024},
  eprint = {2407.08454},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2407.08454},
}
Figure