FlexPrefill: A Context-Aware Sparse Attention Mechanism for Efficient Long-Sequence Inference

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

Abstract

As Large Language Models (LLMs) are increasingly deployed for long-context applications such as document synthesis and codebase analysis, the computational cost of the pre-filling phase has become a critical bottleneck. Standard attention mechanisms scale quadratically with sequence length, making long prompts prohibitively expensive. This paper introduces FlexPrefill, a novel sparse attention mechanism that dynamically adapts its computation patterns and attention budget in real-time based on specific input prompts and individual attention heads. By intelligently switching between structured and query-specific patterns, FlexPrefill achieves up to a 9.6x speedup in the pre-filling phase while maintaining or improving model accuracy across state-of-the-art LLMs.

Introduction

The ability to process long sequences is a defining feature of modern LLMs, yet the $O(L^2)$ complexity of the standard attention mechanism poses a significant challenge during the pre-filling phase—the initial stage where the model processes the input prompt. While sparse attention techniques have been proposed to mitigate this, most rely on static, "one-size-fits-all" patterns (e.g., sliding windows) or offline-searched configurations. These approaches fail to account for the inherent variability in how different attention heads and different prompts prioritize information.

FlexPrefill addresses these limitations by moving toward a context-aware, real-time approach. It treats sparsity not as a fixed constraint, but as a dynamic parameter that can be optimized on-the-fly to balance computational efficiency with semantic integrity.

Methods

FlexPrefill introduces two primary innovations designed to make sparse attention more flexible and responsive to the input data:

1. Query-Aware Sparse Pattern Determination

Attention heads within a transformer model exhibit specialized behaviors. Some heads are "Structured," showing consistent patterns (such as vertical or diagonal lines) across different queries, while others are "Diverse," changing their focus based on the specific query content.

FlexPrefill utilizes a small representative subset of queries to estimate the attention distribution for a given head. It then calculates the Jensen-Shannon (JS) divergence between this estimate and the true distribution. If the divergence is low, the system employs a flexible, query-specific pattern. If the divergence is high, indicating less predictability, it falls back to a more conservative structured pattern. This ensures that the most efficient pattern is used without sacrificing the head's functional role.

2. Cumulative-Attention Based Index Selection

Traditional sparse attention often uses a fixed sparsity ratio (e.g., keeping only the top 10% of tokens). However, the amount of information required to understand a prompt varies. FlexPrefill replaces fixed ratios with a cumulative attention score threshold ($\gamma$). The system selects the minimum number of tokens required to reach this threshold. Consequently, "easy" prompts may require only 1% of the attention computation, while "complex" prompts can dynamically scale up to 20% or more, ensuring that critical information is never discarded simply to meet a rigid compute budget.

Implementation

The system is implemented using Triton to ensure high-performance GPU execution. By building upon the foundations of FlashAttention, FlexPrefill minimizes the overhead of dynamic pattern switching, making it viable for real-world production environments.

Experimental Evaluation

The researchers evaluated FlexPrefill across four state-of-the-art LLMs: Llama-3.1-8B, GLM-4-9B, Yi-9B-200K, and Qwen2-7B. Performance was measured using two rigorous long-context benchmarks:

  • RULER: A synthetic benchmark testing variable sequence lengths (4k to 128k) and task complexities, including multi-hop tracing.
  • InfiniteBench: A suite of 10 real-world and synthetic tasks (e.g., long-book QA, code debugging) with an average context length exceeding 214,000 tokens.

Key Results and Insights

Significant Acceleration

FlexPrefill demonstrated substantial performance gains over FlashAttention. At a context length of 512k tokens, it achieved a 9.6x acceleration ratio. Even at shorter lengths, the efficiency gains remained significant, providing a superior performance-latency trade-off compared to existing methods like MInference.

Accuracy Retention

On the RULER benchmark, FlexPrefill consistently outperformed other sparse methods such as StreamingLLM. While StreamingLLM's accuracy often plummeted as the context window expanded, FlexPrefill maintained accuracy levels very close to—and in some instances exceeding—full dense attention. This suggests that the dynamic budgeting mechanism effectively captures the "long-range dependencies" that static methods miss.

Head and Layer Specialization

Visualization of the model's internal states confirmed that attention patterns vary significantly across different layers and heads. FlexPrefill’s ability to treat these components individually is central to its success. By recognizing "attention sinks" (tokens that always receive high attention) and adapting to query-specific needs, the model avoids the waste inherent in uniform sparsity.

Conclusion and Future Work

FlexPrefill represents a shift from static to adaptive inference optimization. By utilizing JS divergence as a real-time switch and employing dynamic cumulative thresholds, it provides a scalable solution for the long-context bottleneck.

Future research directions include:

  • Reducing Search Overhead: Further optimizing the pattern-search phase to improve performance on shorter sequences.
  • Architecture Generalization: Testing the mechanism on Mixture-of-Experts (MoE) and non-Transformer architectures.
  • Decoding Phase Integration: Extending dynamic sparsity to the decoding (generation) phase to achieve end-to-end inference acceleration.

Summary updated

BibTeX
@inproceedings{lai2025flexprefill,
  author = {Xunhao Lai and Jianqiao Lu and Yao Luo and Yiyuan Ma and Xun Zhou},
  title = {{FlexPrefill: A Context-Aware Sparse Attention Mechanism for Efficient Long-Sequence Inference}},
  booktitle = {International Conference on Learning Representations},
  year = {2025},
  url = {https://openreview.net/forum?id=OfjIlbelrT},
}
Figure