10.6 Windowed and Linear Attention
Fused kernels (Section 10.5) eliminate the intermediate score matrix, yet both their FLOP count and their key--value cache still grow with sequence length . When processing a 100,000-token document, however, most tokens depend primarily on local context, while only occasional lookups require long-range retrieval.
Two primary architectural strategies reduce attention's computational cost to :
- Sliding-window attention (Child et al., 2019; Beltagy et al., 2020) restricts each query to its most recent keys, reducing per-layer work to and bounding the key--value cache at tokens.
- Linear attention (Katharopoulos et al., 2020) replaces the softmax kernel with a factorized kernel , allowing keys and values to be accumulated into a fixed-size recurrent state matrix.
Both approaches compute a different function from dense softmax attention. This section analyzes how sliding windows trade single-hop reach for tile sparsity, derives the parallel, recurrent, and chunked forms of linear attention, and demonstrates why factorized feature maps lack the sharpening temperature of softmax.
from torch.nn.attention.flex_attention import create_block_mask, flex_attention10.6.1 Sliding-Window Attention#
10.6.1.1 The Band Mask#
In causal sliding-window attention of width , query attends to key only if and . This conjunction of causality and locality replaces the lower triangle of active pairs with a diagonal band of at most pairs:
def window_mask(n, w, device=None):
"""Causal band: query i may attend to keys i - w + 1, ..., i."""
i = torch.arange(n, device=device)
return d2l.causal_mask(n, device=device) & (i[:, None] - i[None, :] < w)10.6.1.2 Receptive Field Growth with Depth#
Just as stacked convolutions expand their receptive field with depth (Chapter 6), stacking sliding-window layers of width allows information to propagate steps backward per layer, yielding a theoretical receptive field of
tokens. For example, Mistral 7B v0.1 (Jiang et al., 2023) used across layers, spanning up to tokens. However, theoretical reach differs from direct retrieval: whereas full self-attention connects any two tokens in a single hop, a stack of windows requires sequential hops across layers to relay a fact across distance . A relayed fact is also diluted at every hop. Figure 10.6.1 shows the smallest case: under uniform window averaging (, ), a token at the boundary arrives along a single four-hop path with weight , compared to in a single global layer.
Stacked windows against one global layer. Left: with four windowed layers of width , the output at the top right depends on a cone of earlier positions, and the input positions back reaches it along a single path of four hops (blue), with weight under uniform attention weights. Right: one global layer connects the same two positions in one hop, with weight .
10.6.1.3 Global Layers#
To preserve one-hop long-range retrieval while retaining most of the memory and compute savings of local windows, modern long-context architectures interleave windowed layers with one full (global) attention layer—for example, Gemma 3 uses windowed layers () per global layer (Team, 2025). Because a windowed layer caches only the last keys and values during generation (Section 11.3), interleaving reduces the total KV cache to the fraction
of an all-global stack ( at and asymptotically for ).
10.6.1.4 Tiles in a Fused Kernel#
Applying window_mask inside a dense matrix multiplication
still computes all scores. To realize time and memory, an
implementation must evaluate only the active band—for instance, by grouping
queries into blocks of size and attending only to the current and
immediately preceding key blocks ( scores total):
def windowed_attention(Q, K, V, w):
"""Causal sliding-window attention in O(nw) time and memory."""
n, d_h = Q.shape
assert n % w == 0, 'blocks must tile the sequence exactly'
Qb, Kb, Vb = (X.reshape(n // w, w, -1) for X in (Q, K, V))
# Each query block attends to its own key block and the one before it
prev = lambda X: torch.cat([torch.zeros_like(X[:1]), X[:-1]])
Kb, Vb = torch.cat([prev(Kb), Kb], 1), torch.cat([prev(Vb), Vb], 1)
i = torch.arange(w, device=Q.device)[:, None] # Query in its block
j = torch.arange(-w, w, device=Q.device)[None, :] # Key offset from it
first = torch.arange(n // w, device=Q.device)[:, None, None] == 0
mask = (j <= i) & (i - j < w) & ~(first & (j < 0)) # No keys before 0
scores = Qb @ Kb.transpose(-1, -2) / math.sqrt(d_h)
return (d2l.masked_softmax(scores, mask) @ Vb).reshape(n, -1)In a tiled GPU kernel such as FlashAttention or FlexAttention (Dong et al., 2025), computation proceeds in tiles ( by default in FlexAttention), and a tile is skipped only when all of its entries are masked out. At and , the causal mask visits of the tiles ( for ), whereas the sliding window visits only the diagonal tile and its left neighbor in each tile row ( tiles, or ; Figure 10.6.2):
def tiles_visited(mask, b):
"""Fraction of b-by-b tiles of a mask that hold at least one True."""
T = mask.shape[0] // b
return mask.reshape(T, b, T, b).any(dim=(1, 3)).float().mean().item()
n, b, w = 2048, 128, 128
print(f'causal: {tiles_visited(d2l.causal_mask(n), b):.1%} of tiles')
print(f'window: {tiles_visited(window_mask(n, w), b):.1%} of tiles')causal: 53.1% of tiles
window: 12.1% of tiles
Tiles visited by a fused kernel, for tile rows. Solid entries are allowed scores, and the faint remainder of a square marks a tile that the mask cuts but the kernel must still visit. The causal mask (left) visits tiles and cuts only the on the diagonal. The window of width (right) visits the diagonal tile and its left neighbor in each row, tiles, and cuts every one of them.
Both windowed_attention and the framework's fused sliding-window kernel
match the
dense masked definition up to float32 round-off:
The fused kernel is flex_attention with create_block_mask.
n, w, d_h = 2048, 128, 64
Q, K, V = (torch.randn(n, d_h, device=d2l.try_gpu()) for _ in range(3))
reference = d2l.masked_softmax(Q @ K.T / math.sqrt(d_h),
window_mask(n, w, Q.device)) @ V
# create_block_mask evaluates the band at every position and records which
# tiles are empty, full or cut by it; compiled, the kernel skips the empty ones
band = lambda batch, head, q, k: (k <= q) & (q - k < w)
block_mask = create_block_mask(band, None, None, n, n, device=Q.device)
fused = torch.compile(flex_attention)(Q[None, None], K[None, None],
V[None, None], block_mask=block_mask)
for name, O in (('blocked', windowed_attention(Q, K, V, w)),
('fused kernel', fused[0, 0])):
print(f'{name:>12}: maximum deviation '
f'{float((O - reference).abs().max()):.2e}') blocked: maximum deviation 4.17e-07
fused kernel: maximum deviation 6.56e-07
10.6.1.5 Windowed and Dense Kernels Compared#
With tile rows, the ratio of active causal tiles to active windowed tiles () is , predicting a theoretical tile reduction at (). We benchmark both masks inside the same fused bfloat16 kernel across ( heads, ):
flex = torch.compile(flex_attention)
w = b = 128 # Window width; tile size of the kernel
masks = {'dense causal': lambda batch, head, q, k: k <= q,
f'window (w={w})': lambda batch, head, q, k: (k <= q) & (q - k < w)}
H, lengths = 32, [512, 1024, 2048, 4096, 8192, 16384, 32768]
times = {name: [] for name in masks}
for n in lengths:
X = torch.randn(1, H, n, d_h, device=d2l.try_gpu(), dtype=torch.bfloat16)
for name, rule in masks.items():
block_mask = create_block_mask(rule, None, None, n, n, device=X.device)
times[name].append(d2l.Benchmark(
lambda: flex(X, X, X, block_mask=block_mask)).time * 1e3)
T = n // b # Rows of b x b tiles; causal T(T+1)/2, window 2T - 1
dense, window = (t[-1] for t in times.values())
print(f'n = {n:6,}: window {dense / window:4.1f}x faster, '
f'tile count predicts {T * (T + 1) / 2 / (2 * T - 1):4.1f}x')
d2l.plot(lengths, list(times.values()), 'sequence length n', 'time (ms)',
legend=list(times), xscale='log', yscale='log', figsize=(4.5, 3))n = 512: window 1.0x faster, tile count predicts 1.4x
n = 1,024: window 0.9x faster, tile count predicts 2.4x
n = 2,048: window 1.2x faster, tile count predicts 4.4x
n = 4,096: window 4.4x faster, tile count predicts 8.4x
n = 8,192: window 11.7x faster, tile count predicts 16.4x
n = 16,384: window 23.0x faster, tile count predicts 32.4x
n = 32,768: window 47.0x faster, tile count predicts 64.4x
Beyond , dense causal runtime scales quadratically while windowed runtime scales linearly, reaching a speedup at . This is between one half and three quarters of the that the tile count predicts. The count treats every visited tile as the same amount of work, so it is an upper bound on the gain and not an estimate of it.
In FlexAttention every visited tile of a width- band is cut by the mask boundary (Figure 10.6.2) and pays for elementwise masking, whereas the interior tiles of the causal triangle run unmasked.
10.6.2 Linear Attention#
10.6.2.1 Kernelizing the Score#
Rather than restricting which pairs are scored, linear attention (Katharopoulos et al., 2020) replaces the exponential similarity with a factorized kernel using a nonnegative elementwise feature map . By the associativity of matrix multiplication,
avoiding the matrix in favor of a summary matrix. Under a causal mask (), factoring out of the numerator and denominator sums yields
Following Katharopoulos et al. (2020), we choose elementwise (with a small in the denominator against float32 underflow). The prefix sums satisfy the linear recurrence
turning causal attention into an RNN whose hidden state is a
associative memory matrix updated by outer products (a fast weight
programmer, (Schlag et al., 2021)). We can evaluate
(10.6.2) either in parallel via cumulative sums (cumsum) or
recurrently step by step in memory:
def phi(X):
return F.elu(X) + 1
def linear_attention_parallel(Q, K, V, eps=1e-6):
"""Training form: all outputs at once via cumulative sums."""
Qp, Kp = phi(Q), phi(K)
S = torch.cumsum(Kp[:, :, None] * V[:, None, :], dim=0) # (n, d_h, d_v)
z = torch.cumsum(Kp, dim=0) # (n, d_h)
den = (Qp * z).sum(-1, keepdim=True) + eps
return (Qp[:, :, None] * S).sum(1) / den
def linear_attention_recurrent(Q, K, V, eps=1e-6):
"""Generation form: a (d_h, d_v) state, updated token by token."""
Qp, Kp = phi(Q), phi(K)
S = torch.zeros(Q.shape[-1], V.shape[-1], device=Q.device)
z = torch.zeros(Q.shape[-1], device=Q.device)
outputs = []
for t in range(Q.shape[0]):
S = S + Kp[t][:, None] * V[t][None, :] # Outer-product write
z = z + Kp[t]
outputs.append(Qp[t] @ S / (Qp[t] @ z + eps)) # Query the memory
return torch.stack(outputs)10.6.2.2 Chunked Computation#
During training on GPUs, materializing all intermediate matrices
in linear_attention_parallel
consumes memory (256 MiB per head at ), whereas linear_attention_recurrent executes sequential vector
steps that underutilize GPU matrix cores. Partitioning the sequence into
chunks of length (Yang et al., 2024) combines both: for a
chunk starting at with pre-chunk state ,
so both intra-chunk attention () and inter-chunk state propagation use dense matrix multiplications in FLOPs and store only chunk states:
def linear_attention_chunked(Q, K, V, c=64, eps=1e-6):
"""Training form in chunks: quadratic within, recurrent across."""
n, d_h = Q.shape
assert n % c == 0, 'chunks must tile the sequence exactly'
Qp, Kp = phi(Q).reshape(n // c, c, d_h), phi(K).reshape(n // c, c, d_h)
Vc = V.reshape(n // c, c, -1)
# The state each chunk starts from: sums over all earlier chunks
S = torch.cumsum(Kp.transpose(-1, -2) @ Vc, dim=0) # (n/c, d_h, d_v)
z = torch.cumsum(Kp.sum(1), dim=0) # (n/c, d_h)
S = torch.cat([torch.zeros_like(S[:1]), S[:-1]])
z = torch.cat([torch.zeros_like(z[:1]), z[:-1]])
A = torch.tril(Qp @ Kp.transpose(-1, -2)) # (n/c, c, c)
num = Qp @ S + A @ Vc # Past + this chunk
den = Qp @ z[..., None] + A.sum(-1, keepdim=True) + eps
return (num / den).reshape(n, -1)All three forms compute the exact same outputs up to float32 rounding, and the recurrent state occupies a constant 16 KiB per head ( floats) regardless of sequence length:
n = 512
Q, K, V = (torch.randn(n, d_h, device=d2l.try_gpu()) for _ in range(3))
recurrent = linear_attention_recurrent(Q, K, V)
for name, f in (('parallel', linear_attention_parallel),
('chunked', linear_attention_chunked)):
err = (f(Q, K, V) - recurrent).abs().max()
print(f'{name:>8}: maximum deviation {float(err):.2e}')
print(f'recurrent state: {d_h}x{d_h} + {d_h} floats '
f'= {(d_h * d_h + d_h) * 4 / 1024:.0f} KiB at any sequence length')parallel: maximum deviation 4.77e-07
chunked: maximum deviation 4.77e-07
recurrent state: 64x64 + 64 floats = 16 KiB at any sequence length
10.6.2.3 Capacity and Sharpness#
Compressing an arbitrary number of key--value pairs into a state matrix incurs two fundamental costs:
- Finite associative capacity: Because is nonnegative, a query can isolate a single stored value without cross-talk only if key feature vectors are nearly orthogonal (nearly disjoint supports), limiting exact retrieval to at most keys.
- Lack of temperature sharpening: In softmax attention, scaling a query by exponentiates score differences (), driving the distribution toward a one-hot lookup as . In linear attention with , scaling by large yields , so the scale factor cancels out between numerator and denominator (Exercise 2):
Q = torch.randn(1000, d_h, device=d2l.try_gpu())
K = torch.randn(8, d_h, device=d2l.try_gpu())
for beta in (1, 4, 16): # Scale the queries up; 8 keys: uniform is 0.125
soft = torch.softmax(beta * Q @ K.T / math.sqrt(d_h), dim=-1)
lin = phi(beta * Q) @ phi(K).T
lin = lin / lin.sum(-1, keepdim=True)
print(f'queries x{beta:<2}: mean largest weight, softmax '
f'{soft.amax(-1).mean():.2f}, elu+1 {lin.amax(-1).mean():.2f}')queries x1 : mean largest weight, softmax 0.36, elu+1 0.15
queries x4 : mean largest weight, softmax 0.76, elu+1 0.15
queries x16: mean largest weight, softmax 0.94, elu+1 0.15
10.6.2.4 Recall Under Each Mechanism#
Both limits, and the limit of a window, appear in the simplest lookup we can pose. We store random key--value pairs of width , query with one of the stored keys, and count a hit when the output has a larger inner product with the right value than with any other stored value. Four mechanisms answer the query: dense softmax attention; a window that sees only the last pairs; linear attention with the elu+1 feature map; and the outer-product state , which is linear attention with the identity feature map and no normalizer. The last one sets the feature map aside, so that it shows the capacity of a state by itself:
def recall(N, w=16, trials=1000):
"""Look up one of N stored pairs by its key; fraction of hits per rule."""
K, V = (torch.randn(trials, N, d_h, device=d2l.try_gpu())
for _ in range(2))
target = torch.randint(0, N, (trials,), device=K.device)
rows = torch.arange(trials, device=K.device)
q = K[rows, target][:, None] # (trials, 1, d_h)
scores = q @ K.transpose(1, 2) / math.sqrt(d_h) # (trials, 1, N)
recent = torch.arange(N, device=K.device) >= N - w # The last w pairs
lin = phi(q) @ phi(K).transpose(1, 2)
outputs = {'softmax': torch.softmax(scores, -1) @ V,
f'window (w={w})': d2l.masked_softmax(scores, recent) @ V,
'elu+1': lin / lin.sum(-1, keepdim=True) @ V,
'outer-product state': q @ (K.transpose(1, 2) @ V)}
# A hit: of the N stored values, the target is nearest to the output
return {name: float(((O @ V.transpose(1, 2)).argmax(-1)[:, 0] == target)
.float().mean()) for name, O in outputs.items()}
for N in (16, 64, 256, 1024):
print(f'N = {N:4}: ' + ', '.join(f'{name} {hit:.2f}'
for name, hit in recall(N).items()))N = 16: softmax 1.00, window (w=16) 1.00, elu+1 0.24, outer-product state 1.00
N = 64: softmax 1.00, window (w=16) 0.24, elu+1 0.04, outer-product state 0.99
N = 256: softmax 1.00, window (w=16) 0.07, elu+1 0.00, outer-product state 0.67
N = 1024: softmax 1.00, window (w=16) 0.02, elu+1 0.00, outer-product state 0.09
Softmax attention finds the pair at every . The window finds it only when the pair lies among the last , so its recall is about : perfect at , a quarter at , and a few percent at . More striking is elu+1 linear attention, which fails even at , where the state has four times as many rows as there are pairs to store. Its weights cannot sharpen, so the output is close to the average of all stored values, and the right one barely stands out.
The outer-product state does much better, and it shows the capacity limit cleanly. For the query its output is plus crosstalk from the other pairs. Each crosstalk coefficient has size about , so the noise relative to the signal is about . Recall is nearly perfect up to , drops to about two thirds at , and has collapsed at . Softmax attention keeps all pairs and recalls at every ; a state of fixed size recalls only while stays near its width.
10.6.3 Choosing a Mechanism#
- Exact fused attention is the default for short-to-medium contexts, providing exact one-hop retrieval in working memory.
- Interleaved sliding-window and global layers are the standard for long-context transformers (e.g., Gemma 3), cutting KV-cache memory and tile FLOPs on local layers while preserving one-hop global routing on periodic global layers.
- Linear attention requires data-dependent decay gates (so old entries can be forgotten; see Exercise 4 and Chapter 12) and hybrid interleaving with full softmax layers (e.g., MiniMax-01, (MiniMax, 2025)) to handle exact associative recall (Arora et al., 2024; Yang et al., 2024).
10.6.4 Summary#
Sliding-window attention restricts each query to the most recent keys, reducing arithmetic to and cache memory to while expanding its effective receptive field to tokens across layers; modern long-context models interleave these local layers with periodic global attention layers to preserve single-hop retrieval. On GPUs, tiled kernels realize this speedup by skipping completely masked score tiles, up to boundary masking overhead. Linear attention takes an algebraic route instead, replacing the exponential score with a factorized similarity kernel that collapses causal attention into an recurrence over a fixed matrix state trainable in parallel chunks. Because a fixed-size state with nonnegative features cannot sharpen weights via query scaling or store more than orthogonal keys without cross-talk, practical linear-attention architectures incorporate data-dependent decay gates and hybrid softmax layers.
10.6.5 Exercises#
-
[code] Tiles of a fused kernel. A fused kernel works on tiles of scores and skips a tile only if the mask excludes all of it. Let .
- Show that a causal mask leaves of the tiles, and
that a window of width , for a whole number , leaves
. Check both counts with
tiles_visited. How does the count change when is not a multiple of ? - Several documents are packed into one sequence of tokens,
and the mask combines causality with "same document" as in the
masks of Section 10.2. Using
tiles_visitedwith , compare four documents of 512 tokens with documents of 1,000, 600, 300, and 148 tokens. Explain why documents whose boundaries do not fall on tile boundaries cost more tiles.
- Show that a causal mask leaves of the tiles, and
that a window of width , for a whole number , leaves
. Check both counts with
-
[code] The feature map. The feature map in
phiis one choice among many. Compare it with and , both applied elementwise, on random queries and keys of widthd_h.- For each map, compute the causal linear-attention weight matrix with entries
and measure its maximum absolute difference from the causal softmax
weight matrix d2l.masked_softmax(Q @ K.T / math.sqrt(d_h), d2l.causal_mask(n)), and the mean entropy of its rows.
- Under which condition on and the keys does the ReLU map produce an undefined row? Derive the probability of this event for row when all entries are independent standard normal, and evaluate it for at width and at width .
- The section scaled the queries by and watched the largest weight. Do the same for the ReLU and exponential maps, measuring the mean row entropy instead. Derive, for each of the three maps, the limit of the normalized weights as , and explain why none of them becomes one-hot where softmax does.
-
An exact feature map. ● The softmax kernel also factorizes, but only with infinitely many features.
- Expand in its Taylor series, and show that the degree- term equals for a feature map of dimension built from the -fold tensor product of its argument.
- Truncate the series after degree . Show that the truncated kernel is positive for every pair of and , so the normalizer of (10.6.2) cannot vanish, and give the dimension of the feature map that concatenates , , and . For and values of width , compute the size of the state in single precision and the length at which the key--value cache of a softmax head reaches the same size. A truncation of this kind is the feature map of Based (Arora et al., 2024).
- Take as given that the matrix with entries is positive definite for distinct . Show that no feature map of dimension reproduces exactly on these points when queries and keys coincide.
-
[code] A decaying state. ● Give the state of (10.6.3) a scalar decay ,
- Show that the parallel form now weights the contribution of position
to the output at by , and implement it by
rescaling the cumulative sums of
linear_attention_parallelwith powers of . - Add the decay to
linear_attention_recurrent, and verify that the two forms agree for and . - The rescaling multiplies position by before the cumulative sum. For which does this overflow single precision at and at ?
- Add the decay to
linear_attention_chunked: rescale each position relative to the start of its chunk, and carry the state from one chunk to the next with the decayed recurrence. Show that no factor larger than appears, run the result for , , and , and compare it with the recurrent form. - Compute the lag at which the weight falls below for . A task requires recalling one token from positions back, while the tokens in between are filler. Explain why no fixed serves both that token and the filler, and what a decay computed from each token's own input could do instead.