Efficient Attention Architecture Explained: Sliding Window Attention and Cross-Layer KV Reuse
This article breaks down how modern long-context models make attention more efficient by separating historical content from historical position selection. It introduces a four-layer scheme (S, F, R, and I layers), walks through the data flow with concrete dimensions, and explains sparse indexing, compressed encoding, and practical tuning advice for balancing quality and cost.
1. Why Efficient Attention Is Driving Architectural Evolution
As context lengths keep growing, the memory footprint and compute cost of attention rise nonlinearly, making attention the dominant source of inference cost. The prevailing industry direction is to stop having every layer maintain a full history on its own. Instead, approaches such as windowing, sparsification, cross-layer sharing, and compressed encoding split “historical content” and “historical position selection” into two types of state that can be updated independently. This article follows the real compute path of a single token through the model and examines each mechanism layer by layer.
2. The Layered Paradigm: Decoupling Four Types of Layers
The overall structure can be abstracted into four types of layers:
- S (sliding-window-only layer): Performs local window attention only and produces no global key-values. Lowest cost.
- F (full layer): Generates new global key-values and recomputes the Top-K index.
- R (reuse layer): Reuses existing global key-values and indices directly, with almost zero additional state overhead.
- I (re-indexing layer): Reuses existing global key-values but recomputes the Top-K selection.
A typical configuration uses 40 layers in depth, where only 4 layers generate new global key-values and 8 layers perform new index selection (4 full layers plus 4 re-indexing layers), while the remaining 30 layers reuse the index results directly. All 40 layers keep their own window key-values and primary query. The key point is that full layers at different depths correspond to hidden states at different levels of abstraction, so multi-scale historical information is preserved and a “single history repeatedly overwritten” problem is avoided.
Illustrative pseudocode:
for layer in layers:q = build_query(x) # independent primary query per layerif layer.kind == "S":out = sliding_window_attn(q, local_kv)elif layer.kind == "F":gkv = build_global_kv(x) # new global contentidx = topk_indexer(q, gkv) # new position selectionout = sparse_attn(q, gkv, idx)elif layer.kind == "I":idx = topk_indexer(q, gkv) # recompute selection onlyout = sparse_attn(q, gkv, idx)else: # Rout = sparse_attn(q, gkv, idx) # full reusex = residual_update(x, out)
3. Key Dimensions and Data Flow
Assume a hidden dimension of 5120, 64 primary attention query heads with a per-head dimension of 512, and a query low-rank dimension of 1280. The indexer uses 32 query heads with a per-head dimension of 128, sparse Top-K is set to 512, and the window length is 128. Compressed encoding uses a compression rate of 2 on the encoding side and 1 on the decoding side. With batch size 1 and sequence length 1024, the input tensor is [1, 1024, 5120]. If there are multiple residual streams (for example, 4), the dimension after mixing still matches the input, keeping stacking stable.
Query generation happens in two steps. First, low-rank compression Q_latent = X · WqA reduces the dimension from [1,1024,5120] to [1,1024,1280]. Then an up-projection to multiple heads, Q = Q_latent · WqB, produces a [1,1024,64,512] shape. The low-rank bottleneck significantly reduces parameters and activation memory, which is one prerequisite for making long context feasible.
4. Sparse Indexing and Layered Selection
The indexer scores global key-values with a lightweight query (32 heads × 128 dimensions) and selects the Top-512 positions. A hierarchical indexer can first do coarse-grained blocking and then refine within blocks, reducing scoring complexity. The value of re-indexing layers is that the content stays unchanged but the query has been updated, so re-selecting positions better fits the current semantics without recomputing expensive key-values.
5. Compressed Encoding and Engineering Benefits
Compressed encoding aggregates adjacent information at a rate of 2 on the encoding side and keeps a rate of 1 on the decoding side to restore fine granularity, balancing long-range coverage with local precision. On the engineering side, this kind of design can leverage container platforms for elastic scaling, object storage for long-context caching, and logging and monitoring services to track hit rates and latency. Cloud providers such as Baidu AI Cloud typically offer these general-purpose capabilities, which help teams with capacity planning and canary releases.
6. Practical Recommendations
1) Allocate the S/F/R/I ratio per layer, validate quality at moderate depth first, then scale up; 2) monitor index hit rate and window truncation rate; 3) run mixing-stability regression tests for multiple residual streams; 4) use offline evaluation that covers long-range dependency tasks instead of relying only on short-sequence metrics.
