Sliding-window attention and access to distant tokens

← Back to Blog & Articles

The practical consequence for streaming and long-context inference is direct: a sliding-window cache-eviction policy that naively drops the oldest cached tokens once the window fills will, sooner or later, evict the attention sink along with everything else — and doing so degrades generation quality sharply and often abruptly, well beyond what the loss of “ordinary” distant context alone would predict, because it removes positions the model has come to rely on as a kind of always-available pressure-release valve for every attention head.

KV caching and GQA/MQA reduce the cost per byte and bytes per head of a T×TT\times T-scaling attention computation; they do not change the fact that computing (or caching) attention over the full sequence is fundamentally an O(T2)O(T^2)-shaped problem in TT. An orthogonal family of techniques instead restricts which keys a query is allowed to attend to at all, trading some of the modeling flexibility of full attention for a cost that scales linearly, not quadratically, in TT.

Fixed-window local attention. The simplest such restriction bounds each query to a fixed-size backward window: query position tt may attend only to key positions in {max(1,t−w+1),…,t}\{\max(1, t-w+1), \dots, t\}, for a window size ww set as a fixed hyperparameter, independent of TT. This is exactly the causal mask from the companion book with one additional constraint — an extra lower bound on the allowed key index, not just the existing upper bound s≤ts\le t. Counting the number of allowed query-key pairs: for t≥wt \geq w, exactly ww keys are visible; for t<wt<w, only tt keys are visible (there simply aren’t ww positions yet). Summing across all TT query positions, ∑t=1T(visible keys at t)=∑t=1w−1t+(T−w+1)w=O(Tw), \sum_{t=1}^{T} (\text{visible keys at } t) = \sum_{t=1}^{w-1} t + (T-w+1)\,w = O(Tw), which for T≫wT \gg w is dominated by the steady-state term and grows linearly in TT. Since each query-key comparison still costs O(dk)O(d_k) as in the companion book, the total per-head attention cost of a sliding-window layer is

O(Twdk),\begin{equation} O(T\,w\,d_k), \end{equation}

linear in sequence length whenever ww is held fixed — a direct asymptotic improvement over the O(T2dk)O(T^2 d_k) of full attention once TT grows large relative to ww. The same restriction bounds the KV cache: because no query ever attends further back than ww positions, keys and values older than ww positions behind the current generation point are provably never read again, and can be evicted from the cache entirely, capping a sliding-window layer’s cache at O(w)O(w) rather than O(T)O(T) — a second, independent memory saving on top of GQA/MQA, and one that matters specifically for the streaming and very-long-context inference settings this section closes with.

A single sliding-window layer, of course, cannot see further back than ww tokens no matter how the rest of the network is built, which looks like a severe limitation for tasks that genuinely require long-range dependencies. Stacking LL such layers largely repairs this, by the same receptive-field-growth argument used for dilated convolutional networks: information at position tt in layer ℓ\ell can depend (indirectly, through the layers below it) on information as far back as t−ℓ(w−1)t - \ell(w-1), since each additional layer’s window can reach w−1w-1 positions further back than what the previous layer already aggregated into its own outputs. An LL-layer stack of window-ww local attention therefore has an effective receptive field on the order of L(w−1)+1L(w-1)+1 — smaller than a full-attention model’s receptive field of the entire context in a single layer, but growing linearly with depth rather than being capped at ww regardless of how deep the network is. This composition of narrow local layers into a wide effective receptive field is exactly the design used by Longformer (Beltagy et al., 2020), which combines sliding-window attention with a small number of designated “global” tokens that attend to (and are attended to by) every position, restoring some full-sequence connectivity without paying the full O(T2)O(T^2) cost anywhere.

Strided and dilated patterns. A related family of sparsity patterns keeps each query’s number of visible keys bounded, as sliding windows do, but chooses which keys to make visible by a stride rather than contiguous adjacency — for instance, attending to every kk-th previous position rather than the ww most recent ones, analogous to a dilated convolution’s expanded receptive field at fixed kernel size. Child et al. (2019) formalize this as factorized sparse attention: alternate attention layers (or attention heads within a layer) between a local pattern and a strided pattern, so that the two patterns compose across depth to let information reach any position within a small constant number of layers, while each individual layer’s cost remains far below O(T2)O(T^2) — Child et al. (2019) report complexity on the order of O(TT)O(T\sqrt{T}) for their factorized scheme, against O(T2)O(T^2) for full attention, a substantial asymptotic improvement for long sequences even though it is not linear.

The attention sink phenomenon. A separate, empirically discovered regularity is worth stating precisely because it directly constrains how sliding-window and cache-eviction schemes can be implemented in practice: across trained causal Transformers, a small number of initial token positions — often just the very first token — receive a disproportionately large share of attention weight from nearly every later query, at nearly every head and layer, largely independent of what token actually occupies that position. Xiao et al. (2023) term this an “attention sink” and offer a mechanistic explanation consistent with the softmax normalization the companion book derives: softmax is forced to distribute its full probability mass of 11 across every visible key, even on queries for which no key is genuinely informative for that particular head’s function at that step. Rather than spreading this unavoidable “leftover” probability across many uninformative positions (which would inject noise into the weighted-value output), a trained model can learn to dump it onto a small set of fixed, reliably visible positions instead — and the earliest tokens in a causal sequence are uniquely suited to this role, since under causal masking they are the only positions visible to literally every subsequent query, at every generation step, regardless of how long the sequence eventually grows; no interior position has that property, since it eventually falls behind newer positions and, under a naive sliding window, would leave the visible window altogether. the companion book’s discussion of causal attention weight matrices already flagged a simplified stand-in for exactly this pattern (its the companion book example shows a toy heatmap with exaggerated weight on the first token); the mechanism identified here is the reason that toy pattern is not an arbitrary illustrative choice.

The practical consequence for streaming and long-context inference is direct: a sliding-window cache-eviction policy that naively drops the oldest cached tokens once the window fills will, sooner or later, evict the attention sink along with everything else — and doing so degrades generation quality sharply and often abruptly, well beyond what the loss of “ordinary” distant context alone would predict, because it removes positions the model has come to rely on as a kind of always-available pressure-release valve for every attention head. Xiao et al. (2023) show that the fix requires no retraining: pin a small fixed number of initial tokens (as few as four, in their reported experiments) permanently in the cache, in addition to whatever sliding window of recent tokens is retained, and generation quality over arbitrarily long streams stabilizes. the companion book (Inference and Decoding) returns to this interaction between cache-eviction policy and generation quality when it treats streaming inference and cache-management strategies quantitatively.

Continue with the book

Explore the full treatment, worked examples, and exercises in LLMs Derived.


Companion article for LLMs Derived, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.

Scroll to Top