SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2601.17367 · ICML · 2026

Elastic Attention: Test-time Adaptive Sparsity Ratios for Efficient Transformers

Yi Yang, Juntao Li, Min Zhang, Zecheng Tang, Zhiyi Hong, Haiya Xiang, Kebin Liu, ! ! ∈ ℝ "×$ !, Quantong Qiu, Qingqing Dang

arXiv · PDF · Open in the Atlas

Code that ran

8 of 12 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 0 have no contract verdict; 7 failures of our instrument; 4 no recorded run); 1 of them was also run on the host, not in the jail, by the peer-agreement lane that set its level, measured 2026-11-22; 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/2601.17367.json · badge: /api/ran/2601.17367.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
LCM-Lab/Elastic-Attention canonical (classifier label)
classifier basis: census
8 ran · 4 no recorded run
FunctionStatusWhere it lives
repeat_kv Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
LCM-Lab/Elastic-Attention/elasticattn/src/model_utils.py
code served (permissive licence) · get_code("3c76e52815c5401d")
How it ran

Ran in Syntology's jail 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, 6, 5, 4) as a later run recorded it. The image it ran in was not recorded. The comparison behind this sample's level is a different run: the peer-agreement lane ran it again on the host, not in the jail (report dated 2026-09-04T23:23:17Z). 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

torch.manual_seed(0)

# Create a small tensor with shape (batch, num_key_value_heads, seqlen, head_dim)
# Using distinct sizes: batch=2, num_key_value_heads=3, seqlen=5, head_dim=4
hidden_states = torch.randn(2, 3, 5, 4)

# n_rep is the repetition factor
n_rep = 2

ARGS = {
    "hidden_states": hidden_states,
    "n_rep": n_rep,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — 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, 6, 5, 4) — shape (2, 6, 5, 4) 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
apply_rotary_pos_emb Ran
ran; our contract draft was wrong, not the code
LCM-Lab/Elastic-Attention/elasticattn/src/model_utils.py
code served (permissive licence) · get_code("583539efd6fd01fb")
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 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

torch.manual_seed(0)

# Create small tensors for query and key
# Shape: [batch_size, heads, seq_len, head_dim]
batch_size = 2
heads = 3
seq_len = 4
head_dim = 8

q = torch.randn(batch_size, heads, seq_len, head_dim)
k = torch.randn(batch_size, heads, seq_len, head_dim)

# Create cos and sin tensors
# Shape: [batch_size, seq_len, head_dim]
cos = torch.randn(batch_size, seq_len, head_dim)
sin = torch.randn(batch_size, seq_len, head_dim)

# position_ids is optional and unused according to docstring
position_ids = None

# unsqueeze_dim defaults to 1, but we can specify it
unsqueeze_dim = 1

ARGS = {
    "q": q,
    "k": k,
    "cos": cos,
    "sin": sin,
    "position_ids": position_ids,
    "unsqueeze_dim": unsqueeze_dim,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — 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
create_causal_mask Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
LCM-Lab/Elastic-Attention/elasticattn/src/utils.py
code served (permissive licence) · get_code("4b4f5a76f5aeef0e")
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, 3, 4, 20) as a later run recorded it. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is 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

torch.manual_seed(0)

ARGS = {
    "batch_size": 2,
    "head_num": 3,
    "block_size": 4,
    "block_num": 5,
    "divide_block_num": 2,
}
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 Tensor, ndim 4, dtype family float, shape (2, 3, 4, 20) — shape (2, 3, 4, 20) 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
deterministic_z_from_log_alpha Ran
ran; our contract draft was wrong, not the code
LCM-Lab/Elastic-Attention/elasticattn/training/attention_mask.py
code served (permissive licence) · get_code("410c0139054f9f9c")
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 2, dtype family float, shape (2, 4) 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
import numpy as np

torch.manual_seed(0)

# Construct log_alpha tensor - small 2D tensor
# The function uses: .shape, .device, reshaping, torch operations
log_alpha = torch.randn(2, 4, requires_grad=False)

# Construct apply_one parameter - boolean flag
apply_one = False

# Define ARGS dict with all parameters
ARGS = {
    "log_alpha": log_alpha,
    "apply_one": apply_one,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family float, shape (2, 4) — shape (2, 4) 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
generate_streaming_info_blocksparse_flash_attn Ran
ran, honoured the contract we drafted
LCM-Lab/Elastic-Attention/elasticattn/training/eval/modeling_flash_qwen.py
code served (permissive licence) · get_code("13f436e0309e6fd0")
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 1, dtype family int, shape (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

torch.manual_seed(0)

ARGS = {
    "sink_block_num": 2,
    "local_block_num": 3,
    "n_query_heads": 4,
    "device": "cpu"
}
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 Tensor, ndim 1, dtype family int, shape (8,) — shape (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
rotate_half Ran
ran; our contract draft was wrong, not the code
LCM-Lab/Elastic-Attention/elasticattn/src/model_utils.py
code served (permissive licence) · get_code("e03d53ba9d4f9ae5")
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 2, dtype family float, shape (2, 4) 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

torch.manual_seed(0)

# The function takes a single parameter 'x' which is a tensor
# It accesses x[..., :x.shape[-1] // 2] and x[..., x.shape[-1] // 2:]
# So x needs to be a tensor with a last dimension that can be split in half
# Let's create a small tensor with batch size 2 and feature dimension 4

x = torch.randn(2, 4)

ARGS = {
    "x": x
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 2, dtype family float, shape (2, 4) — shape (2, 4) 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
sample_z_from_u Ran
ran; our contract draft was wrong, not the code
LCM-Lab/Elastic-Attention/elasticattn/training/attention_mask.py
code served (permissive licence) · get_code("07ce21c57ca66278")
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 2, dtype family float, shape (2, 4) 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

torch.manual_seed(0)

# Create small tensors for u and log_alpha
# u should be in (0, 1) for the sigmoid computation to work properly
u = torch.rand(2, 4)  # batch size 2, dim 4, values in [0, 1)
u = torch.clamp(u, min=1e-7, max=1-1e-7)  # avoid exact 0 or 1

log_alpha = torch.randn(2, 4)  # batch size 2, dim 4

ARGS = {
    "u": u,
    "log_alpha": log_alpha,
}
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 Tensor, ndim 2, dtype family float, shape (2, 4) — shape (2, 4) 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
worker_pack_chunk Ran
ran; our contract draft was wrong, not the code
LCM-Lab/Elastic-Attention/elasticattn/training/dataset_packing.py
code served (permissive licence) · get_code("4476c5672f1aafdf")
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 list, ndim 1, 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
import numpy as np
from unittest.mock import Mock

# Create a mock tokenizer that behaves like a HuggingFace tokenizer
class MockTokenizer:
    def __init__(self):
        self.eos_token_id = 2
        self.pad_token_id = 0
    
    def __call__(self, text, add_special_tokens=False):
        # Simple mock: return a reasonable number of token IDs based on text length
        token_count = max(1, len(text.split()) + 5)
        return {'input_ids': list(range(token_count))}
    
    def apply_chat_template(self, messages, tokenize=False, enable_thinking=False):
        # Concatenate message contents with role labels
        result = ""
        for msg in messages:
            role = msg['role']
            content = msg['content']
            result += f"[{role}]: {content}\n"
        return result

# Create mock dataset with diverse items
chunk_dataset = [
    {
        'context': 'The Earth orbits the Sun.',
        'question': 'What does the Earth orbit?',
        'answer': 'The Earth orbits the Sun.',
        'metadata': {'task': 'Single QA', 'is_prefix': True}
    },
    {
        'context': 'Paris is the capital of France. France is in Europe.',
        'question': 'What continent is France in?',
        'answer': 'Europe',
        'metadata': {'task': 'MultiHop QA', 'is_prefix': True}
    },
    {
        'context': 'Breaking News: Stock market reaches all-time high.',
        'question': '',
        'answer': 'The stock market has reached an all-time high today.',
        'metadata': {'task': 'Summarization', 'is_prefix': False}
    },
    {
        'context': 'def hello():\n    print("world")',
        'question': 'Complete this function',
        'answer': 'def hello():\n    print("world")',
        'metadata': {'task': 'Code', 'is_prefix': True}
    },
    {
        'context': 'Example context',
        'question': 'Example question',
        'answer': 'Example answer',
        'metadata': {'task': 'In-Context Learning', 'is_prefix': True}
    },
]

tokenizer = MockTokenizer()
max_seq_len = 512
min_seq_len = 10
worker_id = 0
is_sft = True

ARGS = {
    'chunk_dataset': chunk_dataset,
    'tokenizer': tokenizer,
    'max_seq_len': max_seq_len,
    'min_seq_len': min_seq_len,
    'worker_id': worker_id,
    'is_sft': is_sft
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch, tqdm — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 1, dtype family float — a list 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
apply_rotary_emb_torch Not yet run
unverified (harvested, no recorded run)
LCM-Lab/Elastic-Attention/elasticattn/training/modeling_flash_qwen.py
code served (permissive licence) · get_code("2ed34e7143f94ce9")
How it ran

no invocation recorded.

cdf_stretched_concrete Not yet run
unverified (harvested, no recorded run)
LCM-Lab/Elastic-Attention/elasticattn/training/attention_mask.py
code served (permissive licence) · get_code("412fcbe6527509d8")
How it ran

no invocation recorded.

find_blocks_chunked Not yet run
unverified (harvested, no recorded run)
LCM-Lab/Elastic-Attention/elasticattn/src/utils.py
code served (permissive licence) · get_code("1872408025927f3f")
How it ran

no invocation recorded.

get_mask Not yet run
unverified (harvested, no recorded run)
LCM-Lab/Elastic-Attention/elasticattn/training/modeling_flash_qwen.py
code served (permissive licence) · get_code("3fb9135f1581e90e")
How it ran

no invocation recorded.

Also present in other papers' code

Of 12 samples lifted from this paper's linked repositories, 12 carry a function identity and 0 do not. Of the 12 distinct functions with an identity, 9 are also present in other papers whose code we hold (7 with at least one paper dated earlier, 3 the same month, 8 later) and 3 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
rotate_half 360 other papers
316 dated earlier, 7 the same month, 34 later, 3 undated · 30 only as an assembly brick
1901.02860 (2019-01)
Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
2203.08913 (2022-03)
Memorizing Transformers
2302.13971 (2023-02)
LLaMA: Open and Efficient Foundation Language Models
and 357 more not named here
repeat_kv 243 other papers
215 dated earlier, 6 the same month, 20 later, 2 undated · 22 only as an assembly brick
1901.02860 (2019-01)
Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
2203.08913 (2022-03)
Memorizing Transformers
2305.17888 (2023-05)
LLM-QAT: Data-Free Quantization Aware Training for Large Language Models
and 240 more not named here
apply_rotary_pos_emb 94 other papers
78 dated earlier, 3 the same month, 10 later, 3 undated · 6 only as an assembly brick
1901.02860 (2019-01)
Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
2305.17888 (2023-05)
LLM-QAT: Data-Free Quantization Aware Training for Large Language Models
2309.11674 (2023-09)
A Paradigm Shift in Machine Translation: Boosting Translation Performance of Large Language Models
and 91 more not named here
apply_rotary_emb_torch 6 other papers
3 dated earlier, 3 later
2309.06180 (2023-09)
Efficient Memory Management for Large Language Model Serving with PagedAttention
2407.08608 (2024-07)
FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision
2412.06464 (2024-12)
Gated Delta Networks: Improving Mamba2 with Delta Rule
and 3 more not named here
create_causal_mask 2 other papers
1 dated earlier, 1 later
2509.24745 (2025-09)
ProxyAttn: Guided Sparse Attention via Representative Heads
2604.07394 (2026-04)
Flux Attention: Context-Aware Hybrid Attention for Efficient LLMs Inference
find_blocks_chunked 2 other papers
1 dated earlier, 1 later
2509.24745 (2025-09)
ProxyAttn: Guided Sparse Attention via Representative Heads
2604.07394 (2026-04)
Flux Attention: Context-Aware Hybrid Attention for Efficient LLMs Inference
generate_streaming_info_blocksparse_flash_attn 1 other paper
1 later
2604.07394 (2026-04)
Flux Attention: Context-Aware Hybrid Attention for Efficient LLMs Inference
sample_z_from_u 1 other paper
1 dated earlier
2403.03942 (2024-03)
The Heuristic Core: Understanding Subnetwork Generalization in Pretrained Language Models
worker_pack_chunk 1 other paper
1 later
2604.07394 (2026-04)
Flux Attention: Context-Aware Hybrid Attention for Efficient LLMs 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-22.

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 quadratic complexity of standard attention mechanisms poses a significant scalability bottleneck for large language models (LLMs) in longcontext scenarios. While hybrid attention strategies that combine sparse and full attention within a single model offer a viable solution, they typically employ static computation ratios (i.e., fixed proportions of sparse versus full attention) and fail to adapt to the varying sparsity sensitivities of downstream tasks during inference. To address this issue, we propose Elastic Attention, which allows the model to dynamically adjust its overall sparsity based on the input. This is achieved by integrating a lightweight Attention Router into the existing pretrained model, which dynamically assigns each attention head to different computation modes. Within only 12 hours of training on 8×A800 GPUs, our method enables models to achieve both strong performance and efficient inference (see Figure 1). Experiments across three long-context benchmarks on widely-used LLMs demonstrate the superiority of our method.

For agents

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

get_harvested_code_for_paper("2601.17367")
get_code_for_paper("2601.17367")
have("2601.17367")

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

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

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

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

Connect an agent — have() is free.