---
title: Shared-KV Gated Sliding-Window Attention
url: https://www.emergentmind.com/topics/shared-kv-gated-sliding-window-attention
type: topic
---

# Shared-KV Gated Sliding-Window Attention

Searching arXiv for the cited works to ground the article in the relevant papers.
Found the primary paper on hybrid sparse attention and learnable token eviction. Searching for related Shared-KV gated sliding-window formulations.
Shared-KV Gated Sliding-Window Attention denotes a family of sparse-attention constructions that preserve the linear-time, linear-memory profile of sliding-window attention while improving memory access or memory dynamics through KV sharing and gating. In the cited literature, this family appears in at least two technically distinct forms: a hybrid sparse-attention design in which a sliding window is augmented by a learned cache of retained distant KV-pairs selected by a contextualized gating module [2510.20787], and a FlashAttention-compatible sliding-window mechanism in which a per-token gate is accumulated into a decay bias on the attention logits, yielding a learnable contraction of the induced associative-memory recurrence [2512.07782]. A related systems-oriented precursor is MixAttention, which combines sliding-window attention with KV-cache sharing across layers to reduce inference memory and improve throughput, and whose summary explicitly treats gating only as an optional extension rather than as part of the base mechanism [2409.15012].

## 1. Problem setting and lineage

The motivating problem is the tension between efficient sequence modeling and direct token retrieval. Pure linear-attention models compress the entire input sequence into a fixed-size recurrent state and therefore operate in constant time and space per token, but their finite memory induces forgetfulness that harms retrieval-intensive tasks [2510.20787]. Full Softmax attention restores direct access to all past KV-pairs, but incurs \(O(N)\) cost per token and \(O(N^2)\) cost overall. Sliding-Window Attention (SWA) occupies an intermediate regime: each query attends only to the most recent \(w\) tokens, sometimes augmented with a small set of global tokens, so its per-token time and space are \(O(w)\), constant when \(w\) is fixed [2510.20787].

Within this design space, “Shared-KV” addresses a second systems bottleneck: the cost of storing and indexing keys and values. MixAttention formalizes one form of sharing by computing new \(K,V\) only in selected “compute-KV” layers and reusing them in other layers, while also restricting attention to a sliding window of size \(s\) [2409.15012]. The later gated variants keep the sliding restriction but add either selective retention of out-of-window KV-pairs or a learnable decay bias inside the window [2510.20787, 2512.07782].

This suggests that Shared-KV Gated Sliding-Window Attention is best understood as a design family organized around three recurring objectives: retain SWA’s asymptotic efficiency, reduce KV-cache overhead through sharing or compaction, and recover some of the long-range utility that plain SWA loses once tokens exit the window.

## 2. Sliding-window attention as the base operator

In the hybrid sparse-attention formulation, let the sequence length be \(N\) and let the per-head query, key, and value matrices satisfy \(Q,K,V\in\mathbb{R}^{N\times d}\). For head \(h\) and position \(i\), the sliding-window index set is defined as
\[
\mathcal{W}_i=\{\,j:\max(1,i-w)<j\le i\,\}\cup\{1,\dots,s\},
\]
where \(s\) is the size of a small attention sink of global tokens [2510.20787]. The corresponding attention weights and head output are
\[
\alpha_{i,j}^{(h)}=
\frac{\exp\bigl(q_i^{(h)\,\top}k_j^{(h)}/\sqrt{d}\bigr)}
{\sum_{j'\in\mathcal{W}_i}\exp\bigl(q_i^{(h)\,\top}k_{j'}^{(h)}/\sqrt{d}\bigr)},
\qquad
y_i^{(h)}=\sum_{j\in\mathcal{W}_i}\alpha_{i,j}^{(h)}v_j^{(h)}.
\]
In matrix form for a query tile, this is the usual Softmax–MatMul restricted to \(\mathcal{W}_i\) [2510.20787].

MixAttention adopts the same basic locality principle, but places it in a layer-sharing framework. Its sliding-window index set for token \(i\) in layer \(\ell\) is
\[
W_i^{(\ell)}=\{\max(1,i-s+1),\dots,i\},
\]
and layers outside the compute-KV subset reuse keys and values from an earlier layer \(r(\ell)\) rather than recomputing them [2409.15012]. Optional gating is described there only as an extension: if used, it mixes local and shared keys and values through headwise scalars \(g_{\ell,h}\in[0,1]\) [2409.15012].

The technical significance of SWA across these formulations is that it replaces the full past with a bounded local receptive field. All later gating mechanisms operate on top of this bounded substrate rather than replacing it.

## 3. Two gating paradigms

The first gating paradigm is learnable token eviction. In the hybrid model of [2510.20787], once a token leaves the sliding window, a per-token, per-head retention score \(r_{j,h}\in(0,1)\) determines whether the KV-pair \((j,h)\) is kept in an out-of-window cache. The module is explicitly fine-grained, contextualized, independent, and lightweight: it makes a separate decision for each token and head; it uses local context from both past and future adjacent tokens via a small CNN; it avoids global top-\(K\) selection by using a sigmoid-plus-threshold decision; and it uses only three small 1D convolutions per head, for approximately \(1\%\) extra parameters [2510.20787]. Concretely, the module begins from the pre-RoPE concatenated vector
\[
u_{j,h}=\bigl[k_{j,h}\,\Vert\,v_{j,h}\bigr]\in\mathbb{R}^{2d_h},
\]
then applies three grouped 1D dilated convolutions with kernel size \(3\) and dilation \(2\), halving channel width each layer, followed by Swish activations and dropout; a final grouped \(1\times 1\) convolution maps to a scalar logit \(\ell_{j,h}\), and
\[
r_{j,h}=\sigma(\ell_{j,h}), \qquad m_{j,h}=\mathbf{1}\{r_{j,h}>0.5\}.
\]
Training uses a straight-through estimator, and sparsity is encouraged by a per-head \(\ell_1\) penalty on \(\max(0,r_{j,h}-0.5)\) with a learnable head-wise weight \(\lambda_h\) adjusted to target an average retained count \(b\) [2510.20787].

The resulting sparsity pattern is described as “A+column”: local sliding-window tokens plus a learned sparse set of distant tokens retained per head [2510.20787]. In effect, gating determines which old tokens remain directly retrievable after they have left the local window.

The second gating paradigm is logit-decay gating. GatedFWA computes a nonnegative gate \(\alpha_t^{(l,h)}>0\) for each layer, head, and position through a “softplus over scaled pre-activation” construction:
\[
h_t^{(l,h)}=x_t^{(l)}W_g^{(l,h)}+b_g^{(l,h)}\in\mathbb{R},\qquad
\beta_t^{(l,h)}=1+\mathrm{ELU}\bigl(x_t^{(l)}W_\beta^{(l,h)}\bigr)>0,
\]
\[
\alpha_t^{(l,h)}=\frac{1}{\beta_t^{(l,h)}}\,\mathrm{softplus}\bigl(\beta_t^{(l,h)}h_t^{(l,h)}\bigr).
\]
It then accumulates a prefix
\[
u_t^{(l,h)}=\sum_{q=1}^t\bigl(-\alpha_q^{(l,h)}\bigr)\le 0,
\]
and defines the pairwise decay bias
\[
B_{t,j}^{(l,h)}=u_t^{(l,h)}-u_j^{(l,h)}
=\sum_{q=j+1}^t\bigl(-\alpha_q^{(l,h)}\bigr)\le 0,
\]
which is added to the raw dot-product logits under the sliding mask [2512.07782]. Under the exact-kernel associative-memory interpretation, this yields the recurrence
\[
\mathbf M_t
=
\exp(-\alpha_t)\,\mathbf M_{t-1}
+
\frac1w\Bigl(\phi(k_t)^\top v_t-c_t\,\phi(k_{t-w})^\top v_{t-w}\Bigr),
\]
where
\[
c_t=\prod_{j=t-w+1}^{t-1}\exp(-\alpha_j)\in(0,1).
\]
The Jacobian with respect to the previous memory is \(\partial \mathbf M_t/\partial \mathbf M_{t-1}=\exp(-\alpha_t)\mathbf I_d\), so \(\alpha_t\) acts as a learnable contraction: when \(\alpha_t\to 0\), memory and gradients pass; when \(\alpha_t\gg 0\), old history is suppressed [2512.07782].

These two gating paradigms solve different problems. Token eviction restores direct access to selected distant KV-pairs. Logit-decay gating stabilizes the memory dynamics of SWA itself. The shared label can therefore be misleading if the underlying gate semantics are not specified.

## 4. Shared-KV organization and cache semantics

The phrase “Shared-KV” is overloaded across the cited works. In the learnable-token-eviction design, all recent windowed KVs and all gated retained KVs are stored in a head-wise global cache that is physically contiguous. The cache consists of a circular buffer of size \(w\) for the window and a capped buffer of size \(b\) for retained tokens, together with \(s\) global sink tokens [2510.20787]. Because post-RoPE \(K\) and \(V\) are stored, their relative order is declared unimportant, so entries can be compacted and reordered arbitrarily, which is what enables tiled FlashAttention kernels across both segments [2510.20787]. In the same formulation, all heads share the same projection matrices for \(Q,K,V\), while the gating CNN is implemented as grouped convolutions that are independent per head but share weights wherever possible [2510.20787].

In GatedFWA, Shared-KV refers primarily to headwise sharing of \(K,V\) computation and gate preprocessing. The implementation recipe explicitly recommends a single KV cache: compute \(K,V\) once per token, not per head, and broadcast to all heads, thereby halving the memory footprint and indexing logic [2512.07782]. The gate can itself be shared or head-wise. The gate-preprocessing algorithm outputs \(U\in\mathbb{R}^N\) under the Shared-KV setting, with one gate per token broadcast to all heads, although one may instead compute \(U_t^{(h)}\) per head for greater expressivity [2512.07782].

In MixAttention, by contrast, sharing is inter-layer. Only layers in a subset \(C\subseteq\{1,\dots,L\}\) compute and store new \(K,V\); every other layer reuses the most recent \(K,V\) from an earlier compute-KV layer \(r(\ell)\in C\) [2409.15012]. This means that shared-KV can denote contiguous per-head storage, head-broadcasted KVs, or cache reuse across layers, depending on the paper.

A plausible implication is that any discussion of “Shared-KV Gated Sliding-Window Attention” should specify the sharing axis explicitly: across heads, across layers, or across local and retained memory segments.

## 5. Kernels, buffer management, and asymptotic properties

The systems implementations are designed around FlashAttention-style tiling and Triton or CUDA kernels. In the token-eviction architecture, prefilling maintains a sliding-window buffer and a capped KV cache per head. Attention is computed separately over the window and the retained cache, optionally combined as \(y_{t,h}=g_{\mathrm{swa}}\,y_{\mathrm{swa}}+g_{\mathrm{kv}}\,y_{\mathrm{kv}}\). When a KV-pair leaves the circular window buffer, its retention score is computed if necessary; if \(r_{popped,h}>0.5\), it is inserted into the retained cache and the lowest-scoring entry is evicted if the cache is full [2510.20787]. The implementation notes further specify lazy batching of CNN scoring every \((w-R)\) steps to amortize cost, and fused Triton kernels for eviction and compaction [2510.20787].

GatedFWA organizes computation into two kernels: a one-pass tiled scan that computes the prefix vector \(U\) from the gate parameters, and a Flash-style tiled attention kernel that injects the bias \(+u_i^q\otimes 1-1\otimes (u_j^k)^\top\) before the masked streaming Softmax [2512.07782]. The implementation notes emphasize that only two extra vector loads per tile are required, the bias arithmetic is \(O(B_rB_c)\) additions, and the rest of the pipeline remains identical to FlashAttention, including online max/sum stabilization [2512.07782].

A compact comparison from the hybrid sparse-attention paper is reproduced below [2510.20787].

| Method | Time/token | Space/token |
|---|---:|---:|
| Full Attn | \(O(N\cdot d)\) | \(O(N\cdot d)\) |
| Linear Attn | \(O(d^2)\) | \(O(d^2)\) |
| SWA | \(O(w\cdot d)\) | \(O(w\cdot d)\) |
| Pure LTE | \(O(d^2+w\cdot d)\) | \(O(d^2+w\cdot d)\) |
| Shared-KV Gated SWA | \(O(w\cdot d+b\cdot d)\) | \(O(w\cdot d+b\cdot d)\) |
| laNSA | \(O(N/M\cdot d+MK\cdot d)\) | \(O(N\cdot d)\) |

Because \(w\) and \(b\) are fixed, the hybrid is described as retaining the constant-time, constant-space benefits of linear attention while still offering direct access to \(O(b)\) distant tokens per head [2510.20787]. GatedFWA gives a more kernel-level accounting: its compute is \(O(Nwd+NH)\), its off-chip traffic is \(O(Nw+Nd+NH)\), and when \(H\ll w\) the additional scan cost is negligible, reported as less than \(1\) ms at \(N=64\)K [2512.07782].

## 6. Empirical behavior and interpretation

The learnable-token-eviction variant is evaluated on retrieval-intensive benchmarks. On the RULER “needle-in-a-haystack” suite and EVAPORATE recall benchmarks, with contexts up to \(4\)K tokens, Shared-KV Gated SWA under the name laLTE and layer-interleaving with Gated DeltaNet outperforms pure Gated DeltaNet, Gated DeltaNet plus SWA without gating, heuristic eviction via TOVA, and MLP-based gating [2510.20787]. On RULER S-NIAH at \(0.4\) B parameters, the reported averages are \(51.7\%\) for GDN, \(54.7\%\) for GDN + SWA, \(63.3\%\) for laLTE, and \(80.4\%\) for the Full Attn hybrid. On EVAPORATE recall at \(0.4\) B parameters, the corresponding values are \(19.5\%\), \(22.8\%\), \(25.3\%\), and \(27.2\%\) [2510.20787]. These results support the claim that a small learned sparse set of distant tokens can improve retrieval relative to plain SWA without abandoning fixed-size local computation.

GatedFWA is evaluated on language modeling with \(125\) M and \(360\) M-parameter models trained on OpenWebText/WikiText103 at context \(N=4096\), window \(w=512\), and single-head SV redistribution with \(H=1\) Shared-KV [2512.07782]. The reported forward-plus-backward throughput on A100 is \(0.2\) \(\mu\)s/token for FlashAttention, \(0.03\) \(\mu\)s/token for SWA, and \(0.032\) \(\mu\)s/token for GatedFWA, corresponding to approximately \(6\%\) overhead versus SWA. Validation loss at \(125\) M is \(3.273\) for the LLaMA baseline at \(N=4096\), \(3.274\) for \(+\)SWA, \(3.255\) for \(+\)GatedFWA, and \(3.230\) for \(+\)GatedFWA + NSA [2512.07782]. On MQAR at \(N=512\), GatedFWA achieves greater than \(90\%\) recall where SWA and many SSMs drop below \(75\%\) [2512.07782].

MixAttention provides complementary evidence that the broader combination of SWA and KV sharing can materially change the inference trade-off. At \(32\)K context on NVIDIA H100, the reported peak KV-cache and throughput are \(48\) GB and \(32\)K/sec for Standard Attention, \(5\) GB and \(45\)K/sec for Sliding Window only, \(10\) GB and \(55\)K/sec for MixAttention (MA-Offset), and \(9\) GB and \(53\)K/sec for MixAttention (MA-Pairs) [2409.15012]. On RULER at \(32\)K context, Standard Attention scores \(56.1\) overall, Sliding only \(26.0\), Mix-MA-Offset \(54.8\), and Mix-MA-Pairs \(55.9\) [2409.15012]. This suggests that shared-KV layouts are not merely memory optimizations; they also change which sparse-attention designs remain competitive under long-context deployment constraints.

A common misconception is that sliding-window attention fails only because its window is too small. The cited work points to two additional failure modes: irreversible loss of distant tokens once they leave the window, addressed by learnable token eviction [2510.20787], and unstable or weakly controlled memory dynamics under an associative-memory view, addressed by learnable decay gating [2512.07782]. Another misconception is that “shared-KV” names a unique architectural primitive. In the cited literature, it instead denotes a cluster of storage, broadcasting, and reuse strategies that can be combined with different kinds of gates and with different objectives.

Source: https://www.emergentmind.com/topics/shared-kv-gated-sliding-window-attention