Cross-Layer Sparse Attention Index Reuse: Reducing Long-Context Inference Costs

    This article examines the inference cost pressure created by long-context workloads and explains how sparse attention reduces computation by selecting only a subset of historical tokens for each query. It focuses on cross-layer index reuse: grouping Transformer layers so that the first layer in each group runs the full indexer and later layers reuse the selected top-k indices. The article covers the indexer workflow, a reference implementation pattern, qualitative cost-benefit tradeoffs, engineering considerations such as index tensor lifecycle and decoding behavior, validation risks, and guidance on when the approach is worth adopting.

    1. Background: Cost Pressure in Long-Context Inference

    As applications move from single-turn question answering to long-document analysis, code repository understanding, and multi-turn agent tasks, models need to handle increasingly long contexts. When context reaches the million-token scale, attention computation and the memory footprint of the key-value cache (KV Cache) both become major bottlenecks. Standard full attention requires every query to compute relevance against all historical positions, and the computational cost grows quadratically with sequence length.

    A common approach is therefore to reduce the number of tokens that actually participate in computation at each step, while minimizing any loss in quality. This is the goal of sparsification.

    2. Division of Labor Between Two Cost-Reduction Techniques

    2.1 Compressed Key-Value Representation

    Multi-head Latent Attention uses low-rank projection to compress keys and values into smaller latent vectors for storage. It primarily addresses cache size, reducing the memory footprint per token while retaining the expressiveness of multi-head attention.

    2.2 Sparsely Selecting Tokens for Computation

    Sparse attention first uses a lightweight indexer to score the current query, selects the most relevant subset of historical tokens (top-k), and then performs exact attention computation only over those positions. The two techniques can be combined: the former reduces the storage per token, while the latter reduces computation at each step.

    3. How the Indexer Works

    An indexer typically consists of three parts:

    • A set of lightweight projections that map the query and historical tokens into a low-dimensional space;
    • A scoring function that computes relevance scores between the query and each historical position;
    • A top-k selection step that outputs the indices of the selected positions.

    The following schematic code illustrates the selection process. It is not a specific implementation.

    1. import numpy as np
    2. def select_topk_indices(query, key_cache, k):
    3. # query: [heads, dim_small], key_cache: [seq_len, dim_small]
    4. scores = (query @ key_cache.T).max(axis=0) # Lightweight scoring with heads merged
    5. topk = np.argpartition(-scores, k)[:k] # Select the k positions with the highest scores
    6. return topk

    The indexer itself still has to traverse the entire historical sequence. Its overhead is lower than that of full attention, but it cannot be ignored on long sequences.

    4. The Key Issue: Repeated Index Computation Across Layers

    A Transformer is built from stacked layers. If every layer runs the indexer independently, the same historical sequence is scored repeatedly, and the computational cost grows linearly with the number of layers.

    In many models, adjacent layers attend to positions that overlap substantially. This phenomenon provides a basis for reuse. The exact degree of overlap needs to be measured on the target model and cannot be assumed directly.

    5. Design for Cross-Layer Index Reuse

    The core approach is to divide layers into groups. The first layer in each group runs the full indexer and outputs top-k indices; subsequent layers in the group directly reuse those indices and skip the scoring and selection steps. Attention computation itself is still performed independently in each layer. Only the basis for selecting positions is shared.

    One feasible configuration is to run full indexing in the first layer of every four layers and let the other three layers reuse its result. Schematic code is shown below:

    1. def forward_layers(hidden, layers, group_size=4):
    2. shared_indices = None
    3. for i, layer in enumerate(layers):
    4. if i % group_size == 0:
    5. # First layer in the group: full index computation
    6. shared_indices = layer.indexer(hidden)
    7. # Layers in the group: reuse indices and run sparse attention only
    8. hidden = layer.sparse_attention(hidden, shared_indices)
    9. return hidden

    This design has three key points:

    • Adjustable granularity: The group size is a hyperparameter. A larger group saves more index computation, but the indices used by later layers may deviate further from their actual needs.
    • Clear sharing scope: Only the indices of selected positions are shared, not the attention outputs. Each layer still uses its own queries and projections, so expressiveness is not affected.
    • Boundary handling: When sequence length changes, or when one token is added at each step during autoregressive decoding, the indices need incremental updates or periodic refreshes.

    6. Qualitative Cost-Benefit Analysis

    Let the total number of layers be L and the group size be g. The number of full indexing runs drops from L to approximately L/g. The longer the sequence, the higher the indexer’s share of total latency, and the more noticeable this saving becomes.

    Two points need attention. First, reuse reduces only index computation. It does not reduce the computation of attention itself, nor does it reduce KV cache occupancy. Second, the actual saving ratio depends on the indexer’s share of total latency as well as on hardware and operator implementations. These factors vary considerably, so measured results should be the basis for decisions.

    7. Engineering Implementation Notes

    1. Measure before optimizing: Separately profile the latency and memory of the indexer, sparse attention, and linear layers. Confirm where the bottleneck is before deciding whether to introduce reuse.
    2. Standardize index tensors: The index tensor shape is typically [batch, query_len, k]. Plan its lifecycle and release it promptly after use within a group to avoid raising peak memory.
    3. Handle the decoding phase: During autoregressive generation, only one token is added at each step. Either incremental index updates or fixed-interval refreshes can be used.
    4. Consider training consistency: If reuse is introduced at inference time, it is best to account for this strategy during training or fine-tuning to reduce distribution shift between inference and training.
    5. Match the distributed layout: Under cross-device parallelism, indices must remain consistent with the corresponding key-value shards to avoid transmitting excessively large intermediate results.

    8. Quality Validation and Risks

    • Accuracy regression: Compare full indexing and reused-index versions on tasks such as long-context retrieval, multi-hop question answering, and code understanding.
    • Layer-by-layer error accumulation: Record differences between each layer’s output and the baseline, and observe whether errors amplify with network depth.
    • Boundary cases: When critical information happens to fall on a group boundary or is ignored by a previous group, quality may drop noticeably. Build dedicated test sets to cover such cases.
    • Metric combination: In addition to accuracy, monitor first-token latency, throughput, and peak memory to avoid optimizing only a single metric.

    9. Applicable Scenarios and Deployment Recommendations

    • Scenarios with greater benefit: Tasks requiring very long context, such as long-document question answering, large-scale code analysis, and long-conversation memory, often have a high index overhead, making reuse most valuable.
    • Scenarios with limited benefit: In short-context tasks, the index overhead is a small fraction, and the added complexity of reuse may not be worthwhile.
    • Recommended deployment order: First find an acceptable group size on an offline evaluation set, then roll out to a small traffic share, and keep a switch to revert to full indexing so that issues can be rolled back quickly.

    10. Summary

    Sparse attention addresses which tokens should be computed at each step. Cross-layer index reuse further reduces the repeated computation of those selections across layers. It does not change the basic idea of attention; instead, it exploits similarity between adjacent layers to reduce redundancy. Deployment should be based on measured data, finding the right balance between inference cost and output quality for the business.