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

  1. Window — local neighbors (as above),
  2. Global — a few tokens attend to / are attended by all (as in Longformer),
  3. 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.


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.


5. Illustration: the masks side by side

Rows = queries, columns = keys; a filled cell means “allowed” (). Causal (lower-triangular) case, , window .

Dense causal O(s²) Sliding window (w=2) O(s·w) Window + global (t0) Longformer Sinks + rolling win StreamingLLM

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:

PatternAllowed entriesCore FLOPs (scores + A·V)Scaling in
Densequadratic
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

7. Practice


  • 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

  1. 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

  2. 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

  3. 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

  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