Long Context Sparse Attention: Index Cache Compression for Faster Inference
This article explains how index cache compression addresses the indexing bottleneck in long-context sparse attention. It covers a four-to-one weighted pooling scheme that shrinks the indexer cache to one quarter of its original size, along with key design choices, engineering implementation details, and an evaluation and tuning checklist for balancing recall quality against memory and latency costs at million-token context lengths.
1. The Problem: The Indexer Bottleneck in Long Contexts
When context length grows from tens of thousands of tokens to the million-token (1M) range, a naive attention implementation suffers from two costs that worsen at the same time: computation grows quadratically with sequence length, while KV Cache memory grows linearly.
A common industry response is a hybrid attention architecture. Some layers use linear attention or recurrent state compression to capture local dependencies, while other layers use sparse attention. In the sparse layers, a lightweight “indexer” retrieves a small set of the most relevant context blocks for the current query across the global context, and exact attention is applied only to those blocks.
This architecture shifts the main pressure from full attention to the indexing and retrieval stage. Although a single indexer step is not computationally heavy, the indexer must maintain its own cache vectors and, at every decoding step, score, rank, and select the top-k entries for each query. At a context length of 1M, both the memory footprint of the indexer cache and the per-token scoring latency become significant enough to offset the gains from sparsification. Compressing the indexer cache itself is therefore a natural entry point for long-context engineering optimization.
2. Core Idea: Four-to-One Cache Compression via Weighted Pooling
A typical and engineering-friendly approach can be summarized as “four-in-one index cache compression”: merge every 4 adjacent vectors in the indexer cache into 1 vector using weighted pooling, reducing the indexer cache size to one quarter of the original.
There are three key design points:
- Compression happens on the index side, not the main KV side. The main key-value cache usually carries the accuracy baseline and is risky to compress. The indexer is only responsible for coarse retrieval, is relatively insensitive to accuracy, and is a safer compression target.
- Use weighted rather than equal-weight averaging. Equal-weight averaging makes important and secondary positions contribute equally, blurring the distinction between scores. Weights derived from position, time decay, or attention statistics preserve more pronounced peaks after compression, making top-k selection closer to the uncompressed result.
- Compression ratio and recall window must be tuned together. After the cache shrinks by 4x, index granularity becomes coarser, so the number of retrieved blocks usually needs to be adjusted accordingly, trading “fewer entries with a slightly larger window” for a similar recall coverage.
Illustrative pseudocode (expressing the idea only, not any specific product interface):
# Index cache: [seq_len, dim], compress every 4 adjacent vectors into 1def pool_index_cache(cache, weights):# cache: [N, D] N is the number of index entries# weights: [N] position/decay weights, softmax normalizedN, D = cache.shapeassert N % 4 == 0c = cache.view(N // 4, 4, D)w = weights.view(N // 4, 4, 1)return (c * w).sum(dim=1) / w.sum(dim=1).clamp_min(1e-6)# Retrieval: score on the compressed index and take top-kdef recall(pooled, q, k):scores = pooled @ q # [N/4]idx = scores.topk(k).indicesreturn idx * 4 # map back to the original block start position
3. Engineering Implementation Details
- Source of weights. Common options include fixed geometric decay (positions closer to the current token get higher weights), online weights based on cumulative attention statistics, or weights learned by a projection layer with a very small number of parameters. The recommendation is to start with fixed decay, confirm the gains, and only then introduce learnable weights to avoid early training instability.
- Compression granularity alignment. The boundaries of the 4-to-1 grouping should align with the downstream recall block size and the paged cache allocation granularity to reduce extra copies caused by cross-boundary concatenation.
- Consistency during inference. During incremental decoding, trigger pooling only after every 4 new index vectors are written, rather than recomputing at each step; also cache the “uncompressed tail” to prevent over-compression in the short-sequence phase.
- Numerical stability. Vector norms change after pooling, so normalization before scoring is recommended to prevent top-k from being persistently biased toward specific compressed regions.
- Coordination with linear attention layers. Local layers handle short-range dependencies and the index layer handles long-range retrieval; when the responsibility boundary between them is clear, index compression has the least impact on overall quality.
4. Evaluation and Tuning Checklist
Evaluation should cover at least three categories of metrics. First, the resource side, including index cache memory usage, single-step decoding latency, and long-context time-to-first-token and sustained throughput. Second, recall quality, measured by top-k overlap rate before and after compression and recall coverage. Third, task performance, focusing on scenarios sensitive to global retrieval such as long-document retrieval, multi-hop question answering, and long code base understanding.
Recommended tuning order: first fix the compression ratio at 4 to verify memory and latency gains, then gradually relax the recall count to find the quality inflection point, and finally tune the weighting scheme. If quality drops, first check whether the most recent context at the very end of the sequence was compressed, and whether score normalization is missing.
5. Summary
The essence of indexer cache compression is finding a controllable balance between recall accuracy and long-context resource cost. The four-to-one weighted pooling scheme applies compression on the accuracy-insensitive index side and, together with coordinated adjustments to the recall window and weights, can alleviate both latency and memory pressure at million-token context lengths. For deployment, it is recommended to introduce it as a revertible switch and to build three comparison tables for memory, latency, and recall overlap rate, letting data rather than intuition decide the compression ratio and weighting strategy.
