Mistral Architecture › Sliding Window Attention

Michael BrenndoerferUpdated August 6, 202516 min read
Language AI HandbookAll chapters
Part 29 of 67Modern Decoder Models
Chapter 211Mistral Architecture › Sliding Window Attention
Reading section 3 of 14 · Sliding Window Attention · 16 minSection 3 of 14 · 16 min

Book contents

Section 3 of 14 · 16 min read

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 nn tokens, that's nn scores per token, and nn tokens total, giving n×n=n2n \times n = n^2 scores. Store these in memory, and you need space proportional to n2n^2. Compute them, and you need operations proportional to n2n^2.

This quadratic scaling creates a harsh reality:

Attention score counts grow quadratically with sequence length. Each 4x increase in length produces a 16x increase in scores.
Sequence LengthAttention ScoresGrowth Factor
1,024 tokens~1 million1x
4,096 tokens~17 million16x
16,384 tokens~268 million256x

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 ii to attend to all tokens from 0 to ii, we restrict it to a fixed window of size ww. Token ii can only attend to tokens in positions max⁡(0,i−w+1)\max(0, i - w + 1) through ii, a span of at most ww 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 Maski,j\text{Mask}_{i,j} determines whether query position ii can attend to key position jj:

Maski,j={0if max⁡(0,i−w+1)≤j≤i−∞otherwise\text{Mask}_{i,j} = \begin{cases} 0 & \text{if } \max(0, i-w+1) \leq j \leq i \\ -\infty & \text{otherwise} \end{cases}

Let's unpack each component:

  • ii: the query position, meaning the token that's "asking" for information
  • jj: the key position, meaning the token that might provide information
  • ww: the window size (4096 for Mistral 7B)
  • max⁡(0,i−w+1)\max(0, i-w+1): the leftmost position in the window, clamped to 0 for early tokens
  • The condition max⁡(0,i−w+1)≤j≤i\max(0, i-w+1) \leq j \leq i: defines the valid window, positions jj can attend to

The mask values themselves serve a specific purpose in the attention computation:

  • 00: When added to attention scores, leaves them unchanged, allowing attention
  • −∞-\infty: When added to attention scores, makes them negative infinity. After softmax, e−∞=0e^{-\infty} = 0, 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 −∞-\infty 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 nn tokens computes scores against all nn tokens, giving O(n2)O(n^2) operations. With sliding window attention, each of nn tokens computes scores against only ww tokens, giving O(n⋅w)O(n \cdot w) operations.

When ww is fixed (4096 for Mistral), this becomes O(n)O(n): linear in sequence length. The difference is significant:

  • Full attention at 32K tokens: 32,7682≈1.0732{,}768^2 \approx 1.07 billion scores
  • Sliding window at 32K tokens: 32,768×4,096≈13432{,}768 \times 4{,}096 \approx 134 million scores

That's an 8x reduction at 32K tokens, and the gap widens as sequences grow longer.

Out[6]:
Visualization
Log-scale line plot showing full attention curve rising steeply while sliding window attention grows linearly.
Computational complexity comparison showing quadratic O(n^2) scaling for full attention versus linear O(n*w) scaling for sliding window attention. At 32K tokens, sliding window requires 8x fewer operations.
Out[7]:
Visualization
Lower triangular heatmap showing full causal attention pattern where darker cells indicate allowed attention.
Standard causal attention mask. Every token can attend to all previous tokens, creating a lower triangular pattern. Memory and compute scale quadratically with sequence length.
Banded diagonal heatmap showing sliding window attention pattern with fixed window width.
Sliding window attention mask with window size 4. Each token attends only to the 4 most recent tokens, creating a banded pattern. Memory and compute scale linearly with sequence length.

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 ww 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:

  1. Layer 1: Token ii sees positions [i−w+1,i][i-w+1, i], a direct window of ww tokens
  2. Layer 2: Token ii attends to tokens that themselves saw ww tokens back, extending indirect reach to 2w2w
  3. Layer ℓ\ell: Information can travel up to ℓ×w\ell \times w positions through layered propagation

This gives us the receptive field formula:

Rℓ=ℓ×wR_\ell = \ell \times w

where:

  • RℓR_\ell: the receptive field at layer ℓ\ell, measuring how far back information can theoretically travel
  • ℓ\ell: the layer number (1 to LL)
  • ww: the sliding window size

Applying the Formula to Mistral

For Mistral 7B with L=32L = 32 layers and w=4096w = 4096:

R32=32×4096=131,072 tokensR_{32} = 32 \times 4096 = 131{,}072 \text{ tokens}

This theoretical receptive field of 131K tokens vastly exceeds Mistral's 8K context length. Even at layer 2, the receptive field is 2×4096=8,1922 \times 4096 = 8{,}192 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.

Out[8]:
Visualization
Line plot showing receptive field expanding linearly from 4K tokens at layer 1 to 128K tokens at layer 32.
Receptive field growth across transformer layers. With each layer, the effective context a token can access grows linearly. By layer 32, the receptive field covers over 130K tokens, far exceeding the typical context window.

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 nn query positions and nn key positions, we have n×nn \times n 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:

Mfull=n×n×h×b=n2⋅h⋅bM_{\text{full}} = n \times n \times h \times b = n^2 \cdot h \cdot b

For sliding window attention, each query position only attends to min⁡(n,w)\min(n, w) key positions. When the sequence is shorter than the window (n≤wn \leq w), we still compute nn scores per query. When the sequence exceeds the window (n>wn > w), we compute exactly ww scores per query:

Msliding=n×min⁡(n,w)×h×bM_{\text{sliding}} = n \times \min(n, w) \times h \times b

Let's define each variable precisely:

  • MM: total memory in bytes for all attention score matrices
  • nn: sequence length (number of tokens)
  • ww: sliding window size (4096 for Mistral)
  • hh: number of attention heads (32 for Mistral)
  • bb: bytes per element (2 for fp16, 4 for fp32)

The Crossover Point

The formulas reveal a key insight: the two methods behave identically when n≤wn \leq w. Both compute the same n×nn \times n attention matrix because the window hasn't started to "slide" yet. The divergence occurs when n>wn > w:

  • Full attention: Memory grows as n2n^2, accelerating as sequences lengthen
  • Sliding window: Memory grows as n⋅wn \cdot w, which is linear in nn since ww is fixed

For Mistral with w=4096w = 4096, the crossover happens at 4096 tokens. Below this, both methods are equivalent. Above this, sliding window provides increasing savings:

  • At n=8192n = 8192: Sliding window uses 8192×409681922=12\frac{8192 \times 4096}{8192^2} = \frac{1}{2} the memory (50% savings)
  • At n=32768n = 32768: Sliding window uses 32768×4096327682=18\frac{32768 \times 4096}{32768^2} = \frac{1}{8} the memory (87.5% savings)

The savings percentage follows a simple formula: 1−wn1 - \frac{w}{n} when n>wn > w. As sequences grow longer, the savings approach 100%.

Quantifying the Savings

Let's compute concrete memory numbers for Mistral's configuration:

In[9]:
Code
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)
Out[10]:
Console
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.

Out[11]:
Visualization
Log-scale plot comparing memory growth, with full attention curving upward quadratically and sliding window attention flattening into linear growth.
Memory consumption comparison between full attention and sliding window attention. Full attention grows quadratically (red), while sliding window attention grows linearly after reaching the window size (blue). The gap widens significantly at longer sequences.

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.

Out[12]:
Visualization
Line plot showing memory savings percentage increasing from 0% at 4K tokens to nearly 90% at 64K tokens.
Memory savings from sliding window attention as a function of sequence length. Savings approach 100% as sequences grow longer, following the formula 1 - w/n where w is the window size (4096) and n is the sequence length.