# What Is Sliding-Window and Sparse Attention?

> How sliding-window and sparse attention cut the cost of long text, what they miss, and how models mix them, for your AI interview.

**In short:** Sliding-window attention lets each token look only at a fixed number of nearby tokens, so cost grows in a straight line instead of with the square of the length. Sparse attention is the wider family of patterns that skip most pairs, and it can miss links to distant tokens.

AI and LLM interview question Q059, Transformer architecture. Advanced, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/sliding-window-and-sparse-attention

## Say it in 30 seconds

Full attention lets every token look at every earlier token, so long text gets very costly. Sliding-window attention fixes that: each token looks only at a fixed number of nearby tokens, so the cost grows in a straight line. Sparse attention is the wider idea of skipping most pairs, often with a few global tokens that see everything. The catch is that far clauses can be missed, so real models mix in full-attention layers.

## Say it in 2 minutes

Full attention lets every token look at every earlier token. That is fine for a short message, but a 32,000 token contract bundle makes a huge grid of pairs. Doubling the length makes the work about four times bigger, so the cost grows with the square of the text.

Sliding-window attention changes the rule. Each token looks only at the last W tokens, so the work for each token stays the same however long the text gets. Stacked layers still let information travel further, because each layer passes on what it has seen. Sparse attention is the wider family. BigBird adds a few global tokens that see the whole text, and Longformer adds task-chosen global attention, so most pairs are skipped on purpose.

The trade-off is real. A token cannot see a far clause directly, so a fact on page one may be missed when the question is about page forty. Teams handle that by mixing layers: some with full attention, some with a window. OpenAI's gpt-oss models and Google's Gemma 2 both mix the two kinds of layer. I would test on real bundles, asking for clauses at the start and the end, and measure both speed and misses.

## What is sliding-window and sparse attention, in plain words?

Attention is how a model decides which earlier tokens matter for the one it is reading now. A token is a chunk of text, often a word or part of one. Full attention scores every token against every earlier token. That is fine for a short message. For long text, the pairs add up fast.

Sliding-window attention takes a shortcut. Each token looks only at the last W tokens, where W is a fixed window size. The window slides along the text as the model moves forward. Sparse attention is the wider family. It means any pattern that skips most pairs on purpose.

Picture a claims adjuster at an insurer. A good adjuster checks each new page against the pages just before it, and pulls the policy front sheet out to compare with the whole file. She does not compare every page with every other page. Sliding windows and sparse patterns work the same way.

In the contract case below, a legal team's reader handles a 32,000 token agreement bundle. Full attention does far more work than the job needs, and the reader must still link a definition on page one to a clause on page forty.

- **Token:** A chunk of text the model reads as one unit, often a word or part of a word.
- **Window:** The last W tokens a token is allowed to look back at.
- **Sparse attention:** Any attention pattern that skips most token pairs on purpose.
- **Global token:** A marked token that looks at the whole text, and that every token can look at.
- **Causal attention:** A model that writes text only looks back at earlier tokens, never ahead.

## How does sliding-window attention work?

Each token scores itself and the tokens inside its window, and nothing else. If W is 4,096, every token does at most 4,096 scores in each layer, however long the bundle is. The work per token stops growing, so the total grows in a straight line with the length.

*Diagram, Two ways to look back: Full attention lets each token look at every earlier token, so the cost grows with the square of the length. A sliding window keeps each look-back at W tokens, so the cost grows in a straight line.*
1. Full attention scores each token against every token before it.
2. A window scores each token against only the last W, so the work per token stays fixed.

Because the span is fixed, the model can keep a rolling buffer as its cache, the store of earlier tokens it reuses. A rolling buffer is a fixed-size memory that overwrites its oldest entries. Only the last W entries need to stay there, so memory does not keep growing with the text. Mistral 7B v0.1, from 2023, used this design.

> **Tip:** The one-line answer: a window caps how far each token looks, so the work per token stops growing with the text.

## What do sparse patterns add beyond a window?

A pure window misses links to far tokens. Sparse designs add a few extra links on purpose. The main families are these.

- **Local windows:** Each token sees its nearby tokens. This is the sliding window from the last section.
- **Global tokens:** A few marked tokens see the whole text, and every token can see them. A question or a defined term can sit there.
- **Factorised patterns:** The attention grid is split into sparse parts, so a token reaches far tokens through a fixed rule rather than a full grid.

> "Transformers are powerful sequence models, but require time and memory that grows quadratically with the sequence length." (Sparse Transformers paper)
>
> "Longformer's attention mechanism is a drop-in replacement for the standard self-attention and combines a local windowed attention with a task motivated global attention." (Longformer paper)
>
> "To remedy this, we propose, BigBird, a sparse attention mechanism that reduces this quadratic dependency to linear." (BigBird paper)

*Diagram, Sparse patterns skip most pairs: A long document feeds two kinds of links: local windows for nearby tokens, and a few global tokens that see the whole text. Most other pairs are never scored, so the work stays in a line.*
1. Each token is linked to its nearby tokens only.
2. A few marked tokens are linked to the whole text.
3. The nearby links are scored and passed on.
4. The marked tokens' links are scored and passed on too.

BigBird's paper says its sparse design reduces the quadratic cost to linear. Longformer's paper says its attention is a drop-in replacement for standard self-attention. Both papers are from 2020.

## What do these designs give up, and how are they mixed?

The trade-off is simple. A token that cannot see a far clause directly may miss it, or only catch it weakly through the layers. Global tokens help, but they only cover the few positions marked for that job.

- **Sliding window: Cheap per token.** The cost stays in a line. Good for long reading with local context. Far links need help from layers.
- **Full attention: Sees everything.** Every link is scored. The number of scores grows with the square, so long bundles get slow.
- **Hybrid: Mixed layers.** Some layers keep full attention, and the rest use windows or sparse patterns. Gemma 2 and gpt-oss use this mix.

Real models mix the two. OpenAI's gpt-oss models alternate full attention (every token sees every earlier token) with banded sparse attention (each token sees a band of nearby tokens). Google's Gemma 2 paper, from 2024, describes interleaving local and global attention. I can't see inside closed models, so in an interview I would name only the designs their makers have published.

> **Tip:** Say it like this: sparse patterns cut the cost from the square to a line, and the price is that far links need extra help, such as full layers or global tokens.

## How many pairs does a window save in a worked example?

Here is a made-up legal review tool. The script counts the scores for one attention view (a head, one of several run in parallel in each layer) on one pass, treating the model as a causal one that only looks back. The window is 4,096 tokens. Full attention counts every earlier pair, so the count is n times (n plus 1), divided by two.

```python
# A made-up legal review tool reads a 32,000 token contract bundle. Each token looks back at itself and earlier
# tokens only, so we count the pairs for one head on one pass.
WINDOW = 4096

def full_pairs(n):
    # token i looks at i tokens (itself included), so the total is 1 + 2 + ... + n
    return n * (n + 1) // 2

def window_pairs(n, w):
    # token i looks back at most w tokens, so the total stops growing once i passes w
    return sum(min(i, w) for i in range(1, n + 1))

for n in [4096, 8192, 16384, 32768]:
    full = full_pairs(n)
    win = window_pairs(n, WINDOW)
    print(f"{n:,} tokens: full {full:,} pairs, window {win:,} pairs, full is {full / win:.1f} times the window")
```

Output:

```text
4,096 tokens: full 8,390,656 pairs, window 8,390,656 pairs, full is 1.0 times the window
8,192 tokens: full 33,558,528 pairs, window 25,167,872 pairs, full is 1.3 times the window
16,384 tokens: full 134,225,920 pairs, window 58,722,304 pairs, full is 2.3 times the window
32,768 tokens: full 536,887,296 pairs, window 125,831,168 pairs, full is 4.3 times the window
```

Look at the last row. At 32,768 tokens, full attention scores about 4.3 times as many pairs as the window does. The gap widens with length, because the full count grows with the square and the window count grows in a line.

At 4,096 tokens the two counts are equal, so the window saves nothing until the text is longer than the window. Real models run many heads and layers, so the totals are bigger, but the trend is the number to remember: the gap grows with length.

### How would you pick an attention design for a contract reader?

1. **Start from the question:** Do the answers need clauses far apart, like a defined term on page one used on page forty? If yes, plan for links across the whole bundle.
2. **Mix the layers:** Use window layers for most of the stack, and keep some full-attention layers so far links survive.
3. **Mark a few global tokens:** Give the defined-terms section and the question a global role, so every token can reach them.
4. **Test on real bundles:** Ask for the clause at the start and at the end of 50 real agreements, count the misses, then measure speed. Keep the design that misses the fewest.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: each token looks only at a window, or at a chosen pattern.
- [ ] Why it helps: the cost grows in a line instead of with the square.
- [ ] What sparse means: any pattern that skips most pairs on purpose.
- [ ] Global tokens, and why they help far links.
- [ ] The trade-off: far clauses may be missed without extra layers or global tokens.
- [ ] Hybrid designs, and how you would test them on real files.

**Common traps**

- Trap: "A window is always cheaper, so use it everywhere." Better: It is cheaper, but far links can be lost. Mix in full layers or global tokens where the task needs them.
- Trap: "Sliding window means the app drops the old chat turns." Better: That is trimming the chat, a product choice. Sliding-window attention is a layer design inside the model, and the full text is still in the input.
- Trap: "Sparse attention is just a smaller model." Better: It changes which pairs get scored inside the model. The model's size stays the same.

## Can you spot the design that misses far clauses?

**Spot the risk:** Which contract reader design can miss a clause on page one when the question is about page forty?

A. Full attention over all 32,000 tokens, in every layer.
B. A sliding window of 4,096 tokens in every layer, with no global tokens.
C. Full attention in every fourth layer, and a window in the rest.
D. Full attention computed in tiles on the GPU, with the same answer.

**Answer:** B. Each layer lets a token see only 4,096 tokens back, so a clause far away is reached only weakly through the layers. The other three keep a full view somewhere, or compute the full view exactly.

**Quick check:** A team must cut attention cost on 32,000 token bundles, and page one must still link to page forty. Which change fits best?

A. Add more instructions to the system prompt
B. Use window layers for most of the stack, with some full-attention layers so far links survive
C. Drop every token after page ten
D. Lower the temperature

**Answer:** B. Window layers keep the cost in a line for most of the stack, and the full layers let distant clauses link. Dropping text loses the clause, and the prompt and temperature do not change attention cost.

## Can you answer these from memory?

**Flash cards**

- **What is sliding-window attention?** Each token looks only at the last W tokens, so the cost grows in a straight line.
- **What is sparse attention?** Any pattern that skips most token pairs on purpose, such as windows plus global tokens.
- **What is a global token?** A marked token that sees the whole text, so far links can still form.
- **What is the main trade-off?** Cheaper per token, but a token cannot see far text directly.
- **Who uses these designs?** Longformer, BigBird, Mistral 7B, Gemma 2 and gpt-oss use windows or sparse layers.
- **Why does full attention get slow?** Every token is scored against every earlier token, so doubling the text makes four times the work.

## Likely follow-up questions

- Q056 Why is attention quadratic in sequence length? https://designervenkat.online/interview/ai/why-is-attention-quadratic-in-sequence-length
- Q057 What is FlashAttention? https://designervenkat.online/interview/ai/what-is-flashattention
- Q058 Multi-query vs grouped-query attention? https://designervenkat.online/interview/ai/multi-query-vs-grouped-query-attention
- Q055 What is the KV cache, and why does it speed up generation? https://designervenkat.online/interview/ai/what-is-the-kv-cache
- Q050 What is causal (masked) attention? https://designervenkat.online/interview/ai/what-is-causal-masked-attention
- Q043 What is self-attention? https://designervenkat.online/interview/ai/what-is-self-attention
