Sliding Window Attention › How Sliding Window Attention Works

Michael BrenndoerferUpdated June 26, 202511 min read
Language AI HandbookAll chapters
Part 17 of 67Efficient Attention
Chapter 119Sliding Window Attention › How Sliding Window Attention Works
Reading section 3 of 12 · How Sliding Window Attention Works · 11 minSection 3 of 12 · 11 min

Book contents

Section 3 of 12 · 11 min read

Sliding Window Attention › How Sliding Window Attention WorksOne section · Sections in this chapter3 / 12 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

To understand sliding window attention, we need to answer three questions: What does "local" mean mathematically? How do we enforce locality in the attention computation? And how does this change the algorithm's behavior? Let's build up the formalism step by step, starting from the intuition and arriving at a complete mathematical specification.

From Intuition to Neighborhoods

In standard attention, every token can attend to every other token. This creates a fully connected graph where information flows freely between all positions. But we observed that most meaningful connections occur between nearby tokens. The first step toward efficiency is formalizing what "nearby" means.

Consider token ii in a sequence. Which tokens should it attend to? The natural answer is: tokens within some fixed distance. If we set a window size ww, we want token ii to attend only to tokens jj that are close enough. We measure closeness by position distance:

∣i−j∣≤⌊w/2⌋|i - j| \leq \lfloor w/2 \rfloor

where:

  • ii: the position of the query token (the one computing its representation)
  • jj: the position of the key token (a candidate for attention)
  • ww: the window size (total number of positions each token can attend to)
  • ∣i−j∣|i - j|: the absolute distance between the two positions
  • ⌊w/2⌋\lfloor w/2 \rfloor: half the window size (rounded down), giving the maximum distance in each direction

This formula defines a neighborhood around each token. With w=5w = 5, token at position 10 can attend to positions 8, 9, 10, 11, and 12. The neighborhood extends ⌊5/2⌋=2\lfloor 5/2 \rfloor = 2 positions in each direction, plus the token itself. Token at position 3 can attend to positions 1, 2, 3, 4, and 5. Every token has the same sized window, centered on itself.

Why floor instead of exact division? Window sizes are typically odd (like 3, 5, or 257) so the token sits exactly in the middle. For even windows, the floor gives a slight asymmetry, attending to one more position on one side than the other. This rarely matters in practice.

Translating Neighborhoods into Masks

Now we face a practical question: how do we tell the attention mechanism which positions each token should attend to? Standard attention computes a score between every query-key pair. We need a way to "zero out" the scores for positions outside the neighborhood.

The solution is an attention mask: a matrix that modifies the raw attention scores before softmax. The mask acts like a filter, allowing some connections and blocking others. For each pair of positions (i,j)(i, j), we assign a mask value:

Mij={0if ∣i−j∣≤⌊w/2⌋−∞otherwiseM_{ij} = \begin{cases} 0 & \text{if } |i - j| \leq \lfloor w/2 \rfloor \\ -\infty & \text{otherwise} \end{cases}

where:

  • MijM_{ij}: the mask value at position (i,j)(i, j)
  • 00: no modification (allow attention)
  • −∞-\infty: block this connection entirely

Why these particular values? The mask gets added to the raw attention scores before softmax. Adding 0 leaves the score unchanged, preserving normal attention behavior for positions within the window. Adding −∞-\infty ensures that after the exponential in softmax, the weight becomes exactly 0:

softmax(…+(−∞))=e−∞∑=0∑=0\text{softmax}(\ldots + (-\infty)) = \frac{e^{-\infty}}{\sum} = \frac{0}{\sum} = 0

The blocked position contributes nothing to the output. In implementation, we use a large negative number like −109-10^9 rather than true infinity to avoid numerical issues, but the effect is identical.

The Complete Attention Formula

With the mask defined, we can write the full sliding window attention computation. Start with the standard attention formula:

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

This computes scores between all query-key pairs (QKTQK^T), normalizes them into weights (softmax), and uses those weights to aggregate values. Sliding window attention inserts the mask before softmax:

Attention(Q,K,V)=softmax(QKT+Mdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T + M}{\sqrt{d_k}}\right)V

where:

  • Q∈Rn×dkQ \in \mathbb{R}^{n \times d_k}: the query matrix, with one row per token
  • K∈Rn×dkK \in \mathbb{R}^{n \times d_k}: the key matrix, with one row per token
  • V∈Rn×dvV \in \mathbb{R}^{n \times d_v}: the value matrix, containing information to aggregate
  • M∈Rn×nM \in \mathbb{R}^{n \times n}: the sliding window mask
  • QKT∈Rn×nQK^T \in \mathbb{R}^{n \times n}: the raw attention scores before masking
  • dkd_k: the dimension of query and key vectors
  • dk\sqrt{d_k}: scaling factor to prevent dot products from growing too large

The computation proceeds in four steps:

  1. Compute raw scores: Multiply queries by keys to get n×nn \times n scores
  2. Apply mask: Add MM to block positions outside each token's window
  3. Normalize: Apply softmax row-wise to convert scores to weights
  4. Aggregate: Multiply weights by values to get the output

After masking and softmax, each row of the weight matrix sums to 1, but the non-zero weights are concentrated in a band around the diagonal. Token 5 has non-zero weights only for tokens 3-7 (with w=5w=5). Token 100 has non-zero weights only for tokens 98-102. The sparse pattern emerges from the mask, even though we computed all n2n^2 scores.

Out[3]:
Visualization
Dense heatmap showing all positions have non-zero attention weights.
Full attention: Every token attends to every other token, creating a dense n x n matrix.
Banded heatmap showing attention concentrated along the diagonal.
Sliding window attention (w=5): Each token attends only to its local neighborhood, creating a sparse banded pattern.

Window Patterns

Several window configurations are possible. The most common is the symmetric window where each token looks an equal distance forward and backward:

Out[4]:
Visualization
Matrix showing diagonal band of attention weights centered on the main diagonal.
Symmetric window (w=5): Each token attends to 2 tokens on each side plus itself.
Matrix showing lower triangular band below and including the diagonal.
Causal window (w=3): Each token attends only to itself and 2 previous tokens.
Matrix showing asymmetric band with more left context than right.
Asymmetric window: Different left and right context sizes.

The symmetric window suits bidirectional models like BERT where context flows in both directions. The causal window is essential for autoregressive models like GPT, where tokens must not attend to future positions. Asymmetric windows can be useful when past context is more informative than future context, or vice versa.

Complexity Analysis

Understanding the complexity reduction is key to appreciating why sliding window attention matters. Standard attention computes n×nn \times n attention scores because every token attends to every other token. With a sliding window of size ww, each token attends to at most ww positions, yielding approximately n⋅wn \cdot w attention scores instead.

The critical insight is that ww is a fixed constant (typically 128-512), independent of sequence length. This transforms the complexity:

O(n2d)→O(n⋅w⋅d)=O(n⋅d)O(n^2 d) \to O(n \cdot w \cdot d) = O(n \cdot d)

where:

  • nn: sequence length (the variable that grows with input size)
  • ww: window size (a fixed hyperparameter, constant with respect to nn)
  • dd: model dimension (also fixed for a given model architecture)

Since both ww and dd are constants for a given model, the complexity is linear in nn. This linear scaling means we can process sequences of arbitrary length with proportional, rather than quadratic, cost. A 10x longer sequence requires only 10x more computation, not 100x.

In[5]:
Code
def attention_complexity(n, d, window_size=None):
    """
    Compute attention complexity for standard vs windowed attention.

    Args:
        n: Sequence length
        d: Model dimension
        window_size: If provided, use sliding window; otherwise full attention

    Returns:
        Number of operations (approximately)
    """
    if window_size is None:
        # Standard attention: O(n^2 * d)
        return n * n * d
    else:
        # Sliding window: O(n * w * d)
        return n * window_size * d
In[6]:
Code
# Compare complexity across sequence lengths
d = 768  # GPT-2 small dimension
window = 256

seq_lengths = [512, 1024, 2048, 4096, 8192, 16384]
results = []

for n in seq_lengths:
    standard = attention_complexity(n, d)
    windowed = attention_complexity(n, d, window)
    speedup = standard / windowed
    results.append(
        {
            "n": n,
            "standard_gflops": standard / 1e9,
            "windowed_gflops": windowed / 1e9,
            "speedup": speedup,
        }
    )
Out[7]:
Console
Complexity Comparison (d=768, window=256):

   Seq Len        Standard        Windowed    Speedup
----------------------------------------------------
       512           0.20G           0.10G        2.0x
     1,024           0.81G           0.20G        4.0x
     2,048           3.22G           0.40G        8.0x
     4,096          12.88G           0.81G       16.0x
     8,192          51.54G           1.61G       32.0x
    16,384         206.16G           3.22G       64.0x

The speedup grows linearly with sequence length. At 512 tokens, sliding window provides a 2x speedup. At 16K tokens, the speedup reaches 64x. This difference matters when processing long documents, where standard attention would be prohibitively expensive.

Out[8]:
Visualization
Log-scale line plot showing quadratic growth of standard attention versus linear growth of sliding window attention.
Complexity comparison between standard attention and sliding window attention (window=256). Standard attention grows quadratically while sliding window grows linearly, with the gap widening as sequence length increases.