Learn: Sparse & Sliding-Window Attention
What you're learning
How to break the wall by changing which pairs of tokens are allowed to attend, instead of changing the attention math itself. By the end you’ll be able to derive the effective receptive field of stacked windowed layers, place Longformer/BigBird on a pattern taxonomy, and explain why the first few tokens become “attention sinks” that make streaming decoding stable.
Sixth lesson of the Attention Mechanisms curriculum. Assumes lessons 01–05 (SDPA, MHA, positions, the quadratic bottleneck, and KV-cache / MQA-GQA-MLA). Vocabulary follows the attention-glossary.
1. Learning map
graph TD A["Problem: O(s²) dense attention<br/>every token sees every token"] --> B["Observation: attention<br/>weight is mostly LOCAL"] B --> C["Idea: restrict the PATTERN<br/>with a sparsity mask"] C --> D["Sliding window<br/>O(s·w), Mistral"] C --> E["+ Global tokens<br/>Longformer"] C --> F["+ Random edges<br/>BigBird (universal)"] D --> G["Depth grows the<br/>receptive field: ≈ L·w"] D --> H["Streaming decode:<br/>rolling KV window"] H --> I["Attention sinks<br/>StreamingLLM"] style B fill:#44a,color:#fff style C fill:#44a,color:#fff style I fill:#a44,color:#fff
2. Intuition: you don’t need every token to see every other
Lesson 04 left us at a wall: dense attention costs in both compute and the size of the score matrix. But look at a trained attention map and a striking fact jumps out — most of the weight is local. A token attending mostly to its recent neighbors, plus a handful of special positions, explains the bulk of the mass. The all-pairs interaction is paying in full for a matrix that is nearly sparse.
So the move is not to change the attention formula (softmax over QKᵀ stays exactly as in lesson 01) — it’s to change the pattern: decide ahead of time which pairs are even allowed to interact, and mask out the rest before softmax. Set the disallowed scores to and they contribute nothing. If each query is only allowed keys instead of , the cost collapses from to .
The CNN analogy (this is the load-bearing intuition)
A single convolution layer has a tiny receptive field, yet a deep CNN “sees” the whole image — because receptive fields compound with depth. Windowed attention is the same trick: one layer only looks tokens back, but a token’s window includes neighbors whose own windows reached further back last layer. Information propagates outward one window per layer, so stacked layers give an effective receptive field of . Locality per layer, globality through depth.
"Sparse" ≠ "lossy by definition"
Restricting the pattern is an approximation of full attention — but a cheap-and-often-harmless one, because the discarded entries were small anyway. The failure mode is specific: genuinely long-range dependencies that no path of stacked windows can bridge within layers (e.g. a fact stated once at token 5 that matters at token 50,000 in a model too shallow for to reach it). The global/random patterns below exist precisely to patch that hole.
3. The math: a taxonomy of patterns
Everything here is one operation with a binary mask applied to the scores:
Dense causal attention is the special case . The cost of the core is proportional to the number of allowed entries, , not . Every pattern below is a choice of which entries stay 1.
3a. Sliding-window (local) attention — Mistral 7B
Each token attends only to itself and the previous tokens (causal window of size ):1
Allowed entries per row: . Total core cost drops from to — linear in sequence length for fixed . Mistral 7B uses with a 32-layer stack.1
Receptive field via depth. Layer 1 lets token see back to . Those tokens, at layer 1, had already pulled in information from their windows, i.e. back to . Inductively, after layers token is influenced by tokens as far back as (in the causal case; for bidirectional). So an -layer model has
For Mistral, tokens of theoretical reach — far beyond any single layer’s 4096-token window.1
Why this is the default long-context primitive
Sliding-window attention needs no new parameters and no new kernels beyond a masked SDPA — it’s a change to the mask and to what you keep in the KV cache. That’s why it’s the cheap workhorse (Mistral, and the local layers of many “hybrid” models that interleave a few full-attention layers for global reach).
3b. Longformer — window + dilation + global tokens
Longformer keeps the sliding window but adds two ingredients:2
- Dilation. Put gaps of size inside the window (attend to every -th token), so a fixed budget of allowed keys reaches further per layer — the same idea as dilated convolutions. Used in some heads to widen reach without widening cost.
- Global tokens. A few designated positions (e.g.
[CLS], or question tokens in QA) attend to everything and are attended to by everything. This adds two full rows/columns per global token to : a global token is a hub that any position can reach in one hop.
Cost stays with global tokens — still linear in . Longformer was the design that scaled BERT-style bidirectional attention to thousands of tokens for documents.2
3c. BigBird — window + global + random
BigBird combines three pattern types:3
- Window — local neighbors (as above),
- Global — a few tokens attend to / are attended by all (as in Longformer),
- Random — each query attends to randomly chosen keys.
The random edges are the theoretical punchline: viewing the mask as a graph, random edges turn it into a sparse random (expander-like) graph with small diameter, so any two tokens are connected by a short path. Zaheer et al. prove that with these three ingredients BigBird is a universal approximator of sequence functions and is Turing-complete — i.e. sparsity this structured loses no expressive power in the limit, while costing instead of .3
"Universal" is an existence result, not a free lunch
BigBird’s universality says a sparse-attention Transformer can represent what a dense one can — it does not say a given trained BigBird matches dense attention at fixed depth/width, nor that random access patterns are hardware-friendly. In practice window+global do most of the work; the random component is finicky to implement efficiently on GPUs (gather-scatter, poor coalescing). This is why deployed long-context stacks lean on window+global (+ a few dense layers) more than on random edges.
Quiz (retrieval): A model has layers and a causal sliding window of . From memory: (a) per-layer attention cost in , and (b) the deepest-layer effective receptive field. Could token 20,000 influence the prediction at token 20,050 through the window alone? What about influencing token 200,000?
Answer
(a) — linear in for fixed . (b) tokens. Token 20,000 → 20,050 is a distance of 50 , so it’s captured within a single layer’s window — trivially yes. Token 20,000 → 200,000 is a distance of 180,000 : no path of stacked windows can bridge it in 24 layers. That gap is exactly what global tokens (Longformer/BigBird) or occasional full-attention layers exist to fix.
4. Attention sinks & StreamingLLM
Now a twist that only shows up at inference / streaming time. Suppose you want to decode an effectively infinite stream (a chat that never ends) with bounded memory. The obvious idea: keep a rolling KV window — cache only the most recent tokens, evict the oldest. This is just sliding-window attention applied to the KV cache (lesson 05). It should work… and it catastrophically fails: perplexity blows up the moment the earliest tokens get evicted.4
The empirical finding — attention sinks. Xiao et al. observed that a huge fraction of attention mass, across layers and heads, is dumped onto the first few tokens of the sequence — regardless of whether those tokens are semantically important. They named these attention sinks. Evicting them is what breaks the model.4
Why do sinks exist? This is the mechanistic point worth locking in. Softmax is a convex combination: its weights are non-negative and must sum to 1. A query has no way to say “I don’t want to attend to anything this step” — even when the right answer is attend to nothing, softmax still forces it to spend all its probability mass somewhere. So the network learns a dumping ground: a default location to park the leftover mass harmlessly. The first tokens are the natural choice because, under causal masking, they are the only positions visible to every query in the sequence — they’re the universally reachable “ground” of the causal graph. The model overtrains a bias to route excess softmax mass there.
Sinks are the "softmax has to sum to 1" tax made visible
The clean way to remember it: dense softmax attention cannot output “no-op”, so it manufactures a no-op by over-attending to a fixed, always-visible position. (This is also the motivation behind proposed fixes like a learned “off” logit — sometimes called softmax-off-by-one / attention with a zero-sink slot — which give the model an explicit place to send the leftover mass.) [verify: the “+1 in the softmax denominator” fix is Evan Miller’s Attention Is Off By One, not from the StreamingLLM paper.]
The fix — StreamingLLM. Keep a tiny number of initial “sink” tokens permanently in the KV cache plus the rolling recent window. Concretely: cache the first tokens (Xiao et al. find suffices) and the most recent tokens, dropping the middle.4 With the sinks retained, the leftover-mass dumping ground still exists, the attention distributions stay in-distribution, and the model decodes stably over millions of tokens with memory — no fine-tuning required.4
StreamingLLM extends stability, not memory
It does not give the model access to information from the evicted middle tokens — those are gone. It lets a fixed-window model keep generating coherently forever without the perplexity explosion. If you need the model to actually recall far-back content, you need real long context (bigger window, retrieval, or global/dense layers), not sinks.
Quiz (retrieval): Explain in two sentences why attention sinks form, and why a naive rolling-window KV cache (recent- only) breaks while StreamingLLM (sinks + recent-) doesn't.
Answer
Softmax weights are non-negative and sum to 1, so a query is forced to place all its mass somewhere even when it wants to attend to nothing; the model learns to dump this leftover mass on the first few tokens, which are visible to every query under causal masking — those become “sinks.” A naive rolling window evicts exactly those sink tokens, so queries must redistribute their large parked mass onto tokens that were never trained to receive it, pushing the attention distribution out of distribution and spiking perplexity; StreamingLLM keeps ~4 initial sink tokens alongside the recent window, preserving the dumping ground and keeping distributions in-distribution.
Quiz (retrieval): Mistral uses a sliding window during training. StreamingLLM uses sinks + a rolling window at inference on already-trained models. Why are these not the same technique even though both keep a window?
Answer
Mistral’s window is an architectural choice baked into training: the model never attends outside , and long-range reach comes from the depth effect. StreamingLLM is a test-time KV-cache eviction policy applied to models (possibly full-attention ones) that were not trained for infinite streaming — it exploits the emergent attention-sink phenomenon to keep those models stable when you throw away most of their KV cache. One shapes what the model can learn to attend to; the other manages what you keep in memory at decode time.
5. Illustration: the masks side by side
Rows = queries, columns = keys; a filled cell means “allowed” (). Causal (lower-triangular) case, , window .
Grey = local window; blue = global hub token (reads and is read by all); red = retained “sink” token(s) kept in the KV cache alongside the rolling recent window. Longformer/BigBird add global (and BigBird also random) edges on top of the window; StreamingLLM keeps sinks + recent and evicts the middle. Source: patterns from Mistral1, Longformer2, BigBird3, StreamingLLM4.
6. FLOPs & memory
Reusing the lesson-01 accounting (multiply-add = 2 FLOPs; batch , model dim , single-head view), the attention core cost is proportional to the number of allowed score entries:
| Pattern | Allowed entries | Core FLOPs (scores + A·V) | Scaling in |
|---|---|---|---|
| Dense | quadratic | ||
| Sliding window () | linear | ||
| Window + global () | linear () | ||
| BigBird (win + global + random) | linear |
The projections still cost regardless of the pattern — sparsity only touches the term. So sparse attention pays off precisely in the long-context regime where the term dominates the term (roughly ); at short the projections dominate and sparsity buys little.
KV-cache / memory (the inference story). This is where sliding windows shine at decode time (recall lesson 05’s KV cache):
- Dense decode: KV cache grows — every past token’s K and V is retained forever. This is usually the binding inference constraint at long context.
- Sliding-window decode: you only ever need the last tokens’ K/V, so the cache is bounded at , independent of how much you’ve generated. Mistral implements this as a rolling buffer cache of fixed size .1
- StreamingLLM decode: — the sink tokens plus the recent window — enabling constant-memory generation over unbounded streams.4
Try it: sparse vs dense in the calculator
Open the Attention FLOPs & KV-cache calculator. Set , , and compare dense prefill at against a windowed estimate: multiply the dense / terms by (e.g. ). Then watch the KV cache: dense grows with , but a rolling window pins it at the size for tokens. The conceptual link: sparsity rescales the term by and caps the cache at .
Quiz (retrieval): You switch a 32k-context layer from dense to a sliding window of . Estimate the factor reduction in (a) the score FLOPs and (b) the decode-time KV-cache size.
Answer
(a) Scores go from to , a factor of — a 16× reduction. (b) The KV cache goes from (32k tokens) to (2k tokens), also 16× smaller and, crucially, constant as generation continues rather than growing. Note projections and MLP are untouched, so end-to-end speedup is smaller than 16×.
7. Practice
Problem: designing a long-context stack
You must serve 128k-token context on a fixed memory budget. You consider (i) pure sliding window over layers, and (ii) sliding window in 30 layers + full attention in 2 layers. What long-range dependencies does (i) provably miss, and how does (ii) fix it? What does it cost?
Solution. (i) Effective receptive field — so in principle a signal can propagate end-to-end, but only via a length-32 chain of windows, i.e. every intermediate layer must preserve and relay it. Fragile for a single token that matters 128k away, and it fully breaks for context . (ii) The 2 full-attention layers give every token a one-hop path to any other token, robustly bridging arbitrary distances; cost is the dense term (the 2 dense layers) the cheap term — dominated by those 2 dense layers but far below 32 dense layers. This “mostly-local, a-few-global/dense” hybrid is the standard long-context recipe.
Problem: why not just make huge?
If depth gives receptive field , why not set and use one layer? Conversely, why not and rely entirely on depth?
Solution. is just dense attention — you’re back to , defeating the purpose. makes each layer see only itself + one neighbor, so reaching distance needs layers (absurd depth) and forces every long-range signal through a long, lossy relay chain, hurting optimization and fidelity. The sweet spot is large enough that (a) most real dependencies are intra-window and (b) with realistic , while so the saving is real. Mistral’s is one such balance.
Read next / primary sources
- Sliding window / rolling KV cache: Jiang et al., Mistral 7B — arXiv:2310.06825, §2 (Sliding Window Attention, Rolling Buffer Cache).1
- Window + dilation + global: Beltagy, Peters, Cohan, Longformer — arXiv:2004.05150.2
- Window + global + random, universality proof: Zaheer et al., Big Bird — arXiv:2007.14062 (the universality/Turing-completeness argument is in the appendix).3
- Attention sinks / streaming: Xiao et al., Efficient Streaming Language Models with Attention Sinks (StreamingLLM) — arXiv:2309.17453.4
Ask your teacher
Want the receptive-field induction written out formally, a walk-through of BigBird’s expander-graph diameter argument, or a look at how FlashAttention kernels handle a windowed mask efficiently? Ask — I can go deeper on any piece or hand you a harder problem.
What’s next
- 07-linear-and-subquadratic — instead of masking the matrix, avoid materializing it at all: kernel/linear attention and state-space-style methods that are subquadratic by construction.
- Back to 05-mqa-gqa-mla — sparse patterns and KV-head sharing are complementary levers on the same inference-memory bottleneck; production stacks combine them.
References
Reference: attention-mechanisms | attention-glossary | Filed: 2026-09-10
Footnotes
-
Jiang, Sablayrolles, Mensch, et al., “Mistral 7B” — arXiv:2310.06825 (2023). Introduces Sliding Window Attention (, 32 layers, effective context ) and the fixed-size Rolling Buffer KV cache. ↩ ↩2 ↩3 ↩4 ↩5 ↩6
-
Beltagy, Peters, Cohan, “Longformer: The Long-Document Transformer” — arXiv:2004.05150 (2020). Sliding-window + dilated-window + task-motivated global attention; linear scaling for long documents. ↩ ↩2 ↩3 ↩4
-
Zaheer, Guruganesh, Dubey, et al., “Big Bird: Transformers for Longer Sequences” — arXiv:2007.14062 (2020). Combines window, global, and random attention; proves the resulting sparse attention is a universal approximator and Turing-complete. ↩ ↩2 ↩3 ↩4
-
Xiao, Tian, Chen, Han, Lewis, “Efficient Streaming Language Models with Attention Sinks” — arXiv:2309.17453 (2023). Identifies the attention-sink phenomenon (mass concentrated on initial tokens) and shows that retaining ~4 sink tokens plus a rolling recent window enables stable, constant-memory decoding over millions of tokens without fine-tuning. ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7