Compressing Long-Context Sparse Attention Index Caches with Weighted Pooling

    As context windows grow from thousands to millions of tokens, attention cost scales quadratically and memory bandwidth becomes the bottleneck. This article breaks down index cache compression for long-context sparse attention: why the lightweight indexer's cache turns into a primary cost at million-token scale, how weighted pooling merges every four cached vectors into one to cut index cache size to roughly one quarter, and where this compression point fits into a hybrid linear-plus-sparse attention decoding flow. It includes a reference PyTorch implementation, evaluation metrics such as Recall@K and P50/P95/P99 index latency, common misconceptions, a tuning checklist, and deployment notes for running long-context inference on cloud infrastructure.

    1. The Indexer Bottleneck in Million-Token Contexts

    When context length grows from a few thousand tokens to the million-token range, attention complexity increases quadratically, while memory capacity and memory bandwidth pressure rise at the same time. A common industry response is a hybrid attention architecture: some layers use linear attention, which models local dependencies through recurrence or state updates with complexity that is roughly linear in sequence length, and other layers use sparse attention, which computes exact attention only over a small set of selected tokens.

    Sparse attention depends on one key premise: selecting the right tokens. To support this, the architecture typically introduces a lightweight indexer. The indexer maintains several cached vectors for every historical token, scores the current query during decoding, and recalls a small batch of the most relevant context from the global token pool. The indexer itself is lightweight, but its cache grows linearly with context length and must be read in full at every decoding step. At million-token scale, this overhead shifts from negligible to a primary cost:

    • Memory capacity: the number of cached vectors equals context length multiplied by vectors per token multiplied by the number of layers, which expands quickly at million-token lengths.
    • Memory bandwidth: every decoding step sequentially scans the entire index cache, a typical memory-bound workload.
    • Latency jitter: the larger the cache, the more pronounced the tail latency of a single decoding step, and jitter worsens when long and short requests run together.

    Index cache compression has therefore become one of the core engineering topics for making long context practical.

    2. Core Method: Four-in-One Cache Compression with Weighted Pooling

    A typical and easy-to-adopt technical route is index cache pooling (conceptualized as an IndexPool-style technique): every four cached vectors in the indexer are merged into one through weighted pooling, compressing the index cache to one quarter of its original size and reducing both latency and memory overhead in the indexing stage.

    The design has four key points:

    1. Grouping strategy. Adjacent index vectors from four consecutive tokens are grouped in temporal order, preserving local temporal structure after pooling. Aligning group boundaries with the chunking or state-update boundaries of linear attention reduces cross-group information loss.
    2. Weighted rather than averaged. A plain mean flattens the signal of important tokens. Weighted pooling introduces learnable weights or weights based on scores or decay, giving more critical vectors in a group a higher share. Common weight sources include positional decay (closer tokens get higher weights), indexer scores, and a very small learnable scalar parameter.
    3. Scoring in the compressed domain. The compressed vector count drops to one quarter, and both indexer scoring and Top-K recall happen in the compressed domain. The Top-K candidate set size stays the same, but the number of vectors scanned falls to one quarter.
    4. Decoupled from the hybrid architecture. Pooling applies only to the index cache of the sparse attention branch and does not change the recurrent state of linear attention. It can therefore be enabled at a chosen ratio per layer (for example, only in long-context layers) to trade off accuracy against overhead.

    Illustrative implementation (expressing the general idea only, not a specific product interface):

    1. import torch
    2. import torch.nn as nn
    3. class WeightedIndexPool(nn.Module):
    4. """Merge every group_size index cache vectors into one via weighted pooling."""
    5. def __init__(self, dim, group_size=4, learnable=True):
    6. super().__init__()
    7. self.group_size = group_size
    8. # In-group kernel weights: learnable scalars, or initialized with positional decay
    9. if learnable:
    10. self.w = nn.Parameter(torch.ones(group_size))
    11. else:
    12. self.register_buffer("w", torch.ones(group_size))
    13. def forward(self, idx_cache):
    14. # idx_cache: [B, H, L, D], where L is the context length
    15. B, H, L, D = idx_cache.shape
    16. pad = (-L) % self.group_size
    17. if pad:
    18. idx_cache = torch.cat(
    19. [idx_cache, idx_cache[:, :, -1:, :].expand(-1, -1, pad, -1)], dim=2
    20. )
    21. g = idx_cache.shape[2] // self.group_size
    22. x = idx_cache.view(B, H, g, self.group_size, D)
    23. w = torch.softmax(self.w, dim=0).view(1, 1, 1, self.group_size, 1)
    24. return (x * w).sum(dim=3) # [B, H, g, D], length reduced to 1/4

    Two engineering details matter. First, streaming pooling during incremental decoding requires caching the residual vectors of an incomplete group to avoid recomputation across steps. Second, weight initialization with a mild positional decay is usually more stable than initializing all weights to one.

    3. Position in the Hybrid Attention Architecture and Data Flow

    A single decoding step follows this data flow:

    1. The linear attention branch updates its state recurrently, capturing local dependencies with complexity that is roughly linear in length.
    2. The new token’s index vector is written to the index cache and enters the pooling buffer.
    3. Every time four vectors accumulate, one weighted pooling operation is triggered and the compressed index vector is written back to the index cache.
    4. The indexer scores over the compressed cache and recalls the Top-K global context.
    5. The sparse attention branch computes exact attention only over the recalled K tokens, and its output is fused with the linear branch output.

    The compression point sits between writing and scoring, so the intrusion into the model backbone is minimal. It is a pluggable inference-time optimization, and it also allows light adaptation during training with a compression-recall consistency objective.

    4. Sources of Gains and How to Quantify Them

    The gains come from three sources: index cache memory drops to roughly one quarter; the volume of sequential scanning in the indexing stage falls accordingly, with more visible latency improvement in memory-bound scenarios; and the smaller cache makes tail latency for long requests and jitter in mixed workloads easier to control.

    Recommended metrics for quantitative evaluation (avoid looking at a single average):

    • Index-stage per-step latency at P50/P95/P99, plus end-to-end decoding throughput.
    • Peak memory and the share of memory taken by the index cache.
    • Recall quality: Recall@K (the overlap between compressed-domain recall and full scoring recall) and downstream task accuracy loss.
    • Long-context task performance: needle-in-a-haystack retrieval, multi-hop question answering, long-document summarization.
    • Stability: sensitivity to different group_size values, learnable versus fixed weights, and the ratio of enabled layers.

    A reusable evaluation skeleton:

    1. def evaluate(pool, indexer, cache_full, cache_pooled, q, k):
    2. top_full = indexer.topk(cache_full, q, k)
    3. top_pool = indexer.topk(pool(cache_pooled), q, k)
    4. recall = len(set(top_full) & set(top_pool)) / k
    5. return recall

    5. Common Misconceptions and a Tuning Checklist

    • Misconception one: compression always hurts accuracy. With a reasonable weight design and an unchanged Top-K budget, accuracy loss is controllable on most long-context tasks. The truly sensitive cases are tasks that require pinpointing a single exact token.
    • Misconception two: a higher compression ratio is always better. 4:1 is a fairly balanced trade-off; pushing the ratio higher weakens intra-group discrimination.
    • Misconception three: optimizing only at inference time. Letting the model adapt to compressed-domain scoring during training usually narrows the accuracy gap further.

    Tuning checklist: sweep group_size and weight schemes on a small sample first; do not enable pooling on accuracy-sensitive layers; set up residual group management for the pooling buffer; track index-stage latency and memory with monitoring and alerts; run stress tests with mixed long and short requests on a container platform or elastic resources.

    6. Cloud Deployment Notes

    In a cloud environment, long-context inference services can be deployed on a container platform, with object storage holding model and cache snapshots, a message queue smoothing request spikes, and logging plus monitoring alerts tracking P95/P99 latency and memory watermarks. General-purpose product categories from Baidu AI Cloud can serve as reference options for hosting such long-context inference services. Overall, weighted pooling compression of the index cache is a general optimization with small intrusion and clear gains, and it is worth validating first in million-token context scenarios.