# Sparse attention saves compute, so why is it slower online?

Date: 2026-11-19
Category: Technology
Tags: Sparse Attention, Inference Optimization, Long Context
Summary: Explain why sparse attention often lags behind dense implementations in terms of memory access, operator fusion, and batch size, and give the order of stress-test judgments before launch

In a long-context design review, the algorithm engineer presented a one-page document: change attention from fully connected to block-sparse, reducing complexity from quadratic to linear, and asked whether it could ship next week. Product cared about first-token latency and per-session cost; engineering cared about whether existing kernels could be reused. No one first asked: are we saving floating-point operations (FLOPs), or time?

## Don't ask how much compute is saved first—ask where the bottleneck is

The theoretical case for sparse attention looks great. Full attention computes relevance between every token and all historical tokens; double the sequence and compute grows quadratically. Local windows, global tokens, block sparsity, dynamically selecting the top-k connections—these methods cut the number of connections, and complexity can drop to linear or near-linear. A sparse connectivity diagram in a paper does look cleaner than a dense fully connected one.

But online latency is not determined directly by a complexity formula. Whether a kernel is fast depends first on how many times it moves data, and then on how many times the moved data is computed. The former is memory access, the latter is compute, and the ratio between them is arithmetic intensity. GPUs like work with high arithmetic intensity: bring in a large chunk of data once and compute on it many times. Sparse attention often does the opposite—compute drops, but to find which blocks to compute, it must read indices, make decisions, and gather data in a scattered way, so arithmetic intensity falls.

So the first question is not how much compute can be saved, but whether the current request is bottlenecked on compute, memory bandwidth, or scheduling overhead. If it is bottlenecked on memory bandwidth, reducing compute may not help unless you also reduce the bytes to be read and keep those reads contiguous. If it is bottlenecked on kernel launch and batch shape, sparsity only makes scheduling more fragmented.

## Dense attention has been tuned by the hardware

Dense attention is not a naive approach. It has been tuned for GPUs for years, with mature matrix-multiply libraries, tiling strategies, and fused kernels. Implementations like FlashAttention try to keep QK computation, softmax normalization, and multiplication by V within one fused kernel to reduce memory round trips, while the computation itself remains large matrix multiplies. Large matrix multiplies are friendly to tensor cores, to caches, and to compilers and kernel libraries.

The first wall sparse implementations hit is the memory access pattern. Fetching K and V by arbitrary indices turns contiguous large-block reads into random small-block reads. Choosing a block size of 16, 32, or 64 looks like just a parameter, but it actually determines whether each memory access can align to cache lines and whether it can form a decent matrix multiply. If blocks are too small, index and boundary checks cost more than the computation; if blocks are too large, sparsity is insufficient and the saved compute is eaten back by padding.

Element-level sparsity is even more awkward. It looks sparse in a diagram but is fragmented on hardware. Structured sparsity such as 2:4 has hardware support in matrix multiplies, but common sparsity patterns in attention are not of this fixed shape. Local windows plus global tokens, or dynamically selecting the top k per head, produce shapes that vary with the input, making it hard for hardware to schedule the pipeline in advance. Regular block sparsity can at least be mapped to small matrix multiplies; dynamic top-k selection often requires sorting first and then gathering, and sorting itself is a significant cost.

This is also why some schemes look fast at the kernel level but are slow once integrated into the model. Layout conversions, mask materialization, and index generation are added in between, and each step reads and writes memory. The time saved by a single kernel is eaten up by the data movement around it.

## Prefill and per-token generation are two different ledgers

When discussing sparse attention, prefill and per-token decode must be separated. Prefill processes the entire input at once, with large matrix multiplies, and is usually closer to compute-bound. Per-token generation reads the historical key-value cache (KV cache) at each step and, with long contexts and small batch sizes, is often closer to memory-bandwidth-bound. The bottlenecks differ, and so do the benefits of sparsity.

In the prefill stage, if the sparsity pattern is a fixed block structure, it can be mapped directly to a batch of large matrix multiplies, and the reduced compute has a chance to become shorter time to first token (TTFT). The prerequisites are that blocks are large enough, fusion is good enough, and the sequence is long enough. Within a few thousand tokens, a dense implementation can already keep the GPU fed, and sparse indexing and branching instead leave compute units idle.

The per-token generation stage is more subtle. Each generated token requires reading the historical KV once. If sparse attention can reliably read only a few blocks, it may indeed reduce KV reads. But selecting which blocks requires indices, and reading blocks is a gather. When the sequence is not long enough, the saved reads do not outweigh the indexing overhead; when the batch size is large, different requests select different blocks, and load is imbalanced. The result may be lower compute with no reduction in time per output token (TPOT), or even worse performance because kernels are more fragmented.

There is another easily overlooked variable here: grouped-query attention (GQA), multi-query attention (MQA), KV quantization, and paged management are already reducing the bytes read from the KV cache. If sparse attention only reduces compute without reducing bytes, or if the reduced bytes are offset by inefficient memory access, it will struggle to win in per-token generation. In terms of order, I would first get the KV ledger clear, then decide whether to change the attention pattern.

## What really eats the gains is this overhead

Looking at dense and sparse side by side, the difference is not only in compute.

| Dimension | Dense implementation | Sparse implementation |
| --- | --- | --- |
| Memory access | Contiguous large blocks | Gather by index |
| Compute | Large matrix multiplies | Small matrix multiplies or gather-based reads |
| Extra data | Little | Indices, masks, lengths |
| Load | Relatively uniform | Uneven block hotness |

This extra data is not free. Mask materialization adds memory proportional to sequence length; dynamic block selection requires sorting or approximate sorting; variable-length requests must be padded to block boundaries; and different heads selecting different blocks makes it hard to merge kernels. Looking at the attention kernel alone, the sparse version may be faster; with pre- and post-processing attached, end-to-end performance may be flat or even slower.

There is also a common misjudgment: treating theoretical sparsity as effective sparsity. A paper may say only a few percent of connections are kept, but on hardware data is fetched by block, unused positions within a block are still computed, and boundaries still need padding. Effective compute is often considerably higher than the formula suggests. The larger the block, the more obvious this gap; the smaller the block, the worse the memory access efficiency. The sweet spot in between depends on head dimension, data type, sequence length, and batch size, and cannot be fixed by a single diagram.

So sparse attention is not finished once you implement a smarter mask. It requires changing kernels, memory layout, and batch scheduling together. If a team only changes the model structure and expects the existing framework to speed up automatically, chances are they will end up with a more complex model and a latency curve that has not gotten any shorter.

## I would judge in this order

I would judge in this order, rather than looking at the complexity in the paper first.

```mermaid
flowchart TD
A[长上下文变慢] --> B{瓶颈在哪}
B -->|算力| C[规则块稀疏]
B -->|访存| D[先减 KV 字节]
B -->|调度| E[查批次与算子启动]
C --> F{块对齐且融合}
D --> F
E --> F
F -->|否| G[回退稠密]
F -->|是| H[端到端压测]
```

If the bottleneck is prefill matrix multiplies, first check whether block sparsity can be mapped to large matrix multiplies and fused with existing kernels. If the bottleneck is KV reads during per-token generation, first look at GQA, quantization, KV eviction, and paged management, then see whether sparse attention can truly reduce bytes read. If the bottleneck is kernel launch and batch shape, sparsity is usually not the answer; it only increases the number of scheduling events.

This order matters. Optimize the wrong bottleneck and the harder you try, the slower it gets. A team changes attention to sparse, finds GPU utilization has dropped, mistakenly assumes there is headroom, and keeps increasing batch size, until latency and memory both go up. Lower utilization does not necessarily mean compute was saved; it may mean compute units are waiting for data.

## Stress test with real traffic before deciding whether to build it

Don't make decisions before launch based on microbenchmarks of single long requests. Single requests, batch size 1, fixed length, and prefill-only testing easily amplify the advantages of sparsity while hiding the overhead. In real traffic, request lengths are distributed, output lengths are uncertain, batch sizes vary, and prefill is interleaved with per-token generation.

Stress testing should at minimum break out length percentiles, batch size, input and output lengths, and concurrency. Look at four metrics: time to first token, per-token output time, throughput per GPU, and p99 latency (tail latency). Average latency is misleading; users with long requests perceive the tail. Also look at cost: if the sparse version saves compute but occupies an extra copy of index memory, the concurrency a single card can support may actually drop. Accuracy can't be judged by perplexity alone either; long-context tasks such as retrieval, multi-hop, and citation position need separate testing. Sparse patterns may preserve local fluency while losing key information from far away.

If the sparse version reduces time to first token but not per-token output time, the optimization is in prefill, not per-token generation. If GPU utilization drops but latency doesn't, the saved compute isn't turning into time. If gains only appear on the longest small fraction of requests, and the routing and fallback logic is complex, I would stay dense first, queue or rate-limit long requests separately, and only move to sparsity once the share of long sequences and cost pressure are large enough.

The criterion can be plain: the sparse implementation must beat dense end to end under your own length distribution, batch size, and latency targets, without losing accuracy, at acceptable maintenance cost. Otherwise it's just a more complex theoretical advantage. At the next review, first ask them to replace the single-sample curves with stress test results from real traffic, then talk about how much was saved.
