Sliding Window Attention

Fixed-window local attention: derivation, effective receptive field across layers, dilated variants, global+local hybrid patterns (Longformer), and memory-complexity analysis for long-context models.

Intermediate

Table of Contents

  1. Learning Objectives
  2. Notation
  3. Core Intuition
  4. The Local Window Formulation
  5. Effective Receptive Field
  6. Dilated Sliding Window
  7. Global + Local Hybrid (Longformer)
  8. Alternating Window Patterns (Mistral)
  9. Memory and Compute Analysis
  10. Comparison with Full Attention
  11. Common Pitfalls
  12. Summary
  13. Exercises

Learning Objectives

  1. Derive the sliding window attention mask and its complexity.
  2. Prove the effective receptive field grows linearly with depth.
  3. Explain how dilated windows extend the receptive field without extra compute.
  4. Describe the Longformer hybrid pattern combining local, global, and sliding attention.
  5. Analyze when sliding window is preferable to full attention.

Notation

  • ww — window size (number of tokens each position attends to)
  • LL — number of layers
  • dd — dilation factor
  • TT — sequence length
  • Mw\mathbf{M}_w — sliding window mask

Core Intuition

Most information in natural language is local: a word's meaning depends primarily on its neighbors. Full O(T2)O(T^2) attention is overkill for most positions — distant tokens contribute negligibly to the softmax distribution. Sliding window attention exploits this locality by restricting each token to attend only within a fixed window, achieving linear complexity in sequence length.

Sliding Window Attention

Attention mask (banded)01234567891011t0t1t2t3t4t5t6t7t8t9t10t11Position 67 visible tokensWindow ±3Complexity: O(N·w)
Window
3
Position
6
In windowMasked out
Explore: Each token attends only to neighbors within ±w positions. Creates a banded matrix — linear memory/compute in sequence length for fixed window.

The Local Window Formulation

Each token at position ii attends to positions in the window [iw/2,i+w/2][i - w/2, i + w/2]:

Aij={exp(sij)k:kiw/2exp(sik)if ijw/20otherwise(1)A_{ij} = \begin{cases} \frac{\exp(s_{ij})}{\sum_{k: |k-i| \leq w/2}\exp(s_{ik})} & \text{if } |i - j| \leq w/2 \\ 0 & \text{otherwise} \end{cases} \tag{1}

where sij=qiTkj/dks_{ij} = \mathbf{q}_i^T\mathbf{k}_j/\sqrt{d_k}.

Mask matrix: The window mask Mw\mathbf{M}_w is a banded matrix:

(Mw)ij={0ijw/2ij>w/2(2)(M_w)_{ij} = \begin{cases}0 & |i-j| \leq w/2 \\ -\infty & |i-j| > w/2\end{cases} \tag{2}

Applied as: A=softmax(QKT/dk+Mw)\mathbf{A} = \text{softmax}(\mathbf{QK}^T/\sqrt{d_k} + \mathbf{M}_w).

For causal models: The window is one-sided: position ii attends to [iw+1,i][i-w+1, i].


Effective Receptive Field

Theorem. After LL layers of sliding window attention with window ww, position tt can be influenced by any position in [tLw,t][t - Lw, t] (causal case).

Proof. At layer 1, position tt sees positions [tw+1,t][t-w+1, t]. At layer 2, each of those positions has already incorporated information from their own window at layer 1. Position tw+1t-w+1 at layer 1 saw positions [t2w+2,tw+1][t-2w+2, t-w+1]. Thus after 2 layers, position tt is influenced by [t2w+2,t][t-2w+2, t]. By induction, after LL layers: [tLw+L,t][tLw,t][t-Lw+L, t] \approx [t-Lw, t]. \blacksquare

Example: Mistral with w=4096w=4096 and L=32L=32: effective receptive field = 32×4096=131,07232 \times 4096 = 131{,}072 tokens — sufficient for 128K contexts even with local attention.

Important caveat: While information can propagate LwLw positions, the signal attenuates exponentially with distance (each hop through a residual connection adds noise).


Dilated Sliding Window

Instead of attending to consecutive neighbors, skip every dd positions:

Window(i,w,d)={j:j=i+kd,  k[w/2,w/2]}.(3)\text{Window}(i, w, d) = \{j : j = i + k \cdot d, \; k \in [-w/2, w/2]\}. \tag{3}

Receptive field per layer: w×dw \times d positions (covers a wider range with the same number of attended tokens).

Multi-head dilation: Different heads use different dilation factors:

  • Head 1: d=1d=1 (local)
  • Head 2: d=2d=2 (skip one)
  • Head 4: d=4d=4 (skip three)

This gives each layer access to both fine-grained local and coarse-grained distant information.


Global + Local Hybrid (Longformer)

Architecture: Combine three attention patterns:

  1. Sliding window (all tokens): Local context, O(Tw)O(Tw) complexity.
  2. Global tokens (selected positions): Attend to/from all positions. Typically: [CLS] token, question tokens, or every kk-th position.
  3. Random attention (optional): Attend to a few random positions for diversity.

Formulation for token ii:

Attn(i)={full attention to all T tokensif iG (global)attend to windowGotherwise (local)(4)\text{Attn}(i) = \begin{cases} \text{full attention to all } T \text{ tokens} & \text{if } i \in \mathcal{G} \text{ (global)} \\ \text{attend to window} \cup \mathcal{G} & \text{otherwise (local)} \end{cases} \tag{4}

Complexity: O(T(w+G))O(T \cdot (w + |\mathcal{G}|)) — linear in TT if G|\mathcal{G}| is fixed.

Use cases: Document classification (global = [CLS]), QA (global = question tokens).


Alternating Window Patterns (Mistral)

Mistral's approach: Use sliding window attention in every layer, but the effective context comes from stacking layers:

  • Every layer: causal sliding window of size w=4096w=4096.
  • No global tokens, no dilated attention.
  • Effective context: L×w=32×4096=128KL \times w = 32 \times 4096 = 128K.

KV-cache optimization: Only need to cache ww tokens per layer (older tokens are evicted). Fixed KV-cache size regardless of sequence length:

KV-cache=L×w×2×dk×bytes=constant.(5)\text{KV-cache} = L \times w \times 2 \times d_k \times \text{bytes} = \text{constant}. \tag{5}

Comparison with Llama: Llama uses full attention (KV-cache grows with TT). Mistral's sliding window gives constant memory but relies on information propagation through layers.


Memory and Compute Analysis

Standard attention: O(T2d)O(T^2 d) compute, O(T2)O(T^2) memory.

Sliding window: O(Twd)O(Twd) compute, O(Tw)O(Tw) memory.

Speedup factor: T/wT/w. For T=128K,w=4096T=128K, w=4096: 32×32\times faster attention.

Implementation: Can be implemented as a block-sparse matrix multiply, or via FlashAttention with masking (FlashAttention-2 supports arbitrary causal masks including sliding window).


Comparison with Full Attention

  • Quality at short context (T<wT < w): Identical (window covers everything).
  • Quality at long context (TwT \gg w): Sliding window loses direct access to distant tokens. Quality depends on task:
    • Summarization, local understanding: minimal degradation.
    • Fact retrieval from specific distant position: significant degradation.
    • Reasoning chains: moderate (info propagates through layers).

Empirical finding: For most language modeling tasks, sliding window with w=4096w=4096 and 32 layers achieves comparable perplexity to full attention, at dramatically lower cost.


Common Pitfalls

Pitfall 1. Setting window too small. With w=512w=512 and L=12L=12: effective context is only 61446144 tokens. For long-document tasks, this is insufficient.

Pitfall 2. Forgetting that information must traverse multiple layers. A token at distance LwLw influences position tt only through a chain of LL intermediate representations — the signal is heavily processed and potentially distorted.

Pitfall 3. Applying sliding window to cross-attention. In encoder-decoder models, the decoder should typically attend to the full encoder output, not a window (the "relevant" encoder positions aren't necessarily nearby).


Summary

  • Sliding window restricts attention to ww nearest tokens: O(Tw)O(Tw) complexity.
  • Effective receptive field = L×wL \times w across layers.
  • Dilated windows extend range without additional compute.
  • Longformer adds global tokens for long-range connections.
  • Mistral uses pure sliding window with layer stacking for 128K context.
  • Fixed KV-cache size (LwLw) regardless of sequence length.

Exercises

Exercise 1. For T=65536,w=4096,L=32T=65536, w=4096, L=32: compute the sliding window attention FLOPs and compare to full attention FLOPs.

Exercise 2. Prove that the effective receptive field after LL layers of dilated attention with dilation dd and window ww is LwdLwd.

Exercise 3. Design a hybrid attention pattern for a 32-layer model processing 100K tokens: specify which layers use sliding window, which use full attention, and justify your choices.

Exercise 4. Compute the maximum KV-cache memory for Mistral (w=4096,L=32,dk=128,G=8w=4096, L=32, d_k=128, G=8) in FP16, and compare to Llama at T=32768T=32768.

Exercise 5. Explain why simply increasing ww to equal TT doesn't recover full attention performance if the model was trained with small ww.