Sliding Window Attention › How Sliding Window Attention Works
Language AI HandbookAll chapters 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 in a sequence. Which tokens should it attend to? The natural answer is: tokens within some fixed distance. If we set a window size , we want token to attend only to tokens that are close enough. We measure closeness by position distance:
where:
- : the position of the query token (the one computing its representation)
- : the position of the key token (a candidate for attention)
- : the window size (total number of positions each token can attend to)
- : the absolute distance between the two positions
- : half the window size (rounded down), giving the maximum distance in each direction
This formula defines a neighborhood around each token. With , token at position 10 can attend to positions 8, 9, 10, 11, and 12. The neighborhood extends 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 , we assign a mask value:
where:
- : the mask value at position
- : no modification (allow attention)
- : 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 ensures that after the exponential in softmax, the weight becomes exactly 0:
The blocked position contributes nothing to the output. In implementation, we use a large negative number like 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:
This computes scores between all query-key pairs (), normalizes them into weights (softmax), and uses those weights to aggregate values. Sliding window attention inserts the mask before softmax:
where:
- : the query matrix, with one row per token
- : the key matrix, with one row per token
- : the value matrix, containing information to aggregate
- : the sliding window mask
- : the raw attention scores before masking
- : the dimension of query and key vectors
- : scaling factor to prevent dot products from growing too large
The computation proceeds in four steps:
- Compute raw scores: Multiply queries by keys to get scores
- Apply mask: Add to block positions outside each token's window
- Normalize: Apply softmax row-wise to convert scores to weights
- 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 ). Token 100 has non-zero weights only for tokens 98-102. The sparse pattern emerges from the mask, even though we computed all scores.


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



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 attention scores because every token attends to every other token. With a sliding window of size , each token attends to at most positions, yielding approximately attention scores instead.
The critical insight is that is a fixed constant (typically 128-512), independent of sequence length. This transforms the complexity:
where:
- : sequence length (the variable that grows with input size)
- : window size (a fixed hyperparameter, constant with respect to )
- : model dimension (also fixed for a given model architecture)
Since both and are constants for a given model, the complexity is linear in . 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.
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# 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,
}
)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.0xThe 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.
