Ten-Million-Token Contexts: Why Indexing Overhead Is the New Bottleneck
As context windows grow to the ten-million-token scale, the main cost in sparse attention can shift from attention computation to the indexing step that selects which tokens to attend to. This article examines why discrete indexing scales poorly, introduces Latent Sparse Attention (LSA) and its four-stage pipeline, reviews key parameters and complexity limits, and outlines how to validate accuracy, interpret speedup claims, deploy with fallback conditions, and diagnose whether indexing is the bottleneck in your own system.
When Contexts Grow, the Bottleneck Shifts from Computation to Retrieval
Sparse attention is already a common approach for handling long contexts. Its idea is straightforward: each query does not need to compute attention against every historical token; it selects a small number of relevant tokens for computation. At the million-token scale, this approach can significantly reduce inference overhead in many scenarios.
Sparse attention is usually implemented in two steps. The first step is an indexer that decides “which tokens to look at”; the second step performs standard attention over the selected tokens. For shorter contexts, the second step is often the main cost. Once contexts expand to the ten-million-token level, the first step may cost more than the second. Existing research has observed in some implementations that index filtering accounts for most of the preprocessing time. However, this ratio depends on model architecture, hardware, batch size, and sequence length, and cannot be directly applied to your own system.
Why Discrete Indexing Does Not Scale
Traditional indexers rely on discrete matching, such as keyword overlap, hash buckets, or mutual information estimation. These methods require maintaining additional structures such as inverted lists or hash tables. Every new query must be compared discretely against all historical tokens. The number of comparisons grows with sequence length, and total cost grows approximately quadratically. The longer the sequence, the harder it is to ignore the indexing cost itself.
The Basic Idea Behind Latent Sparse Attention
Latent Sparse Attention (LSA) avoids discretization. It projects historical key vectors through a low-dimensional linear projection into a continuous space. The query vector obtains corresponding coordinates in the same projection space, and nearest-neighbor search is then used to find the closest historical keys. The original problem of “judging whether each token is relevant one by one” becomes a vector retrieval problem of “finding neighbors in a continuous space.”
This idea has two potential benefits. First, nearest-neighbor search can leverage mature approximate nearest-neighbor algorithms, and retrieval cost has the opportunity to drop from quadratic to near-linear or even logarithmic. Second, if the projection function can be trained end-to-end, indexing features no longer depend on manual design and can instead be adjusted during training.
Four Steps of the Engineering Pipeline
A reproducible LSA module roughly contains the following four steps.
The first step is key vector dimensionality reduction. Suppose the historical context length is L and the key vector dimension of each token is d_k. The module uses a projection matrix to compress it to d_l dimensions (d_l is much smaller than d_k), producing compressed keys. The compressed representation of positional encoding is usually concatenated as well, so that positional information is not lost during dimensionality reduction.
The second step is query projection and nearest-neighbor retrieval. The current query vector passes through the same projection matrix to obtain low-dimensional query coordinates, and the M nearest keys are retrieved from the compressed keys. Common approaches use approximate methods such as Hierarchical Navigable Small World graphs (HNSW) or product quantization (PQ).
The third step is candidate mapping and fine-grained computation. The M coordinates returned by retrieval need to be mapped back to the position indices of the original tokens. Standard attention is then computed only over these M candidates.
The fourth step is gated fusion. Extreme sparsification may lose information, so a learnable gate can be added at the output to weighted-combine the sparse attention result with the attention result over a small number of global anchors. The number of anchors and the gate design need to be adjusted according to the task.
Key Parameters and Selection
The table below lists the main parameters that need to be determined during implementation. Specific values should be based on your own validation set results.
| Parameter | Role | Tuning Direction |
|---|---|---|
| d_l (latent space dimension) | Determines retrieval speed and information retention | Lower dimensions are faster but lose more information; sweep across values |
| M (number of candidates) | Determines the recall ceiling and subsequent computation | Larger M improves recall but increases computation |
| ANN index type | Determines build, insertion, and query costs | HNSW offers fast queries but high memory usage; PQ saves memory but has lower accuracy |
| Number of global anchors | Compensates for the loss of rare details | More anchors improve stability but add overhead |
| Recall threshold | Determines when to fall back to full attention | Set according to the minimum acceptable accuracy for the task |
The Real Boundaries of Complexity
“Retrieval cost close to logarithmic” holds only under specific conditions. First, the key set is mostly static. For example, when prefilling a fixed context, the graph index can be built once. Second, recall must be acceptable. Approximate algorithms sacrifice some precision for speed. Third, building the graph index itself requires time and memory, and this overhead cannot be ignored.
During autoregressive generation, each new token adds one element to the key set. The graph index needs to support insertion, and the update cost in some implementations is not low. Therefore, gains in the generation stage usually cannot directly use the numbers from the prefill stage.
How to Validate Accuracy
The original LSA report usually provides accuracy results on several long-text tasks and describes the gaps as small. This conclusion applies only to the tested tasks, models, and configurations, and cannot be directly generalized to all scenarios.
An executable validation process is as follows:
- Fix a full-attention baseline and use the same dataset version and the same evaluation script.
- Across multiple random seeds or multiple runs, report the mean and fluctuation range of metrics.
- For sampled queries, compute the overlap between the candidate set and the high-weight tokens under full attention, directly measuring recall quality.
- Focus on tasks that require exact retrieval of rare details, such as locating an isolated fact in a long text. These tasks are most likely to fail due to recall misses.
- Report accuracy degradation per task rather than only looking at the overall score.
How to Read Performance Numbers
Speedup ratios in reports require confirmation of the following information: what baseline is being compared; what hardware and numerical precision are used; what sequence length and batch size are used; whether single-layer preprocessing or end-to-end inference is measured; and whether index build time is included.
A speedup that only measures single-layer preprocessing cannot represent the latency improvement of the entire request. If the decoding stage of a request accounts for most of the time, the prefill-stage speedup will have a much smaller impact on user-perceived latency.
Deployment and Fallback
LSA can be wrapped as a standard attention operator and replace the sparse attention implementation in an existing inference framework, without modifying the rest of the model structure. Before replacement, validation should first be completed on small traffic or offline data.
For multi-turn requests with the same context, if the prefix does not change, index results can be cached and reused. The cache must be bound to the context content; once the prefix changes, it must be invalidated.
It is recommended to set fallback conditions in advance, switching back to full attention or traditional sparse attention when any of the following conditions is met:
- Recall on the validation set is below a preset threshold.
- Accuracy degradation on critical tasks exceeds the acceptable business range.
- Request latency in some length ranges is higher than the baseline.
- Memory usage exceeds the budget.
How to Determine Whether Your System Is Affected by the Indexing Bottleneck
You can troubleshoot with the following steps:
- Use profiling tools to record time by stage, separating indexing, attention matrix multiplication, and other operations.
- Repeat measurements across multiple sequence lengths and observe the exponent at which indexing time grows with length. If it is close to quadratic, indexing is a potential bottleneck.
- Record peak memory at the same time to determine the proportion occupied by index structures.
- After confirming that the indexing stage indeed dominates the time, evaluate alternatives such as LSA.
