Mistral Architecture › Sliding Window Attention
Language AI HandbookAll chapters Mistral Architecture › Sliding Window AttentionOne section · Sections in this chapter3 / 14 ↓
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 first appreciate the problem it solves. Standard self-attention allows every token to attend to every other token. This seems natural: when predicting the next word, shouldn't the model consider the entire context? The answer is yes, in principle. But the computational reality tells a different story.
The Quadratic Problem
Consider what happens when you compute attention. For each token in your sequence, you calculate a score against every other token. With tokens, that's scores per token, and tokens total, giving scores. Store these in memory, and you need space proportional to . Compute them, and you need operations proportional to .
This quadratic scaling creates a harsh reality:
| Sequence Length | Attention Scores | Growth Factor |
|---|---|---|
| 1,024 tokens | ~1 million | 1x |
| 4,096 tokens | ~17 million | 16x |
| 16,384 tokens | ~268 million | 256x |
Doubling the sequence length quadruples both memory and compute. By the time you reach 16K tokens, a common context length for modern models, you're dealing with hundreds of millions of attention scores per layer. Multiply by 32 layers and the numbers add up quickly.
The Sliding Window Insight
Mistral's solution starts with a simple observation: in practice, tokens rarely need to attend to the entire preceding context with equal importance. Recent tokens matter more than distant ones for most language patterns. What if we formalized this intuition and restricted attention to only the most recent tokens?
This is exactly what sliding window attention does. Instead of allowing token to attend to all tokens from 0 to , we restrict it to a fixed window of size . Token can only attend to tokens in positions through , a span of at most tokens.
Think of it like looking through a sliding window that moves along with your position in the sequence. Early in the sequence, when you're at position 3, you might see positions 0, 1, 2, and 3. Later, at position 1000, you see positions 997, 998, 999, and 1000. The window always contains the same number of tokens (or fewer, at the start), regardless of how long the sequence grows.
From Intuition to Formula
Let's formalize this sliding window mathematically. We need a mask that tells the attention mechanism which positions are allowed (within the window) and which are forbidden (outside the window or in the future).
The attention mask determines whether query position can attend to key position :
Let's unpack each component:
- : the query position, meaning the token that's "asking" for information
- : the key position, meaning the token that might provide information
- : the window size (4096 for Mistral 7B)
- : the leftmost position in the window, clamped to 0 for early tokens
- The condition : defines the valid window, positions can attend to
The mask values themselves serve a specific purpose in the attention computation:
- : When added to attention scores, leaves them unchanged, allowing attention
- : When added to attention scores, makes them negative infinity. After softmax, , completely blocking attention
Why this particular formulation? The answer lies in how attention scores become attention weights. Raw scores pass through softmax, which exponentiates each score. By adding to forbidden positions, we ensure their exponentiated values are exactly zero, not just small. This creates a hard boundary that the model cannot violate.
Complexity Transformation
The power of sliding window attention becomes clear when we analyze its complexity. With full attention, each of tokens computes scores against all tokens, giving operations. With sliding window attention, each of tokens computes scores against only tokens, giving operations.
When is fixed (4096 for Mistral), this becomes : linear in sequence length. The difference is significant:
- Full attention at 32K tokens: billion scores
- Sliding window at 32K tokens: million scores
That's an 8x reduction at 32K tokens, and the gap widens as sequences grow longer.



The visual difference is clear. Standard causal attention fills the entire lower triangle, meaning late tokens must process attention scores for all preceding tokens. Sliding window attention creates a narrow band along the diagonal, greatly reducing the number of computations.
Information Flow Across Layers
A natural concern arises: if each token can only see tokens back, how does the model capture long-range dependencies? If the sliding window is 4096 tokens, can a token at position 8000 ever learn anything from a token at position 100?
The answer is yes, and understanding why requires thinking about how information propagates through stacked transformer layers.
The Layered Propagation Mechanism
Consider a concrete example. At layer 1, token 8000 can directly attend to tokens 3905 through 8000 (a window of 4096 positions). It cannot see token 100 directly. But here's the key insight: token 3905 at layer 1 could see tokens 0 through 3905. When token 8000 attends to token 3905 at layer 2, it's attending to a representation that already contains information from the beginning of the sequence.
Each layer extends the reach:
- Layer 1: Token sees positions , a direct window of tokens
- Layer 2: Token attends to tokens that themselves saw tokens back, extending indirect reach to
- Layer : Information can travel up to positions through layered propagation
This gives us the receptive field formula:
where:
- : the receptive field at layer , measuring how far back information can theoretically travel
- : the layer number (1 to )
- : the sliding window size
Applying the Formula to Mistral
For Mistral 7B with layers and :
This theoretical receptive field of 131K tokens vastly exceeds Mistral's 8K context length. Even at layer 2, the receptive field is tokens, covering the entire context window.
This analysis reveals an important design choice: Mistral's window size and layer count are calibrated so that the receptive field exceeds the context length early in the network. By layer 2, any token can (indirectly) access information from any other token in the context.
The Trade-off: Direct vs Indirect Access
While the receptive field ensures information can flow across the entire context, there's a qualitative difference between direct and indirect access. When token 8000 directly attends to token 7999, it sees that token's representation with full fidelity. When it indirectly accesses token 100 through layered propagation, the information has passed through multiple aggregation steps, potentially becoming more diffuse.
For tasks requiring precise retrieval of specific early tokens, this indirect propagation may be less effective than full attention. But for most language modeling tasks, where context builds gradually and recent tokens matter most, the sliding window provides an excellent trade-off between efficiency and capability.

The visualization shows that by layer 2, the receptive field already exceeds the 8K context length. This means that even though individual attention operations are local, the overall architecture can still capture dependencies spanning the entire input.
Memory and Compute Savings
Understanding the theory of sliding window attention is valuable, but the practical impact is what matters for deployment. Let's derive exactly how much memory and compute we save, starting from first principles.
Deriving the Memory Formulas
The attention mechanism computes a score for each query-key pair. With query positions and key positions, we have scores to store. Each attention head maintains its own score matrix, and each score requires storage space determined by the numerical precision.
For full attention, the memory required is:
For sliding window attention, each query position only attends to key positions. When the sequence is shorter than the window (), we still compute scores per query. When the sequence exceeds the window (), we compute exactly scores per query:
Let's define each variable precisely:
- : total memory in bytes for all attention score matrices
- : sequence length (number of tokens)
- : sliding window size (4096 for Mistral)
- : number of attention heads (32 for Mistral)
- : bytes per element (2 for fp16, 4 for fp32)
The Crossover Point
The formulas reveal a key insight: the two methods behave identically when . Both compute the same attention matrix because the window hasn't started to "slide" yet. The divergence occurs when :
- Full attention: Memory grows as , accelerating as sequences lengthen
- Sliding window: Memory grows as , which is linear in since is fixed
For Mistral with , the crossover happens at 4096 tokens. Below this, both methods are equivalent. Above this, sliding window provides increasing savings:
- At : Sliding window uses the memory (50% savings)
- At : Sliding window uses the memory (87.5% savings)
The savings percentage follows a simple formula: when . As sequences grow longer, the savings approach 100%.
Quantifying the Savings
Let's compute concrete memory numbers for Mistral's configuration:
def attention_memory_bytes(seq_len, window_size, num_heads, dtype_bytes=2):
"""Calculate memory for attention scores matrix."""
if window_size is None:
# Full attention: n x n matrix per head
return seq_len * seq_len * num_heads * dtype_bytes
else:
# Sliding window: n x w matrix per head (approximately)
effective_size = min(seq_len, window_size)
return seq_len * effective_size * num_heads * dtype_bytes
def memory_comparison(seq_lengths, window_size=4096, num_heads=32):
"""Compare memory for full vs sliding window attention."""
results = []
for n in seq_lengths:
full_mem = attention_memory_bytes(n, None, num_heads)
swa_mem = attention_memory_bytes(n, window_size, num_heads)
savings = (1 - swa_mem / full_mem) * 100 if full_mem > 0 else 0
results.append(
{
"seq_len": n,
"full_attention_mb": full_mem / (1024**2),
"sliding_window_mb": swa_mem / (1024**2),
"savings_pct": savings,
}
)
return results
seq_lengths = [1024, 2048, 4096, 8192, 16384, 32768]
comparison = memory_comparison(seq_lengths)Attention Memory Comparison (32 heads, fp16):
Seq Length Full Attn Sliding (4K) Savings
------------------------------------------------------
1,024 64.0 MB 64.0 MB 0.0%
2,048 256.0 MB 256.0 MB 0.0%
4,096 1024.0 MB 1024.0 MB 0.0%
8,192 4096.0 MB 2048.0 MB 50.0%
16,384 16384.0 MB 4096.0 MB 75.0%
32,768 65536.0 MB 8192.0 MB 87.5%At the 8K context length that Mistral supports, sliding window attention uses exactly half the memory of full attention. At 32K tokens, the savings exceed 87%. These memory reductions directly translate to the ability to process longer sequences or use larger batch sizes.

The crossover point at the window size (4096) matters. Below this threshold, both methods use similar memory because sequences are shorter than the window. Beyond this point, sliding window attention's linear scaling provides increasing advantages.
