Search

Search papers and lessons

Sliding Window Attention

Level 3 · 14 min read

Sliding window attention lets each token attend only to a fixed number of recent tokens, so compute and cache grow linearly with length, while stacked layers still pass information further along.

On this page

  • Colour = topic mix
  • Linear algebra
  • Neural network basics
  • Discrete math
  • Architectures
  • Efficiency
  • Probability
  • Sign in to see your progress

TL;DR

Full attention lets every token look at every earlier token, so the work and the memory for a sequence of length nn grow with n2n^2. Sliding window attention (SWA) caps the look-back: each token attends only to the previous WW tokens and itself. Cost per layer becomes proportional to n⋅Wn \cdot W, and the key-value cache needs only WW entries instead of nn. Information still travels further than WW because each layer passes it one window forward, so after kk layers a token can be influenced by about k⋅Wk \cdot W positions back.

Where you'll see it: long-context decoder language models such as Mistral 7B, where the attention window is 4096 tokens, and in long-document encoders such as Longformer, which combine a window with a few global tokens.

Intuition

Reading with a narrow window

Imagine reading a long novel through a slit that shows only the last few lines. You never see the whole book at once, so you cannot look up a detail from chapter one directly. But as you read, each sentence you process has already absorbed a summary of the sentences before it, and those summaries absorbed earlier ones in turn. A detail from chapter one can reach chapter ten through a chain of hand-offs, even though no single step sees further than the slit.

That is the idea. In a transformer, each layer's token representations are built from the previous layer's representations at nearby positions. Stack many layers and the reach of the stack grows, even though each layer only looks a short way back.

Why bother? Full attention computes a score for every pair of positions. For a 32,000-token prompt that is over a billion pairs in every layer, and during generation the cache of keys and values for all past tokens grows with every new token. Most of the useful information for predicting the next word sits close by, and the rest can often reach the current token through the layers. SWA spends the compute on the near pairs and lets depth carry the rest.

flowchart BT
    subgraph L0[Input]
        i1[t1] ~~~ i2[t2] ~~~ i3[t3] ~~~ i4[t4]
    end
    subgraph L1[Layer 1]
        a2[t2] ~~~ a3[t3] ~~~ a4[t4]
    end
    subgraph L2[Layer 2]
        b4[t4]
    end
    i2 --> a3
    i3 --> a3
    i3 --> a4
    i4 --> a4
    a3 --> b4
    a4 --> b4

The diagram uses a window of one token back, so each position reads itself and the position before it in the layer below. Layer-1 token 3 has read tokens 2 and 3, and layer-1 token 4 has read tokens 3 and 4. Layer-2 token 4 reads both of those, so it carries information from token 2, two positions back, after two layers. That is K⋅W=2⋅1K \cdot W = 2 \cdot 1.

The math

Definition: Sliding window attention

Let x1,…,xnx_1, \dots, x_n be the token representations at some layer, and let WW be the window size. Under causal sliding window attention, token ii attends only to positions jj with i−W≤j≤ii - W \le j \le i. Write Si={max⁡(1,i−W),…,i}S_i = \{\max(1, i-W), \dots, i\} for this set. Attention at position ii is the usual softmax-weighted average of values, restricted to SiS_i:

SWA(Q,K,V)i=∑j∈Siexp⁡ ⁣(qi⋅kj/d)∑l∈Siexp⁡ ⁣(qi⋅kl/d) vj\text{SWA}(Q, K, V)_i = \sum_{j \in S_i} \frac{\exp\!\left(q_i \cdot k_j / \sqrt{d}\right)}{\sum_{l \in S_i} \exp\!\left(q_i \cdot k_l / \sqrt{d}\right)}\, v_j

Here qiq_i, kjk_j and vjv_j are the query, key and value vectors for positions ii and jj, and dd is the head dimension (see Attention Mechanism and Softmax). Positions outside SiS_i receive weight zero, so the mask is the only change from ordinary causal attention.

The paper that popularised this form, Mistral 7B, writes the window as positions from i−Wi-W to ii, which is W+1W + 1 positions. The rolling cache below stores WW past entries plus the current one, so the two descriptions agree. Implementations differ by one here, and the choice does not change the argument.

Cost

For full causal attention, token ii attends to ii positions, so the number of query-key pairs in one layer is ∑i=1ni=n(n+1)/2≈n2/2\sum_{i=1}^{n} i = n(n+1)/2 \approx n^2/2. For sliding window attention, each token attends to at most W+1W + 1 positions, so the number is at most n(W+1)n(W+1). The ratio is

SWA pairsfull causal pairs≈2(W+1)n\frac{\text{SWA pairs}}{\text{full causal pairs}} \approx \frac{2(W+1)}{n}

which falls as the sequence grows. For a fixed window, attention cost is linear in nn, not quadratic. Big-O Notation writes this as O(n⋅W)O(n \cdot W) against O(n2)O(n^2).

Reach

Let hi(k)h^{(k)}_i be the representation of token ii at layer kk. It is computed from hj(k−1)h^{(k-1)}_j for j∈Sij \in S_i. Unrolling the recursion, hi(k)h^{(k)}_i depends on input tokens back to position i−kWi - kW at most. So the theoretical receptive field of a KK-layer model is K⋅WK \cdot W positions. The paper's example uses W=4096W = 4096 and reports a theoretical attention span of about 131K tokens at the last layer, which is 4096×324096 \times 32.

The rolling buffer cache

During generation the keys and values of every past token must be kept in the KV Cache. With full attention the cache grows to nn entries per layer. With SWA only the last WW entries are ever read, so the cache can be a circular buffer of size WW. The key and value for position ii are written to slot i mod Wi \bmod W, overwriting position i−Wi - W, which no later token will need in this layer:

slot(i)=i mod W\text{slot}(i) = i \bmod W

The cache memory is then WW entries per layer, independent of nn. The ratio of full-cache to rolling-cache size is n/Wn / W. For n=32,768n = 32{,}768 and W=4096W = 4096, that ratio is 88, which matches the paper's report of an eight-fold cache reduction at 32K tokens.

Worked examples

Example
Counting pairs on a tiny sequence

Take n=6n = 6 tokens with window W=2W = 2, so each token attends to itself and the two tokens before it.

  1. Token 1 attends to 1: 1 pair.
  2. Token 2 attends to 2: 2 pairs.
  3. Token 3 attends to 3: 3 pairs.
  4. Token 4 attends to 4: 3 pairs.
  5. Token 5 attends to 5: 3 pairs.
  6. Token 6 attends to 6: 3 pairs.
  7. Total for SWA: 1+2+3+3+3+3=151 + 2 + 3 + 3 + 3 + 3 = 15.
  8. Full causal attention: 1+2+3+4+5+6=211 + 2 + 3 + 4 + 5 + 6 = 21.

Interpretation: SWA computes 15 of the 21 pairs, about 71 percent. The saving is small here because nn is close to WW. The gap widens as nn grows past the window, and the ratio approaches the 2(W+1)/n2(W+1)/n scaling from the math section only when nn is much larger than WW.

Example
How far information can travel

Use the three-token window from the paper's figures, W=3W = 3, and ask whether the token at position 6 can be influenced by position 0.

  1. In one layer, token 6 reads positions 3 to 6. Position 0 is not in reach.
  2. After two layers, token 6 has absorbed a summary of positions 3 to 6 from layer one. Position 3 in layer one had read positions 0 to 3, so position 0 has flowed through.
  3. Reach after KK layers is K⋅W=2×3=6K \cdot W = 2 \times 3 = 6 positions, and 6−6=06 - 6 = 0, so the influence arrives.

Interpretation: depth buys reach. In the paper's 4096-token setting with 32 layers, the same argument reaches about 131K positions. The reach is indirect, though. A specific detail from position 0 is only available to token 6 as a blended, compressed signal, which may not survive intact.

Example
A rolling cache at position 7

Set W=3W = 3. Before token 7 is processed, the cache holds the keys and values of positions 4, 5 and 6.

  1. Token 7 attends to positions 4 to 7, which is W+1=4W + 1 = 4 positions, using the cache plus its own fresh key.
  2. Slot assignment: position 4 lives in slot 4 mod 3=14 \bmod 3 = 1, position 5 in slot 22, and position 6 in slot 00.
  3. After token 7 is processed it is written to slot 7 mod 3=17 \bmod 3 = 1, overwriting position 4.
  4. The cache now holds positions 5, 6 and 7, and the buffer size stayed at 3 throughout.

Interpretation: a sequence of any length needs only three cache entries per layer. The memory cost is fixed, and the model still sees the recent past it needs for the next prediction.

Example
A realistic setting: a 32K prompt

Take n=32,768n = 32{,}768 and W=4096W = 4096. Per layer, full causal attention computes about n2/2≈5.4×108n^2 / 2 \approx 5.4 \times 10^8 pairs. SWA computes about n(W+1)≈1.34×108n(W+1) \approx 1.34 \times 10^8 pairs, a ratio of about 0.25. The cache is 8 times smaller. The paper reports that its SWA changes, built on FlashAttention and xFormers kernels, gave a 2x speed-up over a vanilla attention baseline at a 16K sequence length with W=4096W = 4096. The pair count is not the whole story: a naive implementation that builds a full mask and multiplies it out still pays the quadratic cost, so the speed-up depends on a kernel that skips the masked blocks.

Tradeoffs and failure modes

SituationProblemBetter choice
Long prompts with dense cross-references across the whole documentA detail far back reaches the current token only through compressed relaysFull attention in some layers, or retrieval
Needle-in-a-haystack retrieval at long rangeRecall of one early fact degrades as the distance grows past the reachInterleave global or full-attention layers
Short inputs well inside the windowSWA gives the same result as full attention, so it saves nothingFull attention
Generation with a large cache budgetRolling buffer discards positions that older tokens might still needKeep a few global "sink" positions, as in Attention Sink
Naive implementation with a dense maskCost stays quadratic, so the saving never appearsKernels that skip masked blocks, such as the FlashAttention-based ones Mistral used ([[flashattention-paper
Encoder tasks needing global summary tokensPure windows have no global tokenLongformer-style global tokens

The main failure mode is silent: a model trained with a window of WW can still answer questions that look local, and fail on questions that need distant evidence, without any error message. Evaluate on long-range retrieval, not only on perplexity, which is dominated by nearby tokens. A second failure is a cache that is too small for the reach the model needs. Rolling buffers drop keys for positions that were once reachable, which is safe only because the layer stack has already absorbed their information.

SWA also interacts with Positional Encoding: the window is defined by relative distance, so a position scheme that encodes relative offsets fits it naturally.

History

Local attention patterns predate large language models. Sparse Transformers (Child and colleagues, 2019) factorised attention into local and strided patterns to reduce the cost of attending over long images and audio. Longformer (Beltagy, Peters and Cohen, 2020) made the sliding window the main pattern for long-document encoders, and added a handful of global tokens that attend everywhere so that the model can aggregate a document-level summary.

The window reached decoder-only language models through Mistral 7B in 2023. The paper combined it with grouped-query attention and a rolling buffer cache, and reported that the 7B model outperformed Llama 2 13B on the benchmarks it tested. The paper presents the window and the fixed-size cache as the means of handling long sequences at reduced inference cost.

Check yourself

QuestionRecall: what is the key-value cache size per layer under sliding window attention with window WW, and why?Show answer

It is WW entries, not nn. Only the last WW keys and values are ever read by a later token in the same layer, so older entries can be overwritten in a circular buffer. The cache size stops growing once the sequence is longer than WW.

QuestionCompute: with W=2W = 2 and n=8n = 8, how many query-key pairs does SWA compute in one layer, under the convention that each token attends to itself and the two tokens before it? Compare with full causal attention.Show answer

Positions 1 and 2 attend to 1 and 2 tokens, giving 1 and 2 pairs. Each position from 3 to 8 attends to 3 tokens. That is 1+2+6×3=211 + 2 + 6 \times 3 = 21 pairs. Full causal attention computes 8×9/2=368 \times 9 / 2 = 36 pairs. SWA computes 21 of 36, about 58 percent, and the share would fall further as nn grows.

QuestionWhy does a stack of sliding-window layers still let a token use information from far outside its window, and what is the limitation of that route?Show answer

Each layer lets a token read a summary of the window from the layer below, and that summary already contains information from its own window. So after KK layers, the influence reaches about K⋅WK \cdot W positions back. The limitation is that the far information arrives mixed and compressed into the hidden state at each hop, so exact recall of a specific early token is weaker than with direct attention.

QuestionApplied: you are serving a model with a 4096-token window and a 32-layer stack to users who send 100K-token documents. What do you check before trusting it on questions about the middle of the document, and what would you change if it failed?Show answer

Test long-range retrieval directly, placing a fact at varied depths in the document and asking for it. Compare against a full-attention baseline if one exists. Perplexity on the document will not reveal the failure, because most predictions depend on nearby text. If recall fails in the middle, the options are a model with full-attention layers interleaved, a retrieval step that fetches the relevant passage before generation, or chunking the document so each query sees the part that matters. Keeping sink tokens in the cache is a further refinement, not a substitute for those.

Sources