What Is Sliding-Window Attention? Local and Global Layers

By LatestLLM Editorial · Published · Facts verified · 9 min read

Also called: local attention, windowed attention, sliding window, hybrid local-global attention, SWA

Before this: Attention, KV cache

In one line

Sliding-window attention limits each token to reading only the most recent fixed number of tokens, so attention work and cache size stop growing with the length of the text.

Sliding-window attention, simply and technically

In plain English

Ordinary attention lets every word look at every earlier word. That is thorough but expensive: the longer the text, the more each new word has to look at. Sliding-window attention sets a limit. Each word only looks at the last handful of words, such as the previous 128 or 1,024, and ignores anything older.

Usually a word's meaning depends mostly on what is close to it, so the limit costs little. To keep the ability to connect far-apart ideas, models mix the two kinds of layer: many layers with a short window, and some layers that still read everything. Gemma 4 uses five short-window layers for every full one.

Think of it like this: Sliding-window attention is like reading with a ruler under the line you are on: you see the current sentence and the few before it clearly and nothing farther back. Occasionally you stop and flip back through the whole chapter, which is the full-attention layer. The picture leaves out one thing: information can still travel far, because each layer passes what it learned to the next, so facts hop along from window to window.

Everyday example: Reading a long contract

A model reads a 100,000-word contract, answering a question about a clause.

Input:

Question about one clause in a very long text

Output:

Many layers read a short window, a few read everything

What it shows: Most layers look only at the neighbouring paragraphs, which is enough to understand sentences and clauses. A few layers look across the whole contract to connect a definition on page 3 with a use on page 90. Because most layers stay local, the model avoids rereading all 100,000 words at every layer.

Technically

In full causal attention, token i attends to all i earlier tokens. With a sliding window of size w, token i attends only to the last w tokens (itself included), so a layer's cost per token is O(w) instead of O(n) and its KV cache holds at most w tokens. Longformer (Beltagy et al. 2020) combined local windowed attention with task-motivated global attention to scale linearly with length. Mistral 7B uses a 4,096-token window with 32 layers, giving a theoretical attention span of about 131K tokens, because information can pass forward by up to one window per layer.

Current open models interleave local and global layers. gpt-oss alternates a 128-token window with full attention one to one (18 of 36 layers are global). Gemma 4 uses a 5:1 ratio with a 1,024-token window in its 12B, 26B and 31B models (512 tokens and 4:1 in E2B, 512 and 5:1 in E4B), and different KV heads and head widths on the two layer types. Because a window that slides past the first tokens removes a place where attention often parks its surplus, StreamingLLM (Xiao et al. 2023) keeps those initial tokens as attention sinks, and gpt-oss learns an explicit sink in every head.

Technical example: How many keys does a token read?

Keys read by one new token across all layers at the model's full context, for a layer pattern with local and global layers, compared with full attention on every layer.

Code (python):

def keys_read(layers, global_every, window, ctx):
    global_layers = layers // global_every
    local_layers = layers - global_layers
    return global_layers * ctx + local_layers * min(window, ctx), layers * ctx

models = [("gpt-oss-120b", 36, 2, 128, 131072),
          ("Gemma 4 31B", 60, 6, 1024, 262144)]
for name, layers, every, window, ctx in models:
    read, full = keys_read(layers, every, window, ctx)
    print(f"{name:13s} {layers} layers, window {window:>5,}, context {ctx:>7,}: "
          f"{read:>10,} keys read vs {full:>10,} ({100 * read / full:.1f}%)")

print("Mistral 7B span: 4096 x 32 =", 4096 * 32)

Output:

gpt-oss-120b  36 layers, window   128, context 131,072:  2,361,600 keys read vs  4,718,592 (50.0%)
Gemma 4 31B   60 layers, window 1,024, context 262,144:  2,672,640 keys read vs 15,728,640 (17.0%)
Mistral 7B span: 4096 x 32 = 131072

What it shows: At a 131,072-token conversation, gpt-oss-120b reads about half the keys that full attention would, because half of its layers are global, and Gemma 4 31B reads about 17%, because only one layer in six is. The saving comes from the layer mix, not from any single window.

Which tokens can a token read?. A 20 by 20 grid shows which tokens each token may read, with a switch between full causal attention and a sliding window you can resize. Below it, a strip of layers marks the local and global layers of gpt-oss-120b or Gemma 4 31B, and the readout counts keys read at the chosen conversation length. The mask is the standard causal and banded pattern; window sizes and layer ratios come from the published config.json files.

The cost of reading everything

In plain English: In full attention every new word compares itself with every earlier word. For a short text that is trivial, but for a long one it dominates the work, and the notes the model must keep grow with every word. Sliding-window attention removes that growth for the layers that use it.

Technically:

Full attention needs n(n+1)/2 query-key comparisons for a prompt of n tokens, and the KV cache holds n entries per layer. A window of w replaces the n in the per-token term with w, so the total becomes about n × w. FlashAttention avoids storing the score table but does not change the number of comparisons; windows reduce the comparisons themselves.

Windowing also bounds the cache: a local layer never needs keys older than w tokens, so those can be dropped, giving a cache of w entries instead of n. For long conversations that is the dominant saving.

The banded mask

In plain English: The mask for ordinary attention is a triangle: each word may look at all earlier words. For a sliding window, the triangle is cut to a band along the diagonal. A word sees itself and the few words just before it.

Technically:

Written as a mask, token i may read token j if j ≤ i and i − j < w. Implementations compute only the band, so no work is spent on masked entries. In the figure, the green band is exactly that pattern; shrinking the window to 1 leaves only the diagonal, where each token reads only itself.

Window sizes are small relative to context: gpt-oss uses 128 tokens against a 131,072-token context, and Gemma 4 uses 1,024 (512 in the smaller E models) against 262,144. Most understanding of grammar and local meaning needs only a short span.

What is a banded matrix?

A matrix whose non-zero entries lie in a narrow band around the diagonal. A sliding-window attention mask has this shape.

Mixing local and global layers

In plain English: If all layers had short windows, the model could not link a fact at the start of a book to a question at the end. So designers keep a few layers that read everything, spaced out among many that do not.

Technically:

Information reaches beyond one window by stacking: after k layers a token can be influenced by tokens up to k × w positions back. Mistral 7B states a theoretical span of about 131K tokens from a 4,096 window over 32 layers. Models that need exact long-range lookups still add global layers: Gemma 4 uses one global layer for every five local layers, with fewer but wider KV heads on the global ones, and gpt-oss uses every second layer.

The ratio is a tuning knob. More global layers help long-range tasks but cost cache and compute; fewer make the model cheaper. Gemma 4's smaller E2B model uses a 4:1 ratio.

Everyday example: Where the work goes

A model has 60 layers, one global layer in every six.

What it shows: Ten layers read the whole text and fifty read only the last 1,024 tokens. Because the fifty are cheap, the cost is dominated by the ten global layers, about 17% of what full attention would cost at a 262,144-token context.

Attention sinks and windows

In plain English: Models often dump extra attention on the very first words of a text, even when those words are not important. If a window slides past them, the model loses its dumping ground and can produce nonsense. Two fixes exist: always keep a few initial words, or teach the model a dedicated place to park attention.

Technically:

Xiao et al. (2023) observed this attention-sink phenomenon: window attention fails when the text length exceeds the cache size, and keeping the key-value states of the initial tokens largely recovers performance. StreamingLLM uses this to let models trained with a finite window process very long streams.

gpt-oss builds the idea into the architecture: every head has a learned sink logit in its softmax denominator, so a head can give almost no weight to real tokens when nothing is relevant, without relying on the first token. The model card does not state the motivation, so its connection to the windows is an interpretation.

What is an attention sink?

A token, usually the first, that receives large attention weights regardless of its content, giving the softmax somewhere to put surplus weight.

Common misconceptions

  • Myth: With a 128-token window the model cannot use anything older than 128 tokens.

    Reality: Only that layer cannot. Global layers read everything, and information from older tokens is carried forward through the residual stream across layers.

  • Myth: Sliding windows make long contexts free.

    Reality: They cut cost for local layers, but global layers still scale with the full length, so total cost remains well above a purely local design.

  • Myth: A bigger window is always better.

    Reality: The window sets a trade-off between quality on long-range tasks and memory and compute. Models choose windows and layer ratios to balance them.

Where you'll see this

  • gpt-oss architecture: gpt-oss alternates a 128-token window with full attention one to one and adds a learned sink to every head.
  • Gemma 4 architecture: Gemma 4 uses a 5:1 local-to-global ratio with a 1,024-token window (512 in the small models).
  • DeepSeek-V3 architecture: DeepSeek-V3.2 instead selects the 2,048 most relevant tokens per query with a learned indexer, a sparse alternative to fixed windows.

Key takeaways

  • Sliding-window attention lets each token read only its last w tokens, so a layer's work and cache stop growing with text length.
  • Real models mix local and global layers: gpt-oss alternates one to one with a 128-token window; Gemma 4 uses five local layers per global one with a 1,024-token window.
  • Information still travels far, because every layer can pass what it read from one window to the next.
  • Windows remove the early tokens that attention often uses as a sink, so models either keep initial tokens or learn an explicit sink.

Frequently asked questions

What is sliding-window attention?

An attention pattern in which each token reads only the most recent w tokens instead of all earlier ones, which bounds cost and cache size.

How big are the windows in real models?

128 tokens in gpt-oss, 1,024 in the larger Gemma 4 models and 512 in the small ones, and 4,096 in Mistral 7B.

How can a windowed model still use distant text?

Through global layers that read everything, and through stacking: each layer passes information along, so the reach is up to window times layers.

Does sliding-window attention reduce the KV cache?

Yes. A local layer needs only the last w tokens, so its cache is w entries instead of the whole context.

What is the difference between sliding-window and sparse attention?

A window always reads the most recent tokens; sparse attention picks which tokens to read, for example the top 2,048 chosen by DeepSeek's indexer.

Sources

Facts last verified November 23, 2026.

Next concept: Mixture of experts

Learn next

  • Grouped-query attention (Intermediate): Grouped-query attention lets several query heads share one set of key and value heads, cutting the KV cache by the group size at little cost in quality.
  • Context window (Beginner): A context window is the maximum number of tokens, prompt and reply together, that a language model can take into account at one time.
  • Latency and throughput (Intermediate): Latency is how quickly one request gets its tokens and throughput is how many tokens a server produces in total; for LLM decoding both are limited mainly by how fast weights can be read from memory.