AI State of the Art
SOTA/Advanced Attention Mechanisms/21 min
Section 77

Sliding Window Attention (Mistral)

Listen as a podcast →

The problem: the cache grows infinitely

You generate a token. Then another. And another.

Each new token needs its keys and values stored in the "KV cache" so that following tokens can attend to it (its keys and values will be re-read at every step; its query, used only once, is never stored, why). After 1000 tokens, your cache is heavy. After 10K, it's huge. After 100K, your GPU explodes.

To be concrete: with a model like LLaMA-7B in FP16, each token in the KV cache takes up about 0.5 MB across all layers (2 × 32 layers × 32 heads × 128 dimensions × 2 bytes). A 100K token context = 50 GB of KV cache. Add the model's 14 GB of weights, and the 80 GB A100 is nearly full, for a single request. And this cache only grows during generation: it's a major bottleneck for production inference.

The problem isn't just memory: the bigger the cache, the slower each attention operation (it has to scan the entire cache). Latency increases linearly with sequence length.

Mistral's idea: forget the old stuff

Sliding Window Attention (SWA) is a disarmingly simple idea: each token only looks at the W previous tokens, and forgets the rest.

Token at position i→can see tokens [i−W+1,  i]\text{Token at position } i \rightarrow \text{can see tokens } [i - W + 1, \; i]

For example, with W = 4096, token #5000 sees tokens #905 to #5000, but not tokens #1 to #904. It's like a window that slides along the sequence, hence the name.

Three panels side by side. Left, Vanilla Attention: a 5 by 5 matrix over the sentence The cat sat on the, lower-triangular, filled with 1s below the diagonal and 0s above. Middle, Sliding Window Attention: the same matrix, but with additional 0s in the lower-left corner, leaving only a diagonal band of 1s of limited width. Right, Effective Context Length: four stacked rows of tokens representing four layers, with slanted lines showing how information from one token propagates upward layer by layer and covers an increasingly wide span, with a window size arrow at the top.
Left, classic attention: every token sees everything before it, hence the solid triangle. Middle, the sliding window: the lower-left corner drops to zero and only a band remains. That band is exactly the computation you save. The right-hand panel is the important one: even though each layer only sees one window, stacking layers passes information along step by step, so the real reach widens at every level.Source : Mistral 7B paper (Jiang et al., figure 1), via ar5iv

The intuition behind this approach: in practice, a token only needs its local context to make a good prediction. The word you're reading right now mostly depends on the 50-100 previous words, not the first word of the chapter. Very long-range dependencies exist (pronouns referring to a character mentioned 3 pages earlier), but they're rare compared to local dependencies.

A constant cache

Instead of a cache that grows indefinitely with generated tokens (O(L)), it stays constant at O(W):

ApproachCache after 8K tokensCache after 100K tokens
Global attention8K entries100K entries
Sliding Window (W=4K)4K entries4K entries

Whether you generate 8K or 1M tokens, the cache always stays at 4K. Memory is predictable and bounded. For a production system that needs to serve hundreds of requests in parallel, this is crucial: you can plan exactly how much memory each request will consume.

Effective range larger than the window

Each layer only sees a window of W tokens. But a Transformer has 32 stacked layers. At layer 1, the token sees W tokens. At layer 2, it sees tokens that themselves saw W tokens, so potentially 2W tokens. Theoretically, with 32 layers and W=4096, the effective range is 32×4096=13107232 \times 4096 = 131072 tokens (~128K). In practice, information attenuates through layers, but the range remains much larger than W.

Implementation: rolling buffer

The implementation is brutally simple. A circular buffer of size W. When it's full, new K/V entries overwrite the oldest ones.

index=positionmod  W\text{index} = \text{position} \mod W

The formula simply says: the slot to write to is the remainder of the position divided by W, once you reach the end of the array, you wrap around to the start. That's it. No memory copying, no dynamic allocation. Just a pointer going round and round in a fixed-size array. This implementation simplicity is a major advantage: less code = fewer bugs, less overhead, more reliability.

Chart titled Rolling Buffer vs Standard KV Cache for Mistral 7B. The horizontal axis is sequence length from 0 to over 30,000 tokens, the vertical axis is KV cache size in megabytes from 0 to 4500. A red curve, the standard KV cache, rises linearly to about 4100 MB at 33,000 tokens. A dashed blue horizontal line, the rolling buffer, stays flat at about 520 MB. A dotted vertical line marks w equals 4096, the point where the two lines cross. The area between them is shaded green and labelled memory saved.
The circular buffer seen from the memory side. The red curve is the classic cache: it keeps growing as the sequence gets longer. The blue line is the rolling buffer: flat, because it never holds more than W entries. The two cross exactly at W equals 4096 tokens, the Mistral 7B window. Below that, the sliding window buys you nothing; above it, the whole green gap is memory you never have to pay for.Source : Mistral Architecture: Sliding Window Attention, by Michael Brenndoerfer
Zero overhead

The implementation is so simple that there's literally zero overhead compared to standard attention. It's actually faster than global attention, because the cache is smaller and fits better in the GPU's fast memory levels (SRAM/L2 cache). Less data to scan = less time.

Mistral 7B: textbook case

Mistral 7B, the model that popularized SWA, uses a 4096-token window combined with Grouped Query Attention (GQA, dedicated lesson): 8 key/value heads instead of 32 (the 32 query heads share 8 K/V sets).

The combined effect is spectacular:

  • SWA reduces cache size (4K instead of the entire sequence)
  • GQA reduces the cache by an additional factor of 4 (8 K/V instead of 32)
  • Result: tiny KV cache, allowing servers to process many more requests in parallel

In production, this changes everything. At equal GPU memory, a per-request cache several times smaller mechanically means several times more requests served in parallel, that was the whole economic argument of Mistral 7B against the SWA/GQA-free models of its day.

Strengths and weaknesses

The advantages

  • Bounded KV cache: predictable memory, constant throughput regardless of sequence length
  • Ultra-compatible: works with Flash Attention, GQA, quantization, everything combines easily
  • Hardware efficiency: a contiguous window gives sequential memory accesses, which GPUs love. Much more efficient than an arbitrary selection of tokens
  • Simplicity: trivial to implement, trivial to debug, trivial to deploy

The problems

  • Forced forgetting: information beyond the window is irretrievably lost for a given layer
  • Long-recall tasks: retrieving specific information from the beginning of a long document is difficult
Concrete failure example

Imagine a 100K token document. The question is about sentence 2 (at the very beginning). With a 4K window, the answer token at position 100K can only directly see positions 96K-100K. The information from position 2 must "survive" by being propagated layer by layer through 96K tokens. In theory it's possible (effective range = 128K), in practice the information attenuates heavily, it's the neural network version of the "telephone game."

Smart variants

Sink tokens (Attention Sink)

Keep the first tokens (the system prompt, instructions) permanently in the cache, even when the window would have forgotten them. Empirical observation: the first tokens often receive disproportionate attention (they serve as an "attention sink"). Keeping them considerably stabilizes performance on long sequences.

Four charts side by side for Llama-2-7B, Pythia-12B, Falcon-7B and MPT-7B. Each plots log perplexity against input length from 0 to 20,000 tokens for four methods. The blue Dense Attention curve blows up as soon as the input exceeds the pre-training window, marked by a red vertical line. The orange Window Attention curve spikes as soon as the input exceeds the cache size, marked by a purple vertical line. The green Sliding Window with Re-computation curve and the red StreamingLLM curve stay low and flat across the whole range.
Measured proof that keeping the first tokens changes everything. The orange curve is a bare sliding window: it collapses exactly when the earliest tokens fall out of the cache. The red curve is the same window plus a handful of sink tokens kept permanently: it stays flat out to 20,000 tokens. Same method, same memory budget give or take a few tokens, and yet one holds and the other breaks.Source : StreamingLLM paper (Xiao et al., figure 3), via a review on velog

Local + global attention

Combine a local window with a few "global" tokens visible to everyone. This is the Longformer/BigBird approach applied to decoding. A compromise between SWA's efficiency and global attention's range.

Dilated attention

Instead of a contiguous window of W tokens, take the W/2 most recent tokens AND spaced-out tokens (say, one token in four, over a larger window). This covers a much greater range for the same memory budget.

Comparison with other approaches

TechniqueComplexityCacheGlobal recallImplementation
Standard attentionO(L^2)O(L)PerfectStandard
Sliding WindowO(L*W)O(W)Via multi-layerTrivial
Sparse (Longformer)O(L*(W+G)), G = global tokensO(L)Via global tokensComplex
SSM (Mamba)O(L)O(1) fixedCompressed in stateSpecialized
Verdict: pragmatic and effective

Sliding Window Attention isn't intellectually spectacular, it's a simple, almost trivial idea. But that's exactly what makes it strong. The Mistral models proved that well-calibrated local attention rivals global attention on the vast majority of tasks, while being more memory and latency efficient. In production, simple and reliable beats complex and theoretically optimal. That's why SWA has become an industry standard.

Check your understanding0 / 5

1. With a window of W = 4096, what happens to the KV cache as generation goes from 8K to 100K tokens?

2. Each layer only sees W = 4096 tokens. Why does the model's real reach extend far beyond that window?

3. How does the rolling buffer handle a new token arriving once the window is full?

4. A 100K-token document, and the question is about sentence 2, at the very beginning. Why is this SWA's typical failure case?

5. What are sink tokens (attention sink), and why keep them?