Sub-Linear Attention Indexing: Speeding Up Long-Sequence Attention at 10M-Token Contexts

    As large language model context windows scale from tens of thousands to millions of tokens, the cost of the indexing stage in sparse attention—often overlooked—can become the dominant bottleneck. This article examines why common optimizations like lower precision, dimensionality reduction, and key compression only reduce constant factors, and explores structural approaches that change complexity itself: hierarchical index structures, approximate nearest neighbor retrieval, and incremental prefill construction. It also covers practical engineering considerations including recall-accuracy trade-offs, memory management, observability, and integration with inference frameworks, offering a roadmap for scaling to ten-million-token contexts.

    Sub-Linear Attention Indexing: Speeding Up Long-Sequence Attention at 10M-Token Contexts

    1. The Real Cost Structure of Long-Context Inference

    As large model context windows grow from tens of thousands of tokens to hundreds of thousands—and even ten million or more—the performance bottleneck of inference systems is shifting structurally. Traditional dense attention has O(n²) complexity: once sequence length n reaches the hundred-thousand scale, storing and computing the attention matrix itself becomes infeasible. This is why the industry has broadly moved to sparse attention: instead of letting every query interact with all keys, a lightweight “indexer” first selects a small number of the most relevant key blocks for each query, and exact attention is computed only over the selected portion.

    This approach reduces the main attention computation from quadratic to nearly linear. But a key fact is often overlooked: the indexer itself has a cost, and that cost is rarely eliminated—it is merely hidden behind smaller constant factors.

    2. Common Indexer Optimizations and Their Ceiling

    In today’s mainstream sparse attention designs, indexer optimization generally follows three paths:

    1. Lowering compute precision. Reducing the indexing score computation from FP16/BF16 to FP8 or below cuts the hardware cost of each multiply-accumulate operation significantly.

    2. Compressing feature dimensions. Rather than scoring relevance with full attention head dimensions, the indexer uses a smaller projection dimension (for example, compressing 128 dimensions to 32), directly reducing the number of multiply-accumulates per scoring pass.

    3. Key granularity compression. Pooling several consecutive keys (for example, four) into a single “summary key” means the indexer only searches over summary keys, shrinking the candidate set by the compression ratio.

    Combined, these three techniques can lower the indexer’s constant overhead by roughly an order of magnitude. But from a complexity-theory perspective, they share a common ceiling: all of these optimizations divide by constants; none of them changes the order of growth.

    Let n be the context length and m the number of candidate key blocks each query must score. No matter how low the precision, how small the dimensions, or how aggressive the key compression, the indexer’s workload remains O(n·m)—it grows linearly with context length. The prefill phase is worse: every new token must be scored against all existing candidate blocks, for a total of O(n²) scoring operations. A small constant does not change quadratic growth. At the ten-million-token scale, even if a single scoring operation takes only tens of nanoseconds, the cumulative indexing cost once again becomes the dominant bottleneck.

    This is the real meaning behind claims like “22x faster indexing”: only by restructuring the indexer from “linearly scanning all candidates” to “sub-linear retrieval” can you achieve order-of-magnitude—not percentage-level—gains at ten-million-token scales.

    3. From Linear Scanning to Sub-Linear Retrieval: Restructuring the Indexer

    To break free of linear growth, the indexer’s design must shift from “scoring all candidates” to “touching only a few.” Several directions are being actively explored.

    3.1 Hierarchical Index Structures

    Borrowing the tree-based indexing idea from classical information retrieval, key blocks can be organized into multiple levels: the leaf layer holds the raw key blocks, while intermediate layers store progressively aggregated cluster centroids. At query time, the top level first prunes down to a few branches, then descends level by level, ultimately visiting only O(log n) nodes. This reduces per-query indexing cost from O(n) to O(log n), and total prefill complexity from O(n²) to O(n log n).

    The engineering challenge is that the hierarchy must be maintained dynamically during prefill—inserting new key blocks may trigger updates to cluster centroids. A pragmatic compromise is a “lazy update” strategy: rebuild centroids in batches at fixed intervals rather than adjusting after every insertion, amortizing the structural maintenance cost.

    3.2 Approximate Nearest Neighbor Candidate Filtering

    Another direction reframes index scoring as an approximate nearest neighbor search problem. Using locality-sensitive hashing, quantized codebooks, or learned routing functions, each query can be routed directly to a small number of “buckets,” with exact scoring performed only on key blocks inside those buckets. This approach is well established in recommendation systems and vector databases. The core challenge in adapting it to attention indexing is that attention distributions are highly dynamic and drift as generation proceeds, so statically partitioned buckets quickly become stale. The routing function therefore typically needs to be trained jointly with the model, or at minimum support online calibration.

    3.3 Caching and Reuse: Sharing Indices Across Layers and Steps

    Observation shows that the key block sets selected by queries often overlap heavily between adjacent attention layers and adjacent decoding steps. Exploiting this locality, several layers can share the same index results, or consecutive decoding steps can reuse the previous selection with only incremental corrections. These reuse strategies—trading time for space or space for time—do not change asymptotic complexity, but when implemented well, they can cut the indexer’s actual runtime by several more times with almost no loss in model quality.

    4. The Prefill Quadratic Trap: Chunked Parallelism and Incremental Construction

    Decoding-phase indexing cost can be pushed to sub-linear with the techniques above, but the O(n²) scoring operations in prefill need separate treatment. Two complementary approaches exist in practice.

    Chunked streaming processing. Split the very long input into fixed-size chunks and process them sequentially. As soon as a chunk is processed, its keys are written into the index structure; queries from subsequent chunks retrieve history through the sub-linear index rather than scoring against every historical key. This reduces total prefill indexing cost from O(n²) to O(n log n) or even close to O(n).

    Parallelism and pipelining. There is a natural pipelining opportunity between index computation and the main attention computation: while chunk i performs exact attention, chunk i+1’s index scoring can run in parallel. In distributed deployments, the context can also be sharded, with index structures spread across multiple compute nodes, using topology-aware communication scheduling to reduce cross-node retrieval latency. On cloud-native inference platforms, such capabilities typically rely on the platform’s elastic scheduling and high-speed network interconnects, so developers do not need to build the underlying communication layer themselves.

    5. Four Key Engineering Considerations

    5.1 Balancing Precision and Recall

    Sub-linear indexing is inherently approximate and will inevitably suffer recall loss—some key blocks that should have been selected get missed. A quantitative evaluation mechanism is essential: compare outputs against dense attention on representative long-text tasks, and track the relationship between key block recall and downstream metrics (such as long-document QA accuracy). General experience suggests that with recall above 95%, end-to-end quality is nearly unaffected; below 90%, perceptible degradation appears.

    5.2 The Hidden Cost of Memory Footprint

    Hierarchical indices, codebooks, and cluster centroids all require extra memory. At ten-million-token scale, even compressed index metadata can reach gigabytes. The sensible approach is to manage index structures and the KV cache under a unified scheme with tiered hot/cold scheduling: hot data stays in GPU memory, while cold data is swapped to object storage or host memory, with asynchronous prefetching to hide swap-in latency.

    5.3 Building Observability

    Long-context inference involves many stages, and indexer performance degradation (such as recall dropping due to cluster drift) tends to manifest as “slow decay” rather than “sudden failure.” It is advisable to integrate logging services and monitoring/alerting systems, continuously tracking key metrics such as indexing time share, candidate hit rate, and per-block recall, with threshold-based alerts so problems are caught before users notice them.

    5.4 Coordination with the Inference Framework

    The indexing strategy is not an isolated module; it must be co-designed with inference optimizations such as continuous batching, speculative decoding, and paged KV cache. For example, the chunk granularity of index results should align with the KV cache paging granularity—otherwise you end up in the awkward situation where “the index selected a block, but only part of it resides in GPU memory.” When choosing an inference framework, prioritize its extensibility for custom attention and custom indexing.

    6. Conclusion: From “Dividing by Constants” to “Changing the Order”

    Looking back across the technical landscape, a clear evaluation criterion emerges: when assessing any sparse attention optimization, first ask—does it divide by constants, or does it change the complexity order? Precision reduction, dimensionality reduction, and key compression belong to the former: effective at small context scales, but bound to fail at ten-million-token scale. Hierarchical indexing, approximate retrieval, and incremental prefill belong to the latter—the viable path toward sustainable scaling to ultra-long contexts.

    For developers, a pragmatic roadmap is phased evolution: use constant-factor optimizations to stabilize costs today, while architecting interfaces for sub-linear indexing; when context lengths approach the inflection point of existing solutions, switch smoothly to structural approaches. Only by combining complexity-theoretic judgment with careful engineering can “ten million tokens” evolve from a marketing number into a genuinely affordable, operable production capability.