Long-Context Sparse Attention: Compressing the Index Cache with Pooling
This article explains why the index cache becomes the main bottleneck in million-token context inference and how weighted cache pooling reduces its size to one quarter. It covers the motivation behind hybrid linear and sparse attention, the difference between weighted pooling and naive averaging, why pooling preserves coverage better than dropping entries, engineering details such as padding, weight stability and streaming updates, and the metrics needed to validate the compression.
1. Background: The Cost of the Indexer in Long Contexts
In inference scenarios with million-level context, the cost of attention computation grows rapidly with sequence length. As a result, the industry commonly adopts a hybrid architecture of linear attention plus sparse attention: the linear branch compresses historical states recursively and models local dependencies, while the sparse branch uses a lightweight indexer to select a small number of the most relevant historical positions globally, applying exact attention only to those positions.
This design shifts the main cost from full attention to indexing and retrieval. The indexer is lightweight, but it must maintain a cache over the history that can be queried repeatedly (essentially a set of key vectors organized by position). When the context grows from tens of thousands of tokens to the million scale, this cache creates two kinds of direct pressure:
- Memory pressure: the cache size is proportional to the sequence length. In long contexts it takes space that could otherwise be used for activations and batch concurrency, directly reducing the number of requests that can be served concurrently.
- Latency pressure: every decoding step scores and filters the cache. The larger the cache, the more memory bandwidth is consumed, and the harder it becomes to keep single-step decoding latency low.
So one high-leverage point for long-context optimization is not to further weaken the expressiveness of the indexer, but to reduce the storage and access cost of the index cache.
2. Core Idea: Compressing the Index Cache Four to One
A direct and effective approach is cache pooling: instead of keeping multiple index vectors for each historical position, merge every few adjacent ones (for example, 4) into a single vector through weighted pooling, reducing the index cache to one quarter of its original size.
The key word here is weighted, not average. Naive averaging indiscriminately flattens the importance differences between positions and degrades retrieval quality. Weighted pooling assigns weights according to the salience of each position (general signals such as scores, attention quality, or positional decay), so that information tilts toward important positions during compression.
The idea can be expressed with the following illustrative pseudocode:
# Pool every 4 adjacent index cache vectors into 1def pool_index_cache(cache, weights, group=4):# cache: [L, D] original index cache, L is history length, D is dimension# weights: [L] salience weight per position (from scores or decay)L, D = cache.shapepad = (-L) % groupcache = pad_and_reshape(cache, pad, group) # [L', group, D]w = pad_and_reshape(weights, pad, group) # [L', group]w = softmax_over_last_dim(w) # normalize within grouppooled = (w.unsqueeze(-1) * cache).sum(dim=1) # [L', D]return pooled, L // group # new length is about L/4
After compression, the candidate set that the indexer scores and filters shrinks to one quarter, and memory access and computation drop together. Because the merge is weighted, the retained positions are still representative in semantic terms, so the retrieved global context is not severely distorted.
3. Why Compressing the Cache Beats Dropping Entries
A common engineering alternative is to directly reduce the number of entries the indexer maintains (for example, keeping only the most recent N positions or sampling at a fixed stride). Pooling compression has three advantages over that:
- Complete coverage: each pooled unit still corresponds to a continuous span of history, so the timeline is not torn apart and distant key information still has a chance of being retrieved.
- Smoothly tunable: the group size (such as 2, 4, or 8) is a continuously adjustable knob for fine-grained trade-offs between compression ratio and retrieval accuracy, rather than an all-or-nothing choice.
- Clean decoupling from training and inference: pooling is a local, differentiable aggregation operation, which makes it easy to optimize jointly with the indexer during training, while at inference time it degenerates into a single memory-access-friendly reduction.
4. Engineering Implementation Notes
- Position and boundary handling: sequence length is often not an integer multiple of the group size, so a clear padding and masking strategy is needed to avoid counting invalid positions in the weights.
- Keep the weight source stable: weight signals should come from scores aligned with the retrieval objective, avoiding extra high-frequency jitter; apply temperature scaling or clipping to the weights when necessary.
- Be memory-access friendly: implement pooling over a contiguous memory layout, fuse it into a single reduction where possible, and avoid repeatedly reading and writing intermediate tensors.
- Coordinate with the decoding loop: the cache grows incrementally during decoding, so pooling should support streaming updates instead of recomputing the full cache at every step.
- Accuracy regression: turn compression ratio, retrieval hit rate, and end-to-end task metrics into a regression curve, and let data decide the group size rather than intuition.
5. Validation and Metrics to Watch
At minimum, track four categories of metrics: the memory footprint of the index cache and the reduction ratio; single-step decoding latency and time to first token in long contexts; retrieval hit rate (the proportion of truly high-relevance positions among those selected); and end-to-end task quality (long-document question answering, cross-passage retrieval, multi-turn long conversations, and so on). Only when all four categories hold up is the compression a real gain.
6. Running It in the Cloud
To deploy this kind of optimization in a cloud environment, you can build a closed loop with general-purpose capabilities: use a container platform to host the inference service and scale it elastically, use monitoring and alerting to watch latency and memory watermarks, use a logging service to capture the layered latency of long-context requests, and use object storage to keep evaluation sets and regression baselines. Baidu AI Cloud offers corresponding capabilities in these general categories, which makes it easier to turn the tuning process for compression ratio, quality, and cost into a sustainable experiment pipeline.
7. Summary
The bottleneck in long contexts is shifting from doing a lot of computation to storing a lot and fetching slowly. Compressing the indexer cache four to one with weighted pooling is a low-cost, explainable, and easy-to-tune optimization path: it cuts the cache to one quarter of its size while relying on weights to retain key positions, achieving a verifiable balance among latency, memory, and retrieval quality. Get boundary handling, weight stability, and the regression curve right, and you can obtain stable performance gains at the million-token context scale.
