Index Cache Compression for Sparse Attention in Long Contexts

    Long-context inference shifts the cost of attention from model size back to sequence length. Once the context reaches hundreds of thousands or millions of tokens, full attention's quadratic cost is usually unacceptable, so production systems tend toward hybrid architectures: linear or recurrent state for local dependencies, sparse attention to recall distant key spans when needed. This article explains why the indexer, not the main attention, becomes the bottleneck in such systems, and how four-to-one weighted pooling compresses the index cache to roughly one quarter of its length. It covers the indexer's three hard constraints, how weights should be computed cheaply, how memory, prefill and decode latency, and numerical scale shift after compression, the loss of token-level recall granularity and the two-stage retrieval design that compensates for it, plus cache layout, distributed sharding, observability metrics, applicability limits, and a low-to-high risk rollout order.

    Long-context inference pulls the cost of attention back from “how big the model is” to “how long the sequence is.” Once the context grows to hundreds of thousands or even millions of tokens, the quadratic cost of full attention is usually unacceptable. The more common engineering answer is a hybrid architecture: linear or recurrent state captures local dependencies, while sparse attention recalls critical distant spans when necessary. Whether the sparse path is both fast and accurate depends largely on the indexer. It does not replace the main attention; it maintains a searchable cache that decides which historical positions are worth recalling.

    The indexer itself is usually designed to be lightweight, but the cache grows linearly with the sequence. Once every position or time step writes a few vectors, bandwidth, memory footprint, and retrieval latency all rise together at million-token lengths. The main model has already been sparsified, yet the bottleneck moves to “the index that serves sparsification.” Compressing the index cache is therefore a different optimization axis from scaling the model or extending the window: the goal is not to redefine recall semantics, but to reduce the storage and compute needed to maintain them.

    What the Indexer Does in a Hybrid Architecture

    Linear attention and recurrent state suit continuous, local patterns: syntax between adjacent tokens, coreference, and short-range facts can be absorbed by a fixed-size state through recurrence, at a per-step cost that is roughly independent of sequence length. The weakness is that distant information gets diluted by state mixing, making it hard to point precisely at a single piece of evidence after a million tokens.

    Sparse attention fills that gap. Instead of scoring the entire history densely, the system first asks the indexer for candidate positions or blocks, then applies heavier attention only at those locations. The index cache can be understood as a “searchable summary of history”: on write, the representation of the current position is folded into the cache; on query, the current hidden state is compared against the cache by similarity or gating to select a small amount of global context.

    Under this division of labor, the indexer has three hard constraints. First, writes must be cheap, or the prefill stage will be slowed by cache updates. Second, the cache must be accessible randomly or by block, or recall cannot jump to distant positions. Third, compression must not destroy discriminability, or the wrong spans get recalled and the precision of the subsequent sparse attention no longer helps. Weighted pooling compression mainly targets the capacity problem created by the second point, while having to hold the third.

    What Four-to-One Weighted Pooling Solves

    One direct strategy is to merge every four consecutive cache vectors into a single vector, shrinking the index cache to roughly one quarter of its length and reducing memory and sequence-dimension retrieval cost accordingly. What matters is not the four-to-one ratio itself, but whether the merge is weighted by importance.

    A simple average treats the four positions as equal contributors. In long documents, information density across adjacent tokens is often uneven: some are function words or repeated phrasing, others carry entities, numbers, or turns in the argument. With equal weighting, high-information positions get diluted by their neighborhood, and the indexer has a harder time aligning that block with the current question at query time. Weighted pooling first estimates a weight for each of the four vectors, then computes a normalized weighted sum, so each cache slot lands closer to “the direction most worth remembering from this short span.”

    Weights can come from several signals that are decoupled from any specific implementation, such as vector norms, similarity to a representative vector within the segment, or a tiny gate that scores each position. The principle is that the cost of computing weights must be clearly lower than the cache bandwidth saved, otherwise the compression does not pay off. Pooling happens on the write path, and the read path sees a shorter cache; on the query side, similarity computation shifts from aligning four fine-grained vectors to aligning one segment-level vector, so compute drops roughly in proportion to segment length, but recall granularity also falls back from token level to segment level.

    Schematically, the write can be expressed in the following framework-agnostic form:

    1. # Merge every 4 cache vectors into 1 slot
    2. group = cache[-4:] # [4, d]
    3. scores = score_fn(group) # [4]; cost must be far below main attention
    4. weights = softmax(scores)
    5. slot = sum(weights[i] * group[i]) # [d]
    6. compressed.append(slot)

    Here score_fn should stay lightweight, for example a linear projection plus a scalar gate, avoiding the introduction of another attention mechanism on the scale of the main model. softmax guarantees positive weights summing to one, and the merged slot still lives in the original representation space, so downstream retrieval kernels do not need a dimension change.

    How Compression Ratio, Latency, and Memory Move Together

    Four-to-one does not automatically mean a fourfold end-to-end speedup. The index cache is usually only part of the inference graph, and the benefit depends on its share of the critical path.

    The memory side is more straightforward. If the cache is stored per sequence length and the dominant term is index vectors rather than the main KV, the number of slots drops to about one quarter and memory falls by roughly the same ratio. If positions, block boundaries, or auxiliary statistics are also stored, those side structures should be aligned to segments too, otherwise metadata dilutes the gain. At million-token lengths it is not unusual for the index cache to grow from “negligible” to “comparable to the main state,” and at that point one quarter is often the dividing line between fitting the context on a single device and paying for swapping in and out.

    Latency has to be split between prefill and decode. During prefill, weighting and reduction are extra compute, but they reduce subsequent writes and possible cross-device transfers; if the original bottleneck was memory bandwidth, one merged write is often friendlier than four fine-grained writes. During decode, each step retrieves against the entire index history, and the number of comparisons falls with cache length, so four-to-one directly shortens the working set of that scan or approximate nearest-neighbor search. If retrieval already uses blocking, locality-sensitive hashing, or a hierarchical index, compression changes the number of underlying vectors, and the upper-level structure must be rebuilt for the new segment length; you cannot assume the old block size is still optimal.

    The numerical path also deserves attention. Weighted summation can change vector norms, so if retrieval uses unnormalized dot products, the score scale after compression will shift, and thresholds or top-k need to be recalibrated against the segment-level distribution. Cosine similarity or an upfront L2 normalization gives a more stable scale, but normalization itself has a cost and should be done once offline or at write time, not repeatedly over the whole cache at query time.

    Information Retention and Recall Granularity

    The cost of four-to-one is temporal resolution. Once four tokens share a slot, the indexer can only point a query at “this short span” and cannot distinguish which token inside it. If the downstream sparse attention still reads the original representations or original KV of the hit segment, fine-grained alignment can be deferred to a second stage: the index does coarse recall, and the main attention does intra-segment ranking. This two-stage design matches cache compression, because what compression loses is index resolution, not necessarily the resolution of the final attention.

    If the system has no second stage and the hit segment is the only context, the compression ratio must be more conservative, or pooling should be widened only in low-information regions. A common practical compromise is variable-length segmentation: use cheap boundary signals (punctuation, paragraphs, special markers, abrupt hidden-state changes) to split semantic blocks, then apply weighted pooling within each block, instead of mechanically cutting every four tokens. Fixed four-to-one is simple to implement with a regular memory layout and works well as a baseline; variable-length segmentation fits document structure better but produces irregular tensors that require extra handling in kernels and memory allocation.

    The weighting itself can also go wrong. If the gate systematically favors the first or last token of a segment, the cache degrades into “remembering only boundaries” and key sentences in the middle are dropped. Before shipping, check with controlled probe tasks: given a fact that appears only at a specific position inside a segment, does the query still hit the corresponding slot? If the hit-rate drop concentrates at a fixed offset, it is most likely weight bias rather than an excessive compression ratio.

    Fitting Compression into Training, Cache Layout, and Inference Systems

    Compression can be applied at inference time only, or the indexer can be trained to see the compressed cache. Inference-only compression is quick to implement, but the query distribution then diverges from training and recall quality may regress. The safer route is to use the same pooling in the index branch during training, so the scoring function learns what a segment-level vector looks like. The main model’s dense or sparse loss does not need to be tied to any particular vendor implementation; it is enough that the index loss and the recall-position supervision use the same granularity.

    For memory layout, writing four vectors and reducing them immediately still peaks near the uncompressed footprint. A better approach is to accumulate the weighted sum directly while writing into a ring or block buffer, committing one slot once four contributions are in. The resident cache is then allocated at the compressed length. If positional encoding is bound to token indices, each slot should record a representative position for the segment (for example a weighted center or the segment start) so retrieval does not use a wrong relative distance.

    In distributed inference, the index cache is often sharded across devices along the sequence. After compression each device holds fewer slots and cross-device retrieval moves less data, but segment boundaries should not fall in the middle of a device boundary, or the four source vectors of one slot end up on different cards and the reduction introduces synchronization. Treating the segment as the atomic unit for sequence parallelism is usually cleaner than treating the token as the atomic unit.

    Observability needs the same segment-level rework. Cache hit rates, score histograms, and eviction policies previously tracked per token should gain segment-level metrics: slot weight entropy (whether it has degenerated into one-hot), whether intra-segment information is actually used by the second stage, and top-k overlap before and after compression. Without these metrics you can only see memory drop, and cannot tell whether quality was quietly traded away.

    Applicability and Rollout Order

    This approach fits hybrid attention systems where the index cache grows linearly with context and segment-level coarse localization is acceptable for recall, especially when the target window is already at the million-token scale and bandwidth and memory hit their limits before compute does. It does not fit retrieval that must localize token by token with no reranking stage, nor small models with short contexts where index vectors are so short that the bytes saved by compression do not cover the weighting cost.

    A rollout ordered from lowest to highest risk: first apply four-to-one weighting on offline traces, comparing top-k overlap and downstream answer consistency against the uncompressed index, and confirm the score scale; then switch writes to incremental reduction and check the memory peak; finally share the same pooling between training and inference, with positions and parallel sharding aligned to segments. The ratio of four is just a practical starting point that matches “merging several adjacent vectors into one slot”; if overlap is insufficient, improve the weights or move to semantic segmentation first rather than increasing the compression ratio.

    Leaving local dependencies to linear or recurrent state and global recall to a compressible index cache is a clear path to controlling cost in long-context systems. The value of weighted four-to-one is that it trades a controlled loss of resolution for roughly one quarter of the index cache capacity and a correspondingly smaller retrieval working set, while keeping true fine-grained alignment after the hit. As long as the weights are lightweight, the scale is calibratable, and training and inference share the same granularity, this compression can serve as a routine engineering technique for long-sequence sparse attention rather than a one-off trick.