SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2502.20766 · ICLR · 2025

FlexPrefill: A CONTEXT-AWARE SPARSE ATTENTION MECHANISM FOR EFFICIENT LONG-SEQUENCE IN-FERENCE

Xun Zhou, Jianqiao Lu, Xunhao Lai, Yao Luo, Yiyuan Ma

arXiv · PDF · Open in the Atlas

Code that ran

10 of 11 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 7 have no contract verdict; 2 failures of our instrument; 1 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.20766.json · badge: /api/ran/2502.20766.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
bytedance/FlexPrefill canonical (classifier label)
classifier basis not recorded on the link
9 ran · 1 no recorded run
ByteDance-Seed/FlexPrefill canonical (classifier label)
classifier basis: classifier_2025
1 ran · 0 no recorded run
FunctionStatusWhere it lives
apply_rotary_pos_emb Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
bytedance/FlexPrefill/flex_prefill/modules/glm/glm_self_attention_foward.py
code served (permissive licence) · get_code("059a805ecbeca6af")
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; 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)

# Analyze the function:
# - x: torch.Tensor with shape (b, np, sq, hn)
#   - Used as: x.size(0), x.size(1), x.size(2), x.size(3)
#   - Sliced: x[..., :rot_dim], x[..., rot_dim:]
#   - Reshaped to (b, np, sq, rot_dim // 2, 2)
# - rope_cache: torch.Tensor
#   - Used as: rope_cache.shape[-2], rope_cache[:, :sq]
#   - Viewed to (-1, 1, sq, xshaped.size(3), 2)
#   - Shape should be compatible with slicing and reshaping

# Determine dimensions:
# Let's use:
# b = 2 (batch size)
# np = 3 (num_heads)
# sq = 4 (sequence length)
# hn = 8 (hidden dim per head)
# rot_dim must be <= hn, and rot_dim = rope_cache.shape[-2] * 2
# So rope_cache.shape[-2] = rot_dim // 2 = 4 // 2 = 2
# rope_cache needs shape that allows [:, :sq] slicing and view(-1, 1, sq, 2, 2)
# rope_cache should have shape (some_dim, sq_or_more, rot_dim//2, 2)
# For simplicity: (1, sq, rot_dim//2, 2) = (1, 4, 2, 2)

b = 2
np = 3
sq = 4
hn = 8
rot_dim = 4

# x shape: (b, np, sq, hn) = (2, 3, 4, 8)
x = torch.randn(b, np, sq, hn)

# rope_cache shape needs to work with:
# rope_cache = rope_cache[:, :sq]  -> need at least 2 dimensions, second dim >= sq
# rope_cache.view(-1, 1, sq, xshaped.size(3), 2)
# where xshaped.size(3) = rot_dim // 2 = 2
# So rope_cache after slicing should have total elements = -1 * 1 * sq * 2 * 2
# If rope_cache is (B, T, rot_dim//2, 2), then after [:, :sq] it's (B, sq, rot_dim//2, 2)
# This has B * sq * 2 * 2 elements, which matches -1 * 1 * sq * 2 * 2 if B = 1
rope_cache = torch.randn(1, sq, rot_dim // 2, 2)

ARGS = {
    "x": x,
    "rope_cache": rope_cache
}
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 — no output shape is stated: observe_signature.py could not observe it (import:OSError)
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_config_example Ran
ran on a synthesized input
bytedance/FlexPrefill/flex_prefill/modules/patch.py
code served (permissive licence) · get_code("78e17a79809e571b")
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 dict. 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 copy

ATTENTION_CONFIG_EXAMPLE = {'default': {}, 'flash': {}, 'streaming_llm': {'global_window': 1024, 'local_window': 8192}, 'minfer': {'model_type': 'llama3.1'}, 'vertical_slash': {'block_size': 128, 'vertical_size': 8192, 'slash_size': 8192}, 'flex_prefill': {'block_size': 128, 'flex_prefill_gamma': 0.9, 'flex_prefill_tau': 0.1, 'flex_prefill_min_budget': 1024, 'flex_prefill_max_budget': None}}

def get_config_example(pattern: str=None):
    if pattern is None:
        return copy.deepcopy(ATTENTION_CONFIG_EXAMPLE)
    else:
        return copy.deepcopy(ATTENTION_CONFIG_EXAMPLE[pattern])

ARGS = {
    'pattern': 'flash'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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_dataloader Ran
ran on a synthesized input
bytedance/FlexPrefill/experiments/benchmark/run_ruler.py
code served (permissive licence) · get_code("6904e1292ef34ff1")
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 DataLoader. 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.utils.data import DataLoader, Dataset

torch.manual_seed(0)

class ListDataset(Dataset):

    def __init__(self, data_list):
        self.data_list = data_list

    def __len__(self):
        return len(self.data_list)

    def __getitem__(self, idx):
        return self.data_list[idx]

def get_dataloader(data_list):
    data_loader = DataLoader(ListDataset(data_list), batch_size=1, shuffle=False)
    return data_loader

# Create a small data list with tuples of (input, target)
data_list = [
    (torch.randn(4, 3), torch.tensor(0)),
    (torch.randn(4, 3), torch.tensor(1)),
]

ARGS = {
    "data_list": data_list,
}
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 DataLoader — a DataLoader output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a DataLoader 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_num_warps_stages Ran
ran, honoured the contract we drafted
ByteDance-Seed/FlexPrefill/flex_prefill/ops/flex_prefill_attention.py
code served (permissive licence) · get_code("c7bbee93a299753b")
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

torch.manual_seed(0)

# Analyze the function:
# - head_dim: int, used in comparisons (> 64, > 128)
# - block_size: int, used in comparisons (> 64)
# - gpu_name: str, used with .lower() and 'in' checks for 'h100', 'a100', '4090'

ARGS = {
    "head_dim": 128,
    "block_size": 128,
    "gpu_name": "H100"
}
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 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
get_tasks Ran
ran on a synthesized input
bytedance/FlexPrefill/experiments/benchmark/run_ruler.py
code served (permissive licence) · get_code("0ff1542f9a950e79")
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 2, 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

torch.manual_seed(0)

# The function get_tasks takes a single parameter: task_str (a string)
# Based on the function body, task_str is used in string operations:
# - equality check against 'ruler'
# - startswith check against 'ruler'
# - split operations on commas
# The function returns a list of tuples containing (task, length) pairs

# We'll test with different task_str values to cover the branches

ARGS = {
    'task_str': 'niah_single_1,4096'
}
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 list, ndim 2, 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
glm_mlp_forward Ran
ran on a synthesized input
bytedance/FlexPrefill/flex_prefill/modules/glm/glm_mlp_forward.py
code served (permissive licence) · get_code("5f120e3472fb5048")
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 3, dtype family float, shape (2, 3, 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 torch.nn as nn

torch.manual_seed(0)

class GLMMLP(nn.Module):
    def __init__(self, hidden_dim, intermediate_dim):
        super().__init__()
        self.dense_h_to_4h = nn.Linear(hidden_dim, intermediate_dim)
        self.dense_4h_to_h = nn.Linear(intermediate_dim, hidden_dim)
        self.activation_func = nn.GELU()
    
    def forward(self, hidden_states):
        def inner_mlp_forward(x):
            intermediate_parallel = self.dense_h_to_4h(x)
            intermediate_parallel = self.activation_func(intermediate_parallel)
            output = self.dense_4h_to_h(intermediate_parallel)
            return output
        batch_size, seq_len, hidden_dim = hidden_states.shape
        chunk_size = 32768
        output = torch.empty_like(hidden_states)
        for b in range(batch_size):
            for i in range(0, seq_len, chunk_size):
                output[b:b + 1, i:i + chunk_size] = inner_mlp_forward(hidden_states[b:b + 1, i:i + chunk_size])
        return output

hidden_dim = 4
intermediate_dim = 16
batch_size = 2
seq_len = 3

mlp_model = GLMMLP(hidden_dim, intermediate_dim)
hidden_states = torch.randn(batch_size, seq_len, hidden_dim)

ARGS = {
    "self": mlp_model,
    "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 — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float, shape (2, 3, 4) — shape (2, 3, 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
mid_trunc_and_pad Ran
ran on a synthesized input
bytedance/FlexPrefill/experiments/benchmark/utils.py
code served (permissive licence) · get_code("1bd20ca4f6cfb4eb")
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 (6,) 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 torch.nn.functional as F

torch.manual_seed(0)

# Analyze the function:
# - x: list - will be converted to tensor, supports indexing and len()
# - max_len: int - used for division and slicing
# - pad_len: int - used for padding comparison
# - pad_value: int - used as value in F.pad()

# Create a simple list with distinct values
x = [1, 2, 3, 4, 5, 6, 7, 8]

# max_len should be smaller than len(x) to test truncation
max_len = 4

# pad_len should be larger than the result after truncation to test padding
# After truncation: x[:2] + x[-2:] = [1, 2, 7, 8] which has length 4
# So pad_len should be > 4 to trigger padding
pad_len = 6

# pad_value is just an integer
pad_value = 0

ARGS = {
    "x": x,
    "max_len": max_len,
    "pad_len": pad_len,
    "pad_value": pad_value,
}
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 (6,) — shape (6,) 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
remove_duplicates_by_index Ran
ran on a synthesized input
bytedance/FlexPrefill/experiments/benchmark/run_ruler.py
code served (permissive licence) · get_code("2742a6153e7ec429")
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 numpy as np

# Construct valid arguments for remove_duplicates_by_index
# The function expects a list of dictionaries, where each dict has an 'index' key

list_of_dicts = [
    {'index': 1, 'value': 'a'},
    {'index': 2, 'value': 'b'},
    {'index': 1, 'value': 'c'},  # duplicate index
    {'index': 3, 'value': 'd'},
    {'index': 2, 'value': 'e'},  # duplicate index
]

ARGS = {
    'list_of_dicts': list_of_dicts
}
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 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
split_tensor_along_last_dim Ran
ran; our contract draft was wrong, not the code
bytedance/FlexPrefill/flex_prefill/modules/glm/glm_self_attention_foward.py
code served (permissive licence) · get_code("08b693a1068fa690")
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 4, 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 a small tensor with shape (2, 4, 8)
# Last dimension is 8, which is divisible by 2 and 4
tensor = torch.randn(2, 4, 8)

ARGS = {
    "tensor": tensor,
    "num_partitions": 2,
    "contiguous_split_chunks": False,
}
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, ndim 4, 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
str_to_dict Ran
ran on a synthesized input
bytedance/FlexPrefill/experiments/benchmark/utils.py
code served (permissive licence) · get_code("35b094727218cc43")
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 dict. 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 ast import literal_eval

torch.manual_seed(0)

# The function str_to_dict takes a single parameter: cfg (a string)
# It parses a comma-separated string of key=value pairs and converts it to a dictionary
# The function:
# 1. Splits by comma and strips whitespace
# 2. Splits each item by '=' to get key and value
# 3. Uses literal_eval to parse values, falling back to string if that fails

# Valid test cases for cfg parameter:
test_cfg_1 = "a=1, b=2, c=hello"
test_cfg_2 = "x=[1,2,3], y=True, z=3.14"
test_cfg_3 = "model_name=resnet, batch_size=32"
test_cfg_4 = "flag"  # Single key with no value should be True

ARGS = {
    "cfg": "a=1, b=2, c=hello, d=[1,2,3], e=True, f=3.14"
}
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 dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict 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
glm_self_attention_forward Not yet run
unverified (harvested, no recorded run)
bytedance/FlexPrefill/flex_prefill/modules/glm/glm_self_attention_foward.py
code served (permissive licence) · get_code("1c80690cb1a8743d")
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, 3 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 8 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
split_tensor_along_last_dim 8 other papers
7 dated earlier, 1 later
2307.13528 (2023-07)
FacTool: Factuality Detection in Generative AI -- A Tool Augmented Framework for Multi-Task and Multi-Domain Scenarios
2311.18445 (2023-11)
VTimeLLM: Empower LLM to Grasp Video Moments
2401.18058 (2024-01)
LongAlign: A Recipe for Long Context Alignment of Large Language Models
and 5 more not named here
apply_rotary_pos_emb 2 other papers
2 dated earlier
2408.10943 (2024-08)
SysBench: Can Large Language Models Follow System Messages?
2410.03577 (2024-10)
Look Twice Before You Answer: Memory-Space Visual Retracing for Hallucination Mitigation in Multimodal Large Language Models
get_num_warps_stages 1 other paper
1 later
2509.24745 (2025-09)
ProxyAttn: Guided Sparse Attention via Representative Heads

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) encounter computational challenges during longsequence inference, especially in the attention pre-filling phase, where the complexity grows quadratically with the prompt length. Previous efforts to mitigate these challenges have relied on fixed sparse attention patterns or identifying sparse attention patterns based on limited cases. However, these methods lacked the flexibility to efficiently adapt to varying input demands. In this paper, we introduce FlexPrefill, a Flexible sparse Pre-filling mechanism that dynamically adjusts sparse attention patterns and computational budget in real-time to meet the specific requirements of each input and attention head. The flexibility of our method is demonstrated through two key innovations: 1) Query-Aware Sparse Pattern Determination: By measuring Jensen-Shannon divergence, this component adaptively switches between query-specific diverse attention patterns and predefined attention patterns. 2) Cumulative-Attention Based Index Selection: This component dynamically selects query-key indexes to be computed based on different attention patterns, ensuring the sum of attention scores meets a predefined threshold. FlexPrefill adaptively optimizes the sparse pattern and sparse ratio of each attention head based on the prompt, enhancing efficiency in long-sequence inference tasks. Experimental results show significant improvements in both speed and accuracy over prior methods, providing a more flexible and efficient solution for LLM inference.

For agents

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

get_harvested_code_for_paper("2502.20766")
get_code_for_paper("2502.20766")
have("2502.20766")

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

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

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

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

Connect an agent — have() is free.