SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2502.03805 · ICML · 2025

CriticalKV: Optimizing KV Cache Eviction from an Output Perturbation Perspective

S Zhou, Yuan Feng, Junlin Lv, Yukun Cao, Xike Xie, Haoyu Guo

arXiv · PDF · Open in the Atlas

Code that ran

4 of 11 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (2 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 3 have no contract verdict; 1 failure of our instrument; 7 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2502.03805.json · badge: /api/ran/2502.03805.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
FFY0/DefensiveKV community
Papers with Code archive
3 ran · 4 no recorded run
NVIDIA/kvpress marked official in Papers with Code
Papers with Code archive
1 ran · 3 no recorded run
FunctionStatusWhere it lives
DynamicCacheSplitHeadFlatten Ran
ran on a synthesized input · constructed an object; no result was computed
FFY0/DefensiveKV/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("653f147f7dedf90f")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, DynamicCacheSplitHeadFlatten: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from transformers.cache_utils import Cache

torch.manual_seed(0)

# Create valid arguments for DynamicCacheSplitHeadFlatten.__init__
ARGS = {
    "num_layers": 4
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
tiny_api_cuda, torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type DynamicCacheSplitHeadFlatten — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a DynamicCacheSplitHeadFlatten output the recorded ndim 1 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
ExpectedAttentionPress Ran
ran on a synthesized input
NVIDIA/kvpress/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("34a4bcd44bd02b5b")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned tuple, ndim 5, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
from torch.nn import functional as F
from dataclasses import dataclass
from transformers import Cache, QuantizedCache
from transformers.models.llama.modeling_llama import repeat_kv

@dataclass
class BasePress:
    """
    Base class for all KV cache compression methods.
    """

    def post_init_from_model(self, model):
        """
        Optional method to initialize press parameters from the model
        """
        pass

    def compress(self, module: nn.Module, hidden_states: torch.Tensor, keys: torch.Tensor, values: torch.Tensor, attentions: torch.Tensor, kwargs: dict) -> tuple:
        """
        The core logic of the compression method.
        """
        raise NotImplementedError('compress method must be implemented in subclass')

    def forward_hook(self, module: nn.Module, input: list, kwargs: dict, output: list):
        """
        Default forward hook called after the forward pass of an attention layer.
        """
        hidden_states = kwargs.get('hidden_states')
        cache = kwargs.get('past_key_values')
        
        if cache is None or hidden_states is None:
            return output
        
        cache_position = kwargs.get('cache_position')
        q_len = hidden_states.shape[1]
        
        if cache_position is not None and len(cache_position) > 0:
            if cache_position[-1].item() > 0:
                return output
        
        if hasattr(module, 'layer_idx') and module.layer_idx < len(cache.layers):
            cache_layer = cache.layers[module.layer_idx]
            
            if hasattr(cache_layer, 'k_cache') and hasattr(cache_layer, 'v_cache'):
                keys = cache_layer.k_cache
                values = cache_layer.v_cache
                
                if keys is not None and values is not None:
                    attentions = output[1] if len(output) > 1 else None
                    compressed_keys, compressed_values = self.compress(
                        module, hidden_states, keys, values, attentions, kwargs
                    )
                    cache_layer.k_cache = compressed_keys
                    cache_layer.v_cache = compressed_values
        
        return output


class MockAttentionModule(nn.Module):
    def __init__(self, hidden_dim=4, num_heads=2):
        super().__init__()
        self.hidden_dim = hidden_dim
        self.num_heads = num_heads
        self.head_dim = hidden_dim // num_heads
        self.layer_idx = 0
        self.q_proj = nn.Linear(hidden_dim, hidden_dim)
        self.k_proj = nn.Linear(hidden_dim, hidden_dim)
        self.v_proj = nn.Linear(hidden_dim, hidden_dim)
    
    def forward(self, hidden_states, past_key_values=None, cache_position=None, **kwargs):
        batch_size, seq_len, _ = hidden_states.shape
        q = self.q_proj(hidden_states)
        k = self.k_proj(hidden_states)
        v = self.v_proj(hidden_states)
        
        q = q.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        k = k.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        v = v.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        
        attn_output = torch.matmul(q, k.transpose(-2, -1)) / (self.head_dim ** 0.5)
        attn_output = F.softmax(attn_output, dim=-1)
        output = torch.matmul(attn_output, v)
        output = output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.hidden_dim)
        
        return output, attn_output


class MockCache:
    def __init__(self, num_layers=2, batch_size=2, seq_len=8, hidden_dim=4, num_heads=2):
        self.layers = []
        head_dim = hidden_dim // num_heads
        for _ in range(num_layers):
            layer_cache = type('LayerCache', (), {
                'k_cache': torch.randn(batch_size, num_heads, seq_len, head_dim),
                'v_cache': torch.randn(batch_size, num_heads, seq_len, head_dim)
            })()
            self.layers.append(layer_cache)


INIT_ARGS = {}

ARGS = {
    'module': MockAttentionModule(hidden_dim=4, num_heads=2),
    'hidden_states': torch.randn(2, 3, 4),
    'keys': torch.randn(2, 2, 8, 2),
    'values': torch.randn(2, 2, 8, 2),
    'attentions': torch.randn(2, 2, 3, 8),
    'kwargs': {
        'hidden_states': torch.randn(2, 3, 4),
        'past_key_values': MockCache(num_layers=2, batch_size=2, seq_len=8, hidden_dim=4, num_heads=2),
        'cache_position': torch.tensor([0, 1, 2]),
    }
}

METHOD = 'compress'

if __name__ == '__main__':
    press = BasePress()
    try:
        result = press.compress(**ARGS)
        print("compress() raised NotImplementedError as expected")
    except NotImplementedError as e:
        print(f"Expected error: {e}")
    
    module = ARGS['module']
    kwargs = ARGS['kwargs']
    output = [torch.randn(2, 3, 4), torch.randn(2, 2, 3, 8)]
    
    result = press.forward_hook(module, [], kwargs, output)
    print(f"forward_hook executed successfully, output shape: {result[0].shape}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 5, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
MetaData Ran
ran on a synthesized input · constructed an object; no result was computed
FFY0/DefensiveKV/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("346206adb8bf5312")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, MetaData: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from dataclasses import dataclass

torch.manual_seed(0)

@dataclass
class MetaData:
    decoding_cu_seqlens_q: torch.Tensor = None
    cu_seqlens_k: torch.Tensor = None
    max_seqlen_k: int = None
    cu_offset: torch.Tensor = None
    head_lens: torch.Tensor = None
    bsz: int = None
    num_key_value_heads: int = None

    def _update_metadata_while_compressing(self, head_lens, cu_seqlens_k, max_seqlen_k):
        self.head_lens = head_lens
        self.cu_seqlens_k = cu_seqlens_k
        self.max_seqlen_k = max_seqlen_k

    def _update_metadata_remove_n(self, n):
        self.max_seqlen_k -= n
        self.head_lens -= n
        self.cu_seqlens_k -= self.cu_offset * n

    def _update_metadata(self, key_states):
        bs, head, seqlen, dim = key_states.shape
        self.max_seqlen_k += seqlen
        self.cu_seqlens_k += self.cu_offset * seqlen
        self.head_lens += seqlen

    def _init_metadata(self, key_states):
        bsz, num_key_value_heads, k_len, head_dim = key_states.shape
        k_lens = bsz * num_key_value_heads * [k_len]
        _device = key_states.device
        max_seqlen_k = max(k_lens)
        head_seqlens_k = torch.tensor(k_lens, dtype=torch.int32, device=_device)
        cu_seqlens = torch.cumsum(head_seqlens_k, dim=0, dtype=torch.int32)
        cu_seqlens_k = torch.cat([torch.tensor([0], dtype=torch.int32, device=_device), cu_seqlens], dim=0)
        decoding_q_lens = bsz * num_key_value_heads * [1]
        decoding_head_seqlens_q = torch.tensor(decoding_q_lens, dtype=torch.int32, device=_device)
        decoding_cu_seqlens_q = torch.cumsum(decoding_head_seqlens_q, dim=0, dtype=torch.int32)
        decoding_cu_seqlens_q = torch.cat([torch.tensor([0], dtype=torch.int32, device=_device), decoding_cu_seqlens_q], dim=0)
        cu_offset = torch.arange(0, bsz * num_key_value_heads + 1, dtype=torch.int32, device=_device)
        self.decoding_cu_seqlens_q = decoding_cu_seqlens_q
        self.cu_seqlens_k = cu_seqlens_k
        self.max_seqlen_k = max_seqlen_k
        self.cu_offset = cu_offset
        self.head_lens = head_seqlens_k
        self.bsz = bsz
        self.num_key_value_heads = num_key_value_heads

# Create sample key_states for initialization
bsz, num_key_value_heads, k_len, head_dim = 2, 3, 4, 8
key_states = torch.randn(bsz, num_key_value_heads, k_len, head_dim, dtype=torch.float32)

# Create a MetaData instance and initialize it
metadata = MetaData()
metadata._init_metadata(key_states)

ARGS = {
    "decoding_cu_seqlens_q": metadata.decoding_cu_seqlens_q,
    "cu_seqlens_k": metadata.cu_seqlens_k,
    "max_seqlen_k": metadata.max_seqlen_k,
    "cu_offset": metadata.cu_offset,
    "head_lens": metadata.head_lens,
    "bsz": metadata.bsz,
    "num_key_value_heads": metadata.num_key_value_heads,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type MetaData — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a MetaData output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
get_prerope_query_states Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
FFY0/DefensiveKV/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("24eafaba79154752")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 4, dtype family float, shape (2, 2, 3, 2) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from torch import nn

torch.manual_seed(0)

# Create a minimal config class
class MinimalConfig:
    def __init__(self, num_attention_heads=2):
        self.num_attention_heads = num_attention_heads

# Create a minimal Phi3Attention-like module
class MinimalPhi3Attention(nn.Module):
    def __init__(self, hidden_dim=4, num_heads=2, head_dim=2):
        super().__init__()
        self.config = MinimalConfig(num_attention_heads=num_heads)
        self.head_dim = head_dim
        self.qkv_proj = nn.Linear(hidden_dim, num_heads * head_dim * 3)
    
    def forward(self, hidden_states):
        return self.qkv_proj(hidden_states)

# Create a minimal Qwen3Attention-like module
class MinimalQwen3Attention(nn.Module):
    def __init__(self, hidden_dim=4, num_heads=2, head_dim=2):
        super().__init__()
        self.config = MinimalConfig(num_attention_heads=num_heads)
        self.head_dim = head_dim
        self.q_proj = nn.Linear(hidden_dim, num_heads * head_dim)
        self.q_norm = nn.LayerNorm(head_dim)
    
    def forward(self, hidden_states):
        return self.q_proj(hidden_states)

# Create a minimal Llama-like attention module
class MinimalLlamaAttention(nn.Module):
    def __init__(self, hidden_dim=4, num_heads=2, head_dim=2):
        super().__init__()
        self.config = MinimalConfig(num_attention_heads=num_heads)
        self.head_dim = head_dim
        self.q_proj = nn.Linear(hidden_dim, num_heads * head_dim)
    
    def forward(self, hidden_states):
        return self.q_proj(hidden_states)

# Create test hidden states
batch_size = 2
seq_len = 3
hidden_dim = 4
num_heads = 2
head_dim = 2

hidden_states = torch.randn(batch_size, seq_len, hidden_dim)

# Test with Llama-like attention (has q_proj but not Phi3Attention)
module = MinimalLlamaAttention(hidden_dim=hidden_dim, num_heads=num_heads, head_dim=head_dim)

ARGS = {
    "module": module,
    "hidden_states": hidden_states,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 4, dtype family float, shape (2, 2, 3, 2) — shape (2, 2, 3, 2) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
BasePress Not yet run
unverified (harvested, no recorded run)
FFY0/DefensiveKV/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("7d325a6d956c95ae")
How it ran

no invocation recorded.

BasePress Not yet run
unverified (harvested, no recorded run)
NVIDIA/kvpress/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("1bb41fbe40f0cb94")
How it ran

no invocation recorded.

CriticalKVPress Not yet run
unverified (harvested, no recorded run)
FFY0/DefensiveKV/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("bbb411fe894a3c42")
How it ran

no invocation recorded.

CriticalKVPress Not yet run
unverified (harvested, no recorded run)
NVIDIA/kvpress/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("05f4c9404e12f85a")
How it ran

no invocation recorded.

ExpectedAttentionPress Not yet run
unverified (harvested, no recorded run)
FFY0/DefensiveKV/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("77ac43dd592848b4")
How it ran

no invocation recorded.

ScorerPress Not yet run
unverified (harvested, no recorded run)
FFY0/DefensiveKV/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("02fb35ba14327c55")
How it ran

no invocation recorded.

ScorerPress Not yet run
unverified (harvested, no recorded run)
NVIDIA/kvpress/kvpress/presses/criticalkv_press.py
code served (permissive licence) · get_code("bc245f692797739a")
How it ran

no invocation recorded.

Also present in other papers' code

Of 11 samples lifted from this paper's linked repositories, 11 carry a function identity and 0 do not. Of the 11 distinct functions with an identity, 2 are also present in other papers whose code we hold (2 with at least one paper dated earlier, 0 the same month, 2 later) and 9 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
BasePress
brick of this paper's assembly: helper
2 other papers
1 dated earlier, 1 later
2407.11550 (2024-07)
Ada-KV: Optimizing KV Cache Eviction by Adaptive Budget Allocation for Efficient LLM Inference
2608.19920 (2026-08)
Learning how to Forget: Fine-tuning for Long-Context Sparse Attention
ScorerPress
brick of this paper's assembly: helper
2 other papers
1 dated earlier, 1 later
2407.11550 (2024-07)
Ada-KV: Optimizing KV Cache Eviction by Adaptive Budget Allocation for Efficient LLM Inference
2608.19920 (2026-08)
Learning how to Forget: Fine-tuning for Long-Context Sparse Attention

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Large language models have revolutionized natural language processing but face significant challenges of high storage and runtime costs, due to the transformer architecture's reliance on selfattention, particularly the large KV cache for longsequence inference. Recent efforts to reduce KV cache size by pruning less critical entries based on attention weights remain empirical and lack formal grounding. This paper presents a formal study on identifying critical KV cache entries by analyzing attention output perturbation. Our analysis reveals that, beyond attention weights, the value states within KV entries and pretrained parameter matrices are also crucial. Based on this, we propose a perturbation-constrained selection algorithm that optimizes the worst-case output perturbation to identify critical entries. We demonstrate that our algorithm is a universal, plug-and-play enhancement that incurs negligible computational overhead. When integrated with three state-of-theart cache eviction methods on three distinct LLMs, our algorithm significantly reduces the compression loss by more than half on average across 29 datasets from the Ruler and LongBench benchmarks. Further perturbation analysis, at both the head and layer levels, confirms the principles underlying our effectiveness. This work offers a new, formally grounded perspective to cache eviction , opening promising avenues for future research. The code is publicly available at https: //github.com/FFY0/DefensiveKV.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2502.03805")
get_code_for_paper("2502.03805")
have("2502.03805")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2502.03805.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2502.03805.svg)](https://syntology.ai/paper/2502.03805)

Connect an agent — have() is free.