How to Prevent Index Selection from Slowing Prefill in Long-Context Inference
Index selection can become the dominant cost in long-context sparse attention, even after the main attention workload has been reduced. This article explains why index filtering becomes a bottleneck and presents practical optimization strategies, including block-level candidate selection, index-vector reuse, lower-dimensional or lower-precision representations, and operator fusion. It also provides illustrative PyTorch code and guidance for evaluating performance and quality trade-offs.
1. Why Long Contexts Make Prefill a Bottleneck
When the input context approaches one million tokens, the first stage of model inference is prefill. During this stage, the model computes attention-related intermediate results for every position in the input. Because full attention scales quadratically with sequence length, latency and memory pressure can increase rapidly in long-context scenarios.
Sparse attention addresses this problem by avoiding interactions between every query position and the entire history. Instead, a lightweight filtering module—often called an indexer—first identifies a small set of relevant positions. Exact attention is then computed only for those positions.
This reduces the cost of the main attention operation, but it introduces a new cost: the filtering process must still scan the entire context.
In practice, this overhead can be substantial. On one model with a context length in the million-token range, index selection accounted for approximately 73% of prefill time. In another model evaluation, the proportion reached 90.8%. Once the main attention workload is compressed, the bottleneck can shift to the selection stage.
2. Why Index Selection Becomes the New Bottleneck
Its computational cost still depends on context length. During prefill, every query position scores all historical positions. If the context length is (N) and the index-scoring dimension is (d{\text{idx}}), the theoretical cost is approximately (O(N^2 \cdot d{\text{idx}})). Although (d_{\text{idx}}) is much smaller than the hidden dimension used by standard attention, the scaling trend remains unchanged.
Memory access can become the limiting factor before compute capacity is exhausted. Scoring requires reading a large number of index vectors from historical positions. For long sequences, memory bandwidth often becomes the primary constraint.
Separate operators increase data movement. If filtering and core attention run as independent operators, intermediate results may need to be written back to and reread from device memory. These additional transfers increase latency.
3. Main Approaches to Reducing Index-Selection Overhead
3.1 Reduce the Candidate Set
Use coarse-to-fine block selection. First divide the context into fixed-size blocks, generate a representative vector for each block, and select promising blocks. Then perform position-level scoring only within the selected blocks. This reduces the scale of scoring from all (N^2) position pairs to a workload related to the number of blocks.
Reuse historical index vectors. Once the prefix has been generated, the index vector for each historical position is already determined. Reusing these vectors in later steps avoids recomputing them.
3.2 Reduce Index-Vector Dimension and Precision
Use a lower-dimensional projection. A smaller projection dimension can be used for index scoring, reducing both computation and memory traffic.
Use lower-precision representations. Index vectors can be stored in a lower-bit format when the resulting accuracy loss is acceptable. Before applying this optimization, use an evaluation set to verify that retrieval quality does not degrade significantly.
3.3 Fuse Operators at the Engineering Level
- Place index selection and attention computation in the same kernel to reduce intermediate reads and writes.
- Use profiling tools to locate the actual sources of latency before choosing an optimization. This avoids blindly tuning parameters based on assumptions.
4. Example: Coarse-to-Fine Block Selection
The following code illustrates the approach. Batch processing and multi-head dimensions are omitted for simplicity, and the final block is padded with zeros.
import torchdef block_topk_select(q, k_index, block_size=64, top_blocks=8, top_k=256):"""q: [d], k_index: [N, d]. Returns selected historical position indices."""N = k_index.shape[0]num_blocks = (N + block_size - 1) // block_sizepad = num_blocks * block_size - Nk_pad = torch.nn.functional.pad(k_index, (0, 0, 0, pad))# Step 1: Use the mean vector of each block to select promising blocksblock_repr = k_pad.view(num_blocks, block_size, -1).mean(dim=1)block_score = block_repr @ qchosen = torch.topk(block_score, k=min(top_blocks, num_blocks)).indices# Step 2: Score individual positions within the selected blocksidx = (chosen[:, None] * block_size + torch.arange(block_size)).reshape(-1)idx = idx[idx < N]fine_score = k_index[idx] @ qkeep = torch.topk(fine_score, k=min(top_k, idx.numel())).indicesreturn idx[keep]
This implementation reduces the number of scored positions from (N) to approximately:
[
\text{num_blocks} + \text{top_blocks} \times \text{block_size}
]
The block size and the number of retained blocks determine the trade-off between accuracy and speed. These parameters should be tuned against the characteristics of the target data.
5. How to Evaluate the Optimization
Performance metrics: Measure prefill latency share, time to first token, and peak memory usage. Collect these metrics separately before and after the change to avoid conflating different factors.
Quality metrics: Compare answer accuracy on long-document question answering, key-information retrieval, and similar evaluation tasks. Confirm that selection accuracy has not significantly deteriorated.
Recommended validation order: First use profiling to confirm the bottleneck. Then make changes one at a time and measure the benefit of each optimization independently.
6. Deployment Recommendations and Trade-offs
- For relatively short contexts, full attention is simpler to implement, and the benefits of sparsification may be limited. Optimization is not always necessary.
- Selection parameters—including block size, the number of retained candidates, and the precision format—directly affect output quality. Configure them for the target workload instead of copying default values.
- When inference services run in the cloud, use general monitoring and alerting capabilities to track the distribution of prefill latency over time, with particular attention to long-tail requests.
