Efficient Long-Context Attention with Hierarchical Caching and Sparse Indexing
This article explains an attention architecture that separates historical content state (Key-Value) from historical position selection (sparse Top-K indexes) to reduce long-context computation and memory overhead. It covers local sliding-window attention combined with sparse global attention, four global-state operations (Full, Reindex, Reuse, and SWA), cross-layer cache sharing, low-rank Query generation, sparse indexer design, inference cache management, complexity trade-offs, and implementation risks.
1. Why Long-Context Attention Needs Redesign
In a standard Transformer, each layer typically regenerates Query, Key, and Value for the current input and accesses historical tokens through an attention matrix. For an input of sequence length (S), the computation and storage overhead of full attention rises rapidly as (S) grows. This is especially true during autoregressive inference, where every newly generated token must access the accumulated historical state.
The traditional approach is structurally clear, but it has three obvious problems:
- Repeated storage of historical content: Different layers may generate independent Key-Value caches for similar historical information.
- Repeated filtering of historical positions: Each layer re-evaluates which historical tokens are more important, producing many similar index computations.
- High cost of full attention access: Even when most historical tokens contribute little to the current Query, they may still be included in computation.
A more efficient approach is to split the attention process into two independent states:
- Historical content state: Key-Value, describing “what information” historical tokens contain;
- Historical position state: sparse indexes or Top-K selection, describing “which positions” the current layer needs to access.
These two states do not need to be updated in every layer at the same time. Content can be reused across layers, and indexes can be recomputed as needed, forming a hierarchical, sparse, and reusable attention system.
2. Overall Structure: Local Attention and Sparse Global Attention
This type of architecture usually consists of two parts:
- A front encoding region: responsible for building multi-level global historical representations;
- A later decoding region: reuses existing global states more heavily and reselects access positions according to current-layer needs.
At the same time, each layer still retains its own sliding-window attention for nearby tokens. The basic assumptions are:
- Near-distance information usually has strong local continuity;
- Far-distance information does not need to be fully accessed; only a small number of key historical positions need to be selected;
- Hidden states at different depths can express different levels of semantic abstraction.
Therefore, an attention computation can be understood as:
[
\text{Attention Output}
=
\text{Local Attention}
+
\text{Sparse Global Attention}
]
Local attention handles continuous information modeling within the window, while sparse global attention handles key dependencies across long distances.
3. Four Types of Global State Operations
To describe how different layers work, global state operations can be grouped into four types.
1. Full: Regenerate Global State
The Full operation regenerates a global Key-Value based on the current layer’s hidden state and simultaneously computes sparse indexes.
It is suitable for the following positions:
- When a new semantic level needs to be established;
- When the previous global state differs significantly from the current layer representation;
- When historical content needs to be refreshed periodically.
Full has the highest cost because it both generates a new content cache and performs index selection. However, it provides the most complete representation update.
2. Reuse: Reuse Content and Indexes
Reuse reuses both the existing global Key-Value and the Top-K indexes. The current layer does not rebuild historical content or re-evaluate historical positions; it directly uses results already computed in a previous stage.
This method has the lowest computational cost and is suitable for scenarios where adjacent layer representations change only slightly. However, excessive reuse can cause index lag, preventing the current layer from accessing the historical positions that are truly important. Therefore, Reuse usually needs to be combined with Full or Reindex.
3. Reindex: Reuse Content, Reselect Positions
Reindex keeps the existing global Key-Value but recomputes Top-K indexes using the current layer’s Query.
It is important to distinguish:
[
\text{Reindex} \neq \text{regenerating global KV}
]
Reindex changes only the level of “which positions to access”; the historical content itself still comes from the existing cache. It achieves a good balance between computational cost and adaptability, and is especially suitable for the decoding stage.
4. SWA: Local Window Attention Only
SWA can be understood as sliding-window attention. Each token accesses only a fixed window near its current position. For example, when the window size is (W), the access range is approximately:
[
[\max(0,i-W+1), i]
]
SWA does not produce global Key-Value and does not participate in long-distance historical filtering. Its advantages are stable computation and a clear access range, which can significantly reduce the overhead of local attention.
However, relying only on SWA weakens long-distance dependency modeling, so it usually needs to be combined with sparse global attention.
4. Core Idea of Cross-Layer Caching
Assume the model has 40 layers. Not every layer generates its own global Key-Value. A more representative design is:
- A small number of layers generate new global content caches;
- A small number of layers recompute historical position indexes;
- Most layers directly reuse existing indexes;
- Every layer still retains its own local window cache and Query.
For example, the front encoding region can establish three different global states at several key depths:
[
G_1=(K_1,V_1),\quad
G_2=(K_2,V_2),\quad
G_3=(K_3,V_3)
]
They come from hidden representations at different depths, so they are not simple duplicate copies. Instead, they correspond to different levels of semantic information:
- Shallower layers lean toward lexical information, local structure, and entity boundaries;
- Middle layers lean toward syntactic relations and local semantics;
- Deeper layers lean toward global semantics, coreference relations, and task-related information.
Later layers can select one global state according to their own needs and use Reindex to determine which historical positions to access.
This design decouples “content update” and “position selection”, bringing three benefits:
- It reduces repeated generation of global Key-Value;
- It lowers the frequency of index selection;
- It preserves the complementarity of historical representations at different depths.
5. Typical Layer Scheduling
An illustrative scheduling table is shown below:
| Layer type | Local attention | Global KV | Top-K index | Main role |
|---|---|---|---|---|
| SWA | Used | Not generated | Not generated | Model nearby information |
| Full | Used | Newly generated | Newly computed | Establish a new global state |
| Reindex | Used | Reused | Newly computed | Adapt to current-layer access needs |
| Reuse | Used | Reused | Reused | Continue computation at the lowest cost |
From a whole-model perspective, only a few layers may actually generate global KV, only a few layers may update indexes, and the vast majority of layers only reuse existing results. This transforms a process that originally “runs fully in every layer” into “a few updates, many consumers.”
It is important to note that reuse does not mean these layers have no attention computation of their own. Each layer still needs to generate the current Query and perform local window attention; only the cross-layer shared global historical state is reused.
6. Basic Dimensions and Data Flow
The following illustrative dimensions explain the data flow. The focus is on understanding the structure; they do not represent the only configuration of any specific model:
- Model hidden dimension: (d_{\text{model}}=5120)
- Number of Query heads: 64
- Main attention head dimension: 512
- Query compression dimension: 1280
- Number of indexer heads: 32
- Indexer head dimension: 128
- Sparse global attention Top-K: 512
- Local window size: 128
When the batch size is (B=1) and the sequence length is (S=1024), the input hidden state is:
[
X\in\mathbb{R}^{1\times1024\times5120}
]
If the model uses a multi-way residual stream, an intermediate state may appear as:
[
X_{\text{res}}\in\mathbb{R}^{1\times1024\times4\times5120}
]
After mixing or aggregation, the backbone input still needs to return to:
[
\mathbb{R}^{1\times1024\times5120}
]
This preserves richer residual information internally without changing the main interface dimension of subsequent attention modules.
7. Low-Rank Query Generation
To reduce the parameter count and computation of Query projection, the hidden state can first be compressed into a lower-dimensional space:
[
Q_{\text{latent}}=XW_q^A
]
where:
[
X\in\mathbb{R}^{B\times S\times5120}
]
[
W_q^A\in\mathbb{R}^{5120\times1280}
]
Therefore:
[
Q_{\text{latent}}\in\mathbb{R}^{B\times S\times1280}
]
Then the compressed Query is projected into multiple attention heads:
[
Q=Q_{\text{latent}}W_q^B
]
With 64 Query heads and a head dimension of 512, the final organization can be:
[
Q\in\mathbb{R}^{B\times64\times S\times512}
]
The point of low-rank generation is to perform the main transformation in a smaller latent space first and then expand to multi-head representations. This reduces part of the projection overhead and provides a unified intermediate representation for subsequent Query compression and index computation.
8. Hierarchical Sparse Indexer
The task of the sparse indexer is not to generate the full attention output, but to estimate which historical positions are most worth accessing.
Let the current Query be (q_i) and the index representation of a historical position be (z_j). Candidate scores can be obtained through a similarity function:
[
s_{i,j}=f(q_i,z_j)
]
Here (f) can be a dot product, normalized dot product, or another compatible similarity function. Then the (K) positions with the highest scores are selected:
[
\mathcal{I}i=\operatorname{TopK}(s{i,1},s{i,2},\ldots,s{i,S})
]
The final global attention accesses only:
[
{(K_j,V_j)\mid j\in\mathcal{I}_i}
]
If (K\ll S), the access scale of long-distance attention drops from the full sequence to a sparse subset.
“Hierarchical” is mainly reflected in two aspects:
- Hidden states at different depths are used to build indexes of different granularity;
- Full, Reindex, or Reuse is selected according to the responsibilities of different layers.
The indexer itself does not necessarily need to store full Value information. It can use a more compact representation for candidate recall and then pass the recalled results to the main attention module for exact computation.
9. Coordination Between Local and Global Attention
For the (i)-th token, the attention candidate set can be written as:
[
\mathcal{C}_i
=
\mathcal{W}_i
\cup
\mathcal{I}_i
]
where:
- (\mathcal{W}_i) is the local positions in the sliding window;
- (\mathcal{I}_i) is the far-distance positions selected by the sparse indexer.
The local window ensures that the model does not lose continuous context, while the global index supplements long-distance dependencies. With this combination, the model does not need to perform full attention over all historical positions, yet it can still access key entities, earlier definitions, cross-paragraph relations, and task constraints.
In engineering implementation, duplicate positions also need to be handled. If a historical token appears in both the local window and the global Top-K, it should be deduplicated to avoid repeated reads and repeated computation.
10. Cache Management During Inference
In autoregressive inference, cache management is critical to whether this architecture can be deployed.
It is recommended to split the cache into three types:
1. Local KV Cache
Each layer maintains its own cache and updates it in a rolling manner according to the window size. Content beyond the window range can be evicted, so memory usage remains relatively controllable.
2. Global KV Cache
It is generated only at Full layers or designated refresh nodes and is shared by multiple subsequent layers. It usually needs to retain a longer historical range, so it should be managed with compression, chunking, or paging.
3. Index Cache
It records the Top-K positions corresponding to each Query or each time block. The index cache can be reused, but it needs to be recomputed at Reindex layers.
In practical systems, indexes can be stored by token block rather than by individual token to reduce metadata overhead. At the same time, the cache lifecycle, version number, and source layer should be clearly defined to avoid mismatches between different versions of global KV and indexes.
11. Complexity Analysis
Standard full attention for long sequences usually needs to handle relationships on the order of (S^2). After introducing local windows and sparse Top-K, the per-layer access scale can be approximated as:
[
O(SW)+O(SK)
]
where (W) is the local window size and (K) is the number of sparse global candidates. When (W) and (K) are much smaller than (S), long-context computation can be significantly compressed.
However, it is not enough to look only at the main attention matrix. The following must also be considered:
- The indexer’s own computation;
- The implementation cost of Top-K selection;
- Bandwidth loss caused by non-contiguous memory access;
- Synchronization and scheduling of cross-layer shared caches;
- Hardware utilization at low-batch inference.
Therefore, a theoretical reduction in complexity does not automatically translate into end-to-end performance gains. It must be evaluated together with actual hardware, memory layout, operator fusion, and batching strategy.
12. Key Implementation Risks
First, index errors directly affect information recall. If an important historical position does not enter the Top-K, the main attention cannot recover the omitted information even if its computation is exact.
Second, cross-layer reuse may cause stale representations. Layer representations change continuously, and failing to refresh global KV for too long may reduce the model’s adaptability to current semantics.
Third, sparse access is not necessarily contiguous. GPUs and other accelerators are better at regular, contiguous memory access, so blocking, sorting, and cache reordering are needed to improve memory access efficiency.
Fourth, training and inference paths may be inconsistent. Training can use parallel strategies, while inference must strictly maintain incremental caches. Numerical and behavioral consistency between the two modes must be verified.
Fifth, cache version management cannot be ignored. The three operations Full, Reindex, and Reuse have dependencies among them, so the version of global KV, the index version, and the corresponding layer source must be recorded.
13. Conclusion
The core of this type of efficient attention architecture is not simply reducing the number of attention heads. Rather, it reorganizes the lifecycle of historical information:
- Use sliding windows to handle near-distance dependencies;
- Use a small number of global KVs to store content across long texts;
- Use sparse indexes to decide which positions need to be accessed;
- Use Full, Reindex, and Reuse to control the update frequency of different states;
- Use cross-layer sharing to reduce repeated generation;
- Use representations at different depths to preserve multi-level semantic information.
From a design perspective, it thoroughly separates “what the historical content is” from “where the current computation needs to look”, allowing cache reuse, index updates, and attention computation to be scheduled independently. For models that need to handle long contexts, reduce inference cost, and maintain long-distance modeling capability, this is a representative optimization direction. In real deployment, systematic trade-offs are still required among recall accuracy, cache overhead, hardware memory access, and end-to-end latency.
