TL;DR
Full attention lets every token look at every earlier token, so the work and the memory for a sequence of length grow with . Sliding window attention (SWA) caps the look-back: each token attends only to the previous tokens and itself. Cost per layer becomes proportional to , and the key-value cache needs only entries instead of . Information still travels further than because each layer passes it one window forward, so after layers a token can be influenced by about 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 .
The math
Let be the token representations at some layer, and let be the window size. Under causal sliding window attention, token attends only to positions with . Write for this set. Attention at position is the usual softmax-weighted average of values, restricted to :
Here , and are the query, key and value vectors for positions and , and is the head dimension (see Attention Mechanism and Softmax). Positions outside 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 to , which is positions. The rolling cache below stores 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 attends to positions, so the number of query-key pairs in one layer is . For sliding window attention, each token attends to at most positions, so the number is at most . The ratio is
which falls as the sequence grows. For a fixed window, attention cost is linear in , not quadratic. Big-O Notation writes this as against .
Reach
Let be the representation of token at layer . It is computed from for . Unrolling the recursion, depends on input tokens back to position at most. So the theoretical receptive field of a -layer model is positions. The paper's example uses and reports a theoretical attention span of about 131K tokens at the last layer, which is .
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 entries per layer. With SWA only the last entries are ever read, so the cache can be a circular buffer of size . The key and value for position are written to slot , overwriting position , which no later token will need in this layer:
The cache memory is then entries per layer, independent of . The ratio of full-cache to rolling-cache size is . For and , that ratio is , which matches the paper's report of an eight-fold cache reduction at 32K tokens.
Worked examples
Take tokens with window , so each token attends to itself and the two tokens before it.
- Token 1 attends to 1: 1 pair.
- Token 2 attends to 2: 2 pairs.
- Token 3 attends to 3: 3 pairs.
- Token 4 attends to 4: 3 pairs.
- Token 5 attends to 5: 3 pairs.
- Token 6 attends to 6: 3 pairs.
- Total for SWA: .
- Full causal attention: .
Interpretation: SWA computes 15 of the 21 pairs, about 71 percent. The saving is small here because is close to . The gap widens as grows past the window, and the ratio approaches the scaling from the math section only when is much larger than .
Use the three-token window from the paper's figures, , and ask whether the token at position 6 can be influenced by position 0.
- In one layer, token 6 reads positions 3 to 6. Position 0 is not in reach.
- 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.
- Reach after layers is positions, and , 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.
Set . Before token 7 is processed, the cache holds the keys and values of positions 4, 5 and 6.
- Token 7 attends to positions 4 to 7, which is positions, using the cache plus its own fresh key.
- Slot assignment: position 4 lives in slot , position 5 in slot , and position 6 in slot .
- After token 7 is processed it is written to slot , overwriting position 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.
Take and . Per layer, full causal attention computes about pairs. SWA computes about 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 . 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
| Situation | Problem | Better choice |
|---|---|---|
| Long prompts with dense cross-references across the whole document | A detail far back reaches the current token only through compressed relays | Full attention in some layers, or retrieval |
| Needle-in-a-haystack retrieval at long range | Recall of one early fact degrades as the distance grows past the reach | Interleave global or full-attention layers |
| Short inputs well inside the window | SWA gives the same result as full attention, so it saves nothing | Full attention |
| Generation with a large cache budget | Rolling buffer discards positions that older tokens might still need | Keep a few global "sink" positions, as in Attention Sink |
| Naive implementation with a dense mask | Cost stays quadratic, so the saving never appears | Kernels that skip masked blocks, such as the FlashAttention-based ones Mistral used ([[flashattention-paper |
| Encoder tasks needing global summary tokens | Pure windows have no global token | Longformer-style global tokens |
The main failure mode is silent: a model trained with a window of 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 , and why?Show answer
It is entries, not . Only the last 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 .
QuestionCompute: with and , 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 pairs. Full causal attention computes pairs. SWA computes 21 of 36, about 58 percent, and the share would fall further as 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 layers, the influence reaches about 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
- Jiang et al. (2023), Mistral 7B, which introduces the rolling buffer cache and the reach and speed figures used above: https://arxiv.org/abs/2310.06825
- Dao et al. (2022), FlashAttention, the attention kernel that the Mistral implementation modified to skip masked blocks: https://arxiv.org/abs/2205.14135
- Beltagy, Peters and Cohen (2020), Longformer: The Long-Document Transformer: https://arxiv.org/abs/2004.05150