Efficient Attention with Cross-Layer KV Reuse: Architecture Explained

    Long-context large language models face a core challenge that goes beyond parameter scale: attention repeatedly reads and writes historical state across layers. If every layer independently generates full Key/Value caches and performs dense retrieval, memory, bandwidth, and latency grow nearly linearly—or worse—with sequence length. A growing industry approach splits attention into "local exact + global sparse" paths, and decouples "historical content caching" from "historical position selection," allowing most layers to reuse existing global KV and Top-K results. This article walks through the actual path of a single token to explain how such architectures organize the encoder/decoder, compression ratios, and index update strategies.

    1. Overall Compute Path: Local First, Then Global, Then Layer-by-Layer Reuse

    Each Transformer layer can be viewed as one round of information filtering over the same residual stream. Denote the hidden state dimension as (d{\mathrm{model}}) (illustratively 5120), sequence length (S) (illustratively 1024), and batch size (B=1), so the main-path tensor is (X\in\mathbb{R}^{B\times S\times d{\mathrm{model}}}). Some implementations maintain multiple residual branches (mixed and projected back to the same dimension), but the interfaces before and after attention typically stay consistent, keeping compatibility with standard stacked-layer designs.

    A single attention step typically involves three parallel or sequential information channels:

    1. Sliding window attention (SWA): Looks only at a nearby window (illustratively 128 tokens), ensuring precise local interactions for syntax, coreference, and adjacent tokens. Each layer usually keeps its own SWA KV and main Query, because local patterns vary with depth and are not good candidates for sharing.
    2. Global sparse attention: Selects the Top-K key positions from the entire history (illustratively K=512) to capture long-range dependencies. Global KV is expensive, so only a few layers actually “generate new global KV.”
    3. Indexer: Scores positions using fewer heads and smaller head dimensions, deciding the Top-K set. The index can be updated separately from the content KV: when content is unchanged, only “where to look” is recomputed. This is the key idea behind compressed sparse attention (often referred to as CSA-style designs).

    2. Encoder Side: Full / Reuse / Reindex

    The first half of the encoder (illustratively 20 layers) typically interleaves three modes:

    • Full (F): Generates entirely new global KV from the hidden states at the current depth and computes a new Top-K. Suitable where semantic hierarchy shifts—for example, shallower layers lean toward lexical and local structure, while mid-to-deep layers capture phrase and discourse relations.
    • Reuse (R): Reuses both the global KV and the Top-K index. This is the cheapest mode, suited to regions where adjacent layers change little semantically.
    • Reindex (I): Reuses existing global KV but recomputes the Top-K. The meaning is “the historical content is still sufficient, but the current Query’s focus has shifted”—only the selection needs refreshing, not the entire global cache.

    A typical schedule: independent global KV is generated at spaced layers such as L2, L8, and L14. These come from hidden states at different depths, capturing shallow, middle, and deep tiers of history respectively. Most other layers Reuse, and a few Reindex. In a 40-layer network, only about 4 layers may actually write new global KV; about 8 layers perform new index selection (4 Full + 4 Reindex); and roughly 30 layers directly reuse the index. Meanwhile, all 40 layers can still retain their own SWA KV and main Query. History is thus split into two shared states: content cache (KV) and position selection (Top-K), with different lifecycles—this is precisely the benefit of decoupling content from index.

    3. Decoder Side: A Reindex-Driven Generation Path

    In autoregressive decoding, each step adds a token and the Query keeps changing, but the global KV already written often still represents a stable summary of the context. The Decoder therefore favors Reindex: instead of regenerating global KV, it reselects which historical slots to attend to based on the latest Query. Compression ratios can also differ from the Encoder’s—the Encoder side may apply ratio compression to the index or KV (illustratively ratio 2), while the Decoder may use ratio 1 to preserve generation quality, keeping the index more tightly aligned with the main attention. The design principle: amortize the one-time index-building cost during encoding, and minimize per-step bandwidth during decoding.

    4. Basic Dimensions and Query Generation (Illustrative)

    To make the path concrete, here is a common set of magnitudes (teaching illustration only, not any specific product’s specs): hidden dimension 5120; main attention with 64 heads and head dim 128, or low-rank expansion; Query latent space 1280; indexer with 32 heads and head dim 128; sparse Top-K = 512; SWA window 128.

    The Query typically uses two-stage projection to reduce activations:

    Stage one, low-rank compression:
    [
    Q_{\mathrm{latent}}=X W_q^{A},\quad
    [B,S,5120]\rightarrow[B,S,1280]
    ]

    Stage two, projection to main heads:
    [
    Q=Q_{\mathrm{latent}}W_q^{B}
    ]

    After producing the multi-head Query, one branch does windowed softmax against the SWA K/V, and another branch attends over the Top-K set against the global sparse K/V. The indexer can use a narrower (Q_{\mathrm{idx}}) to score compressed position representations and select global slots. Hierarchical sparse indexers can also coarse-filter before fine-ranking: the first stage uses lower dimensions or block-level statistics to shrink candidates, and the second stage performs Top-K within the candidates, avoiding high-dimensional scoring over the full sequence.

    5. Cross-Layer KV Reuse and Consistency Constraints

    Cross-layer reuse must address three issues:

    1. Numerical scale: LayerNorm and residual magnitudes differ across layers. Directly sharing KV requires either a shared set of projections or lightweight adaptation before reuse (linear or RMS alignment); otherwise, deep-layer Queries and shallow-layer K produce drifting inner products.
    2. Positional encoding: Rotary encodings such as RoPE must match the positions at which KV was written. When Reindex only changes the selection and not the content, positions remain bound to the original token indices; if the window slides or cache eviction occurs, the index mapping must be updated in sync.
    3. Training–inference consistency: If training truncates gradients for Reuse layers or uses straight-through estimation for the indexer, inference must use the same F/R/I schedule; otherwise, long-sequence quality degrades.

    In engineering practice, global KV can reside in high-bandwidth cache, while SWA KV uses per-layer ring buffers. The index can be stored as int16/int32 token or block IDs—far smaller than floating-point KV. The bandwidth bottleneck shifts from “every layer writing full global KV” to “occasional KV writes plus frequent reads of a small index.”

    6. Comparison with Standard Full Attention and Applicability Boundaries

    Full attention performs explicit (O(S^2)) interaction per layer—simple and reliable for short sequences. As (S) grows to several thousand tokens or beyond, SWA preserves local precision, sparse global attention retains long-range facts, and cross-layer reuse cuts redundant summarization. The tradeoff is scheduling complexity: which layers are Full, what compression ratio to use, and Top-K that is too small drops critical entities, while too large reverts to bandwidth pressure. In practice, the application layer can complement the model with object storage for long-document chunks, message queues for asynchronous index warm-up, and logging and monitoring to observe hit rates and tail latency—while the model’s internals keep the attention contract described above.

    7. Implementation Notes

    • Get SWA right first, then layer in sparse global attention, for easier ablation.
    • Tune the indexer’s and main attention’s RoPE base and scaling factors separately, to avoid long-term misalignment between scoring and the true attention distribution.
    • Adjust Reindex frequency per task: code completion and other local tasks can lean more on Reuse; multi-document QA may need more Reindex, or periodic Full passes to refresh discourse-level KV.
    • If mixed residuals involve multiple branches, attention input/output dimensions must align, to avoid broadcasting errors when reusing KV.

    In summary, the essence of efficient attention is not eliminating global information, but turning global state into a small, shareable, independently refreshable cache: a few layers “write history,” most layers “read history and update their focus,” and the local window handles “the current sentence.” Only by chaining SWA, CSA-style compressed sparsity, Full/Reuse/Reindex, and hierarchical indexing along the token path can you control both cost and quality in long-context settings.