SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2605.23200 · 2026

Adaptive Mass-Segmented KV Compression for Long-Form Reasoning

Xiaoyu Shen, Junzhe Yang

arXiv · PDF · Open in the Atlas

Code that ran

5 of 7 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; 0 honoured the contract we drafted, 0 violated it and 2 have no contract verdict; 3 failures of our instrument; 2 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/2605.23200.json · badge: /api/ran/2605.23200.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
EIT-NLP/AdaptiveMassSegment community
Papers with Code archive
5 ran · 2 no recorded run
FunctionStatusWhere it lives
ScorerPress Ran
ran on a synthesized input
EIT-NLP/AdaptiveMassSegment/kvpress/presses/adaptive_segment_head_press.py
code served (permissive licence) · get_code("47497fe6d3135214")
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 list. 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 torch import nn
from dataclasses import dataclass
from typing import Optional
from transformers import Cache, QuantizedCache

def extract_keys_and_values(cache, layer_idx):
    """Helper function to extract keys and values from cache"""
    cache_layer = cache.layers[layer_idx]
    if isinstance(cache, QuantizedCache):
        keys = cache_layer._dequantize(cache_layer._quantized_keys)
        values = cache_layer._dequantize(cache_layer._quantized_values)
    else:
        keys = cache_layer.keys
        values = cache_layer.values
    return keys, values

@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['hidden_states']
        cache = kwargs['past_key_values']
        cache_layer = cache.layers[module.layer_idx]
        q_len = hidden_states.shape[1]
        if kwargs['cache_position'][-1] > q_len:
            return output
        keys, values = extract_keys_and_values(cache, module.layer_idx)
        keys, values = self.compress(module, hidden_states, keys, values, output[1], kwargs)
        if isinstance(cache, QuantizedCache):
            cache_layer._quantized_keys = cache_layer._quantize(keys, axis=cache_layer.axis_key)
            cache_layer._quantized_values = cache_layer._quantize(values, axis=cache_layer.axis_value)
        else:
            cache_layer.keys = keys
            cache_layer.values = values
        return output


class SimplePress(BasePress):
    """Simple concrete implementation for testing"""
    
    def compress(self, module: nn.Module, hidden_states: torch.Tensor, keys: torch.Tensor, values: torch.Tensor, attentions: torch.Tensor, kwargs: dict) -> tuple:
        """Simple compression that keeps first 50% of sequence"""
        seq_len = keys.shape[2]
        keep_len = max(1, seq_len // 2)
        compressed_keys = keys[:, :, :keep_len, :]
        compressed_values = values[:, :, :keep_len, :]
        return compressed_keys, compressed_values


class MockAttentionModule(nn.Module):
    """Mock attention module for testing"""
    def __init__(self, layer_idx=0):
        super().__init__()
        self.layer_idx = layer_idx
        self.linear = nn.Linear(4, 4)
    
    def forward(self, hidden_states, past_key_values=None, cache_position=None, **kwargs):
        output = self.linear(hidden_states)
        attentions = torch.randn(2, 2, 3, 3)
        return output, attentions


class MockCacheLayer:
    """Mock cache layer"""
    def __init__(self):
        self.keys = torch.randn(2, 2, 3, 2)
        self.values = torch.randn(2, 2, 3, 2)
        self.axis_key = 2
        self.axis_value = 2
    
    def _quantize(self, tensor, axis=None):
        return tensor
    
    def _dequantize(self, tensor):
        return tensor


class MockCache:
    """Mock cache object"""
    def __init__(self, num_layers=2):
        self.layers = [MockCacheLayer() for _ in range(num_layers)]


INIT_ARGS = {}

ARGS = {
    'module': MockAttentionModule(layer_idx=0),
    'input': [torch.randn(2, 3, 4)],
    'kwargs': {
        'hidden_states': torch.randn(2, 3, 4),
        'past_key_values': MockCache(num_layers=2),
        'cache_position': torch.tensor([0, 1, 2]),
        'position_embeddings': None,
    },
    'output': [torch.randn(2, 3, 4), torch.randn(2, 2, 3, 3)],
}

METHOD = 'forward_hook'

if __name__ == '__main__':
    press = SimplePress(**INIT_ARGS)
    result = press.forward_hook(**ARGS)
    print("Test passed!")
    print(f"Result type: {type(result)}")
    print(f"Result length: {len(result)}")
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 list — a list 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)
SnapKVPress Ran
ran on a synthesized input
EIT-NLP/AdaptiveMassSegment/kvpress/presses/adaptive_segment_head_press.py
code served (permissive licence) · get_code("7743f93621eb7a4a")
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 dataclasses import dataclass
from typing import Optional

@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[torch.Tensor, torch.Tensor]:
        """
        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[torch.Tensor], 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')
        cache_position = kwargs.get('cache_position')
        
        if hidden_states is None or cache is None or cache_position is None:
            return output
        
        q_len = hidden_states.shape[1]
        if cache_position[-1] > q_len:
            return output
        
        return output


INIT_ARGS = {}

ARGS = {
    'module': nn.Linear(4, 4),
    'hidden_states': torch.randn(2, 3, 4),
    'keys': torch.randn(2, 2, 3, 4),
    'values': torch.randn(2, 2, 3, 4),
    'attentions': torch.randn(2, 2, 3, 3),
    'kwargs': {
        'hidden_states': torch.randn(2, 3, 4),
        'past_key_values': None,
        'cache_position': torch.tensor([0, 1, 2])
    }
}

METHOD = 'compress'

if __name__ == '__main__':
    press = BasePress(**INIT_ARGS)
    
    try:
        result = getattr(press, METHOD)(**ARGS)
        print(f"Method {METHOD} called successfully")
        print(f"Result type: {type(result)}")
    except NotImplementedError as e:
        print(f"Expected NotImplementedError: {e}")
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)
dequantize_layer Ran
ran; our contract draft was wrong, not the code
EIT-NLP/AdaptiveMassSegment/kvpress/presses/adaptive_segment_head_press.py
code served (permissive licence) · get_code("9d90fef264047280")
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 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

torch.manual_seed(0)

class MockQuantizedCache(nn.Module):
    def __init__(self):
        super().__init__()
        self._quantized_keys = torch.randint(0, 256, (2, 4), dtype=torch.uint8)
        self._quantized_values = torch.randint(0, 256, (2, 3), dtype=torch.uint8)
    
    def _dequantize(self, quantized_tensor):
        # Simple dequantization: convert to float and scale
        return quantized_tensor.float() / 255.0

cache_layer = MockQuantizedCache()

ARGS = {
    "cache_layer": cache_layer
}
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 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: none by the harness; any seed is in the setup block
extract_keys_and_values Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
EIT-NLP/AdaptiveMassSegment/kvpress/presses/adaptive_segment_head_press.py
code served (permissive licence) · get_code("cf7068666062b2b6")
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 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
from transformers import Cache, QuantizedCache

torch.manual_seed(0)

# Create a mock cache layer for unquantized cache
class MockCacheLayer:
    def __init__(self, keys, values):
        self.keys = keys
        self.values = values

# Create a mock unquantized cache
class MockCache(Cache):
    def __init__(self, layers):
        self.layers = layers
    
    def update(self, key_states, value_states, layer_idx, cache_config=None):
        pass

# Create a mock quantized cache layer with dequantize method
class MockQuantizedCacheLayer:
    def __init__(self, keys, values):
        self._quantized_keys = keys
        self._quantized_values = values
    
    def _dequantize(self, quantized_tensor):
        return quantized_tensor.float()

# Create a mock quantized cache
class MockQuantizedCache(QuantizedCache):
    def __init__(self, layers):
        self.layers = layers
    
    def update(self, key_states, value_states, layer_idx, cache_config=None):
        pass

# Build tiny tensors for keys and values
# batch_size=2, seq_len=3, num_heads=4, head_dim=5
keys_tensor = torch.randn(2, 4, 3, 5, dtype=torch.float32)
values_tensor = torch.randn(2, 4, 3, 5, dtype=torch.float32)

# Create unquantized cache
unquantized_layer = MockCacheLayer(keys_tensor, values_tensor)
unquantized_cache = MockCache([unquantized_layer])

ARGS = {
    "cache": unquantized_cache,
    "layer_idx": 0,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
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: 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)
EIT-NLP/AdaptiveMassSegment/kvpress/presses/adaptive_segment_head_press.py
code served (permissive licence) · get_code("ebf221129de571e8")
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 Tensor, ndim 4, dtype family float, shape (2, 2, 3, 8) 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 minimal config class
class MinimalConfig:
    def __init__(self, num_attention_heads):
        self.num_attention_heads = num_attention_heads

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

# Create a minimal Llama-like attention module (with q_proj)
class MinimalLlamaAttention(nn.Module):
    def __init__(self, hidden_dim=16, num_heads=2, head_dim=8):
        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 a minimal Qwen3Attention-like module (with q_proj and q_norm)
class MinimalQwen3Attention(nn.Module):
    def __init__(self, hidden_dim=16, num_heads=2, head_dim=8):
        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 test hidden states: (batch_size=2, seq_len=3, hidden_dim=16)
hidden_states = torch.randn(2, 3, 16)

# Create module instance (using Llama-like attention)
module = MinimalLlamaAttention(hidden_dim=16, num_heads=2, head_dim=8)

ARGS = {
    "module": module,
    "hidden_states": hidden_states,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
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, 8) — shape (2, 2, 3, 8) 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
AdaptiveMassSegmentWrapperHeadPress Not yet run
unverified (harvested, no recorded run)
EIT-NLP/AdaptiveMassSegment/kvpress/presses/adaptive_segment_head_press.py
code served (permissive licence) · get_code("d32b135a5c0ea95c")
How it ran

no invocation recorded.

BasePress Not yet run
unverified (harvested, no recorded run)
EIT-NLP/AdaptiveMassSegment/kvpress/presses/adaptive_segment_head_press.py
code served (permissive licence) · get_code("b38326bf91935776")
How it ran

no invocation recorded.

Also present in other papers' code

Of 7 samples lifted from this paper's linked repositories, 7 carry a function identity and 0 do not. Of the 7 distinct functions with an identity, 3 are also present in other papers whose code we hold (3 with at least one paper dated earlier, 0 the same month, 2 later) and 4 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
dequantize_layer
brick of this paper's assembly: helper
3 other papers
2 dated earlier, 1 later · 3 only as an assembly brick
2407.11550 (2024-07)
Ada-KV: Optimizing KV Cache Eviction by Adaptive Budget Allocation for Efficient LLM Inference
2502.03805 (2025-02)
CriticalKV: Optimizing KV Cache Eviction from an Output Perturbation Perspective
2608.19920 (2026-08)
Learning how to Forget: Fine-tuning for Long-Context Sparse Attention
extract_keys_and_values
brick of this paper's assembly: helper
3 other papers
2 dated earlier, 1 later · 2 only as an assembly brick
2407.11550 (2024-07)
Ada-KV: Optimizing KV Cache Eviction by Adaptive Budget Allocation for Efficient LLM Inference
2502.03805 (2025-02)
CriticalKV: Optimizing KV Cache Eviction from an Output Perturbation Perspective
2608.19920 (2026-08)
Learning how to Forget: Fine-tuning for Long-Context Sparse Attention
get_prerope_query_states
brick of this paper's assembly: helper
2 other papers
2 dated earlier · 2 only as an assembly brick
2502.03805 (2025-02)
CriticalKV: Optimizing KV Cache Eviction from an Output Perturbation Perspective
2510.07651 (2025-10)
OBCache: Optimal Brain KV Cache Pruning for Efficient Long-Context LLM Inference

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

The linear growth of the Key-Value (KV) cache is a critical bottleneck in longform LLM inference. Existing KV compression methods mitigate this by evicting tokens based on importance scores. However, we show that their reliance on global Top-k selection triggers Region Wipe-out: the severe eviction of contiguous reasoning blocks that derails logical coherence. To address this, we propose Adaptive Mass-Segmented (AMS) KV Compression, a framework that shifts the paradigm from token-level competition to region-aware quota allocation. AMS adaptively partitions the KV cache based on the spatial distribution of attention mass, ensuring structurally vital reasoning segments receive guaranteed memory quotas. To ensure stability during iterative decoding, an EMA-based smoothing mechanism is incorporated to prevent jitter in segment boundaries. Crucially, AMS is a universal plug-and-play layer that is orthogonal to existing scorers. It can be seamlessly integrated into representative methods such as TOVA, Expected Attention, KeyDiff, R-KV and TriAttention. AMS is also system-compatible with modern paged-KV serving frameworks such as vLLM, supporting efficient gather-and-compact KV execution without introducing additional steady-state attention overhead. Extensive experiments across a diverse suite of tasks, including mathematical reasoning (MATH500, AIME, GSM8K), code completion, opendomain QA, and sparse retrieval, demonstrate that AMS consistently mitigates structural fragmentation and boosts model performance. Code is available at: https://github.com/EIT-NLP/AdaptiveMassSegment

For agents

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

get_harvested_code_for_paper("2605.23200")
get_code_for_paper("2605.23200")
have("2605.23200")

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

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

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

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

Connect an agent — have() is free.