Compressing Sparse Attention Index Cache for Long-Context LLM Inference

    This article explains why the index cache becomes a bottleneck in million-token context inference and how four-to-one weighted pooling compresses it. It covers the core pooling approach with a Python example, why the compression offers low risk and predictable gains, and the engineering details needed to deploy it, including boundary alignment, incremental updates, numerical stability, and recall tuning.

    1. The Problem: In Long Contexts, the Index Becomes the New Bottleneck

    In inference scenarios with million-token contexts, the cost of attention computation grows quickly. A common industry response is a hybrid attention architecture: one part uses linear attention, which captures local dependencies through a recurrent state-update mechanism with complexity that is roughly linear in sequence length; the other part uses sparse attention, where a lightweight indexer first performs a coarse filter over the global context, recalls a small set of the historical segments most relevant to the current query, and then runs fine-grained attention only over those segments.

    This architecture splits the cost into two parts: fine-grained attention operates only on the small set of recalled tokens, while the recall step itself requires a resident index structure to support it. The catch is that the index structure is not free. It must continuously maintain cached vectors for historical tokens, and the cache size grows linearly with context length; every decoding step must read and compare these vectors, adding extra memory access and computation. When the context reaches the million-token scale, the indexer’s own latency and memory footprint rise sharply, and can even offset the gains from sparsification.

    Index cache compression therefore becomes an independent optimization problem: reduce the number and size of the cached vectors without noticeably hurting recall quality.

    2. The Core Idea: Four-to-One Weighted Pooling

    A direct approach is to periodically merge several adjacent index cache vectors into a single representative vector, a process known as pooling. If every 4 vectors are merged into 1, the number of cache entries drops to one quarter, and the memory access, comparison count, and GPU memory usage during indexing fall by the same proportion.

    The key question is how to merge them. Simple average pooling is the easiest to implement, but it mixes information from different tokens with equal weight and tends to blur the signals that actually carry discriminative power; max pooling preserves the strongest response but loses distributional information. A more robust choice is weighted pooling: assign a weight to each merged vector, then take the weighted sum to produce the representative vector.

    1. # Example: weighted pooling of every 4 index cache vectors into 1
    2. def pool_index_cache(vecs, weights, group=4):
    3. # vecs: [N, D] historical index cache; weights: [N] or [N, D]
    4. out = []
    5. for start in range(0, vecs.shape[0] - group + 1, group):
    6. chunk = vecs[start:start + group] # [group, D]
    7. w = weights[start:start + group] # [group] or [group, D]
    8. w = w / (w.sum(axis=0, keepdims=True) + 1e-6)
    9. out.append((chunk * w).sum(axis=0)) # [D]
    10. return out

    The weights can come from several sources: position-based decay weights (nearer tokens get higher weight), importance-based scores (such as the historical attention quality at that position), or weights learned by a small projection layer. In practice, teams usually start with static weights to ensure interpretability and zero extra inference cost, then evaluate whether to introduce learnable weights.

    3. Why the Compression Is Low-Risk and High-Reward

    Sparse attention recall is inherently redundant: adjacent tokens are highly correlated semantically, and their index vectors often point in similar directions, so the marginal information from keeping them one by one is low. This means that compressing a short span of continuous context into a single representative vector loses limited discriminative power, while the gains are certain: cache entries drop to one quarter, and read bandwidth, comparison computation, and GPU memory usage during indexing fall in step.

    From a systems perspective, this kind of optimization is especially worthwhile during decoding. Decoding is a memory-access-intensive workload, and every generated token requires scanning the index cache again; shrinking the cache fourfold cuts that bandwidth pressure to one quarter directly, and the improvement in end-to-end latency is linearly predictable. At the same time, a smaller cache means that, under the same GPU memory budget, you can support longer contexts, or leave more headroom for the KV cache and batch concurrency at the same context length.

    It is worth stressing that a higher compression ratio is not always better. Fourfold compression is a fairly balanced choice between recall quality and overhead; pushing the compression rate higher forces each representative vector to carry too much information, raises recall noise, and ends up slowing things down overall.

    4. Engineering Implementation Notes

    1. Alignment and boundary handling: the sequence length is not necessarily an integer multiple of the compression group, so trailing residual vectors must be kept separately or padded according to a policy to avoid out-of-bounds access and semantic misalignment.
    2. Incremental updates: during streaming generation the cache grows step by step, so pooling should be triggered on group boundaries to avoid recomputing the entire cache at every step and incurring extra overhead.
    3. Numerical stability: normalize before the weighted sum and add a tiny value to prevent division by zero; if low-precision storage is used, watch for accumulation error affecting recall ranking.
    4. Coordination with the recall strategy: compression changes the candidate granularity, so the top-k threshold, deduplication, and minimum segment length for recall should be adjusted accordingly.
    5. Observability: monitor indexing latency, cache GPU memory, recall hit rate, and end-to-end throughput separately to determine whether the compression delivers a net gain, and use monitoring, alerting, and logging services to establish baseline comparisons.
    6. Capacity planning: long-context inference typically runs on an elastic container platform, paired with object storage to persist long-session state, and the compressed cache size is an important input for capacity estimation.

    5. Summary

    The essence of index cache compression is trading controllable information loss for certain resource savings. The four-to-one weighted pooling scheme reduces the index cache to one quarter, easing both latency and memory pressure at the million-token scale without changing the upper-level model structure. In practice, focus on boundary alignment, incremental updates, numerical stability, and coordination with the recall strategy, and validate the gains against clear metric baselines, and you can reliably incorporate this optimization into the long-context inference pipeline.