SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2510.07651 · ICML · 2025

OBCache: Optimal Brain KV Cache Pruning for Efficient Long-Context LLM Inference

Enmao Diao, Jiaojiao Zhao, Yuzhe Gu, Xiyu Liang

arXiv · PDF · Open in the Atlas

Code that ran

2 of 6 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 1 honoured the contract we drafted, 0 violated it and 1 has no contract verdict; 0 failures of our instrument; 4 no recorded run), measured 2026-11-23; 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/2510.07651.json · badge: /api/ran/2510.07651.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
DreamSoul-AI/OBCache community
Papers with Code archive
2 ran · 4 no recorded run
FunctionStatusWhere it lives
OBCacheScoringMixin Ran
ran on a synthesized input
DreamSoul-AI/OBCache/kvpress/presses/obcache_press.py
code served (permissive licence) · get_code("840c387847cebae6")
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. 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
import torch.nn as nn
from torch.nn import functional as F
import math

# Mock the imports that would come from transformers
class MockConfig:
    def __init__(self, num_attention_heads=2, num_key_value_heads=2, hidden_size=64):
        self.num_attention_heads = num_attention_heads
        self.num_key_value_heads = num_key_value_heads
        self.hidden_size = hidden_size

class MockAttentionModule(nn.Module):
    def __init__(self, hidden_size=64, num_heads=2, num_key_value_heads=2, head_dim=32):
        super().__init__()
        self.config = MockConfig(num_attention_heads=num_heads, num_key_value_heads=num_key_value_heads, hidden_size=hidden_size)
        self.head_dim = head_dim
        self.q_proj = nn.Linear(hidden_size, num_heads * head_dim)
        self.k_proj = nn.Linear(hidden_size, num_key_value_heads * head_dim)
        self.v_proj = nn.Linear(hidden_size, num_key_value_heads * head_dim)

def repeat_kv(x, num_key_value_groups):
    batch, num_kv_heads, seq_len, head_dim = x.shape
    if num_key_value_groups == 1:
        return x
    x = x[:, :, None, :, :].expand(batch, num_kv_heads, num_key_value_groups, seq_len, head_dim)
    return x.reshape(batch, num_kv_heads * num_key_value_groups, seq_len, head_dim)

def rotate_half(x):
    x1 = x[..., : x.shape[-1] // 2]
    x2 = x[..., x.shape[-1] // 2 :]
    return torch.cat((-x2, x1), dim=-1)

def get_kernel_launch_config(num_positions: int, head_dim: int) -> tuple:
    block_p = 128 if num_positions < 2048 else 256
    block_d = 64 if head_dim == 128 else 32
    return (block_p, block_d)

def get_prerope_query_states(module: nn.Module, hidden_states: torch.Tensor) -> torch.Tensor:
    bsz, q_len, _ = hidden_states.shape
    num_heads = module.config.num_attention_heads
    head_dim = module.head_dim
    
    if hasattr(module, 'q_proj'):
        query_states = module.q_proj(hidden_states)
    else:
        raise NotImplementedError(f'Not implemented for {module.__class__}.')
    
    query_states = query_states.view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
    return query_states

class OBCacheScoringMixin:
    pruning_score: str
    use_triton: bool
    gqa_aggregation: str
    kernel_size: int

    @staticmethod
    def compute_causal_attention(
        module: nn.Module,
        hidden_states: torch.Tensor,
        keys: torch.Tensor,
        position_embeddings: tuple,
        query_start: int = 0
    ) -> tuple:
        _, _, key_length, _ = keys.shape
        query_states = get_prerope_query_states(module, hidden_states[:, query_start:])
        query_length = query_states.shape[2]
        num_heads = module.config.num_attention_heads
        num_key_value_groups = num_heads // module.config.num_key_value_heads
        
        cos, sin = position_embeddings
        cos = cos[:, query_start:query_start + query_length]
        sin = sin[:, query_start:query_start + query_length]
        
        query_states = query_states * cos.unsqueeze(1) + rotate_half(query_states) * sin.unsqueeze(1)
        key_states = repeat_kv(keys, num_key_value_groups)
        
        logits = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(module.head_dim)
        
        return logits, query_states

INIT_ARGS = {}

ARGS = {
    'module': MockAttentionModule(hidden_size=64, num_heads=2, num_key_value_heads=2, head_dim=32),
    'hidden_states': torch.randn(2, 5, 64),
    'keys': torch.randn(2, 2, 7, 32),
    'position_embeddings': (torch.randn(1, 5, 32), torch.randn(1, 5, 32)),
    'query_start': 0
}

METHOD = 'compute_causal_attention'

if __name__ == '__main__':
    result = OBCacheScoringMixin.compute_causal_attention(**ARGS)
    print(f"Logits shape: {result[0].shape}")
    print(f"Query states shape: {result[1].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 — a tuple output has no array shape of its own; none is 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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
get_kernel_launch_config Ran
ran, honoured the contract we drafted
DreamSoul-AI/OBCache/kvpress/presses/obcache_press.py
code served (permissive licence) · get_code("775170539fb88bfc")
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 tuple, ndim 1, dtype family int; 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 numpy as np

torch.manual_seed(0)

ARGS = {
    "num_positions": 1024,
    "head_dim": 128,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family int — 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: none by the harness; any seed is in the setup block
require_triton Not yet run
unverified (harvested, no recorded run)
DreamSoul-AI/OBCache/kvpress/presses/obcache_press.py
code served (permissive licence) · get_code("8060223b0779a88d")
How it ran

no invocation recorded.

run_v_score_kernel Not yet run
unverified (harvested, no recorded run)
DreamSoul-AI/OBCache/kvpress/presses/obcache_press.py
code served (permissive licence) · get_code("8b5a42aedf1f3a36")
How it ran

no invocation recorded.

triton_is_available Not yet run
unverified (harvested, no recorded run)
DreamSoul-AI/OBCache/kvpress/presses/obcache_press.py
code served (permissive licence) · get_code("7060a9e82baa60a4")
How it ran

no invocation recorded.

triton_v_score Not yet run
unverified (harvested, no recorded run)
DreamSoul-AI/OBCache/kvpress/presses/obcache_press.py
code served (permissive licence) · get_code("953df5ec1a977dbc")
How it ran

no invocation recorded.

Also present in other papers' code

Of 6 samples lifted from this paper's linked repositories, 6 carry a function identity and 0 do not. Of the 6 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 6 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.

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 (LLMs) with extended context windows enable powerful applications but impose significant memory overhead, as caching all key-value (KV) states scales linearly with sequence length and batch size. Existing cache eviction methods address this by exploiting attention sparsity, yet they typically rank tokens heuristically using accumulated attention weights without considering their true impact on attention outputs. We propose Optimal Brain Cache (OBCache), a principled framework that formulates cache eviction as a layer-wise structured pruning problem. Building upon the Optimal Brain Damage (OBD) theory, OBCache quantifies token saliency by measuring the perturbation in attention outputs induced by pruning tokens, with closed-form scores derived for isolated keys, isolated values, and joint key-value pairs. Our scores account not only for attention weights but also for information from value states and attention outputs, thereby enhancing existing eviction strategies with output-aware signals. Experiments on LLaMA and Qwen models demonstrate that replacing the heuristic scores in existing works, which estimate token saliency across different query positions, with OBCache's output-aware scores consistently improves longcontext accuracy. Code is available at https:// github.com/DreamSoul-AI/OBCache.

For agents

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

get_harvested_code_for_paper("2510.07651")
get_code_for_paper("2510.07651")
have("2510.07651")

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

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

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

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

Connect an agent — have() is free.