Windowed and Linear Attention

Dive into Deep Learning · §10.6

Windowed, Sparse, and Linear Attention
sliding-window masks · multi-hop receptive fields · tile sparsity · kernelized linear attention · recurrent & chunked forms

Why Fused Exact Attention Still Costs O(n²) Time

Motivation

  • FlashAttention eliminates the O(n^2) score matrix in HBM, yet at n = 32{,}768 (T = 256 tile rows of b = 128) it still visits T(T+1)/2 = \mathbf{32{,}896} tiles and caches all 32{,}768 KV tokens.
  • To cut arithmetic below \Theta(n^2 d) and bound generation memory, we must either score fewer pairs (windows: 511 tiles) or factorize the similarity kernel (linear attention: d_h \times d_v state).

Two Architectural Routes to O(n) Attention

Design Trade-Offs

  • Route 1 — Sliding-Window Attention: Restricts each query i to its w most recent keys (i - w < j \le i), preserving exact softmax sharpness locally at O(nw) cost.
  • Route 2 — Linear Attention: Replaces \exp(\mathbf{q}^\top\mathbf{k}/\sqrt{d_h}) with a nonnegative feature map product \phi(\mathbf{q})^\top\phi(\mathbf{k}), collapsing all past keys/values into a fixed d_h \times d_v state matrix.

Sliding-Window Attention: The Causal Band Mask

Local Attention

A causal sliding window of width w permits query i to attend to key j if and only if j \le i (causality) and i - j < w (locality):

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)
  • Boolean Conjunction: window_mask(n, w) is the logical AND (&) of d2l.causal_mask(n) and the offset constraint i[:, None] - i[None, :] < w.
  • Linear Pair Count: Whereas the causal triangle retains n(n+1)/2 active pairs, the sliding band retains at most nw pairs (\approx 4.2 \times 10^6 vs. 5.4 \times 10^8 at n = 32{,}768, w = 128).

Receptive Field Growth Across Stacked Window Layers

Multi-Hop Propagation

  • Stacking L sliding-window layers of width w steps up to w - 1 positions back per layer: \textrm{Receptive Field}(L, w) = 1 + L(w - 1)
  • Theoretical Reach vs. Effective Attenuation: Reaching distance \Delta requires \lceil \Delta / (w - 1) \rceil hops across layers; under uniform window weights (w = 4, L = 4), a boundary token at \Delta = 12 arrives with weight (1/4)^4 = 1/256.

Interleaving Windowed and Global Attention Layers

Hybrid Long-Context Architectures

  • Modern long-context transformers interleave r windowed layers with 1 full global layer: \frac{\textrm{Hybrid Cache}}{\textrm{All-Global Cache}} = \frac{r \min(n, w) + n}{(r + 1)\,n} \;\xrightarrow{\;n \gg w\;}\; \frac{1}{r + 1}
  • Gemma 3 (r = 5, w = 1{,}024): Shrinks the KV cache to 17.3\% at n = 128\text{K} while guaranteeing a 1-hop global attention path every 6th layer.

Realizing O(nw) Cost via Blocked Band Evaluation

Blocked Implementation

Passing window_mask(n, w) into a dense n \times n matrix product still computes all n^2 scores. To run in true O(nw) time and memory, windowed_attention tiles queries into blocks of w and scores each block only against its own and the previous key block (2nw scores):

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)

How Fused Kernels Exploit Block-Mask Tile Sparsity

Hardware Tile Skipping

  • Tiled GPU kernels (FlashAttention, flex-attention-style kernels, cuDNN) partition the n \times n score matrix into b \times b tiles (typically b = 128) and skip a tile only if all b^2 of its entries are masked out.
  • At n = 2{,}048 and b = w = 128 (T = n/b = 16 tile rows):
    • Causal mask: Visits T(T+1)/2 = 136 of 256 tiles (53.1\%).
    • Sliding window (w = 128): Visits only the diagonal tile and its immediate left neighbor per row: 2T - 1 = 31 tiles (12.1\%).
causal:  53.1% of tiles
window:  12.1% of tiles
     blocked: maximum deviation 4.17e-07
fused kernel: maximum deviation 6.56e-07

Benchmarking Windowed vs. Dense Causal Kernels

Wall-Clock Scaling up to 32K

  • We time dense causal vs. sliding-window (w = 128) attention inside the same compiled bfloat16 fused kernel (H = 32, d_h = 64) from n = 512 to n = 32{,}768:
  • Linear vs. Quadratic Slope: Above n = 2{,}048, dense runtime quadruples per doubling of n, while windowed runtime grows linearly (2\times per doubling).
  • > 30\times Speedup at 32\text{K}: One half to three quarters of the 64.4\times tile ratio. The tile count treats every visited tile as equal work, so it is an upper bound on the gain.
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

Linear Attention: Factorizing the Similarity Kernel

Factorized Kernels

  • Linear attention (Katharopoulos et al., 2020) replaces \exp(\mathbf{q}^\top\mathbf{k}/\sqrt{d_h}) with K(\mathbf{q}, \mathbf{k}) = \phi(\mathbf{q})^\top \phi(\mathbf{k}) where \phi(x) = \mathrm{elu}(x) + 1 > 0: \bigl(\phi(\mathbf{Q})\,\phi(\mathbf{K})^\top\bigr)\,\mathbf{V} \;=\; \phi(\mathbf{Q})\,\bigl(\phi(\mathbf{K})^\top \mathbf{V}\bigr)
  • The Associativity Trick: Computing \phi(\mathbf{K})^\top \mathbf{V} \in \mathbb{R}^{d_h \times d_v} first reduces cost from \Theta(n^2 d_h) to \Theta(n d_h d_v) without ever forming an n \times n matrix.

Causal Linear Attention as a Fast-Weight RNN

Recurrent Matrix State

  • Under a causal mask (s \le t), factoring \phi(\mathbf{q}_t)^\top out of the sums turns causal linear attention into an exact recurrence: \mathbf{o}_t^\top = \frac{\phi(\mathbf{q}_t)^\top \mathbf{S}_t}{\phi(\mathbf{q}_t)^\top \mathbf{z}_t + \epsilon}, \qquad \mathbf{S}_t = \mathbf{S}_{t-1} + \phi(\mathbf{k}_t)\,\mathbf{v}_t^\top
  • Constant Generation State: (\mathbf{S}_t, \mathbf{z}_t) has fixed size d_h d_v + d_h (16.25\text{ KiB} in float32 at d_h = d_v = 64) for any sequence length n.

Parallel and Recurrent Linear Attention in Code

Two Equivalent Evaluations

Because the state recurrence \mathbf{S}_t = \sum_{s \le t} \phi(\mathbf{k}_s)\mathbf{v}_s^\top is a prefix sum, we can evaluate it in parallel via cumsum or sequentially step by step. The parallel (training) form:

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

Parallel and Recurrent Linear Attention in Code (cont.)

Two Equivalent Evaluations

The recurrent (generation) form carries a (d_h, d_v) state and updates it token by token:

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)

Chunked Linear Attention: Hardware-Friendly Training

Chunkwise Parallel Form

  • Chunked Decomposition (Yang et al., 2024): Split the sequence into n/c chunks of length c (c = 64); for a chunk starting at t_0 with pre-chunk state (\mathbf{S}, \mathbf{z}): \mathbf{o}_t^\top = \frac{\phi(\mathbf{q}_t)^\top \mathbf{S} + \sum_{t_0 \le s \le t} \big(\phi(\mathbf{q}_t)^\top\phi(\mathbf{k}_s)\big)\,\mathbf{v}_s^\top}{\phi(\mathbf{q}_t)^\top \mathbf{z} + \sum_{t_0 \le s \le t} \phi(\mathbf{q}_t)^\top\phi(\mathbf{k}_s) + \epsilon}
  • Runs both inter-chunk (\mathbf{Q}_p \mathbf{S}) and intra-chunk (\mathrm{tril}(\mathbf{Q}_p \mathbf{K}_p^\top)\mathbf{V}_c) terms as dense Tensor Core GEMMs while storing only n/c chunk states.

Implementing and Verifying Chunked Linear Attention

Chunked Code & Equivalence

linear_attention_chunked matches both other forms to float32 precision (\sim 10^{-7}):

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)
parallel: maximum deviation 4.77e-07
 chunked: maximum deviation 4.77e-07
recurrent state: 64x64 + 64 floats = 16 KiB at any sequence length

Three Execution Modes of Linear Attention Compared

Systems Comparison

  • Parallel (cumsum): Materializes all n state matrices (256\text{ MiB} at n = 16\text{K}); useful only for short debug sequences.
  • Recurrent Loop: Constant 16\text{ KiB} state (O(1) per step); ideal for token-by-token generation.
  • Chunked (c = 64): Combines Tensor Core GEMMs with 64\times smaller state memory for fast parallel training and prefill.

Limits of Linear Attention: Capacity and Sharpness

Fundamental Limitations

Compressing an unbounded history of key–value pairs into a fixed d_h \times d_v matrix with a finite feature map \phi incurs two fundamental retrieval penalties:

  • 1. Finite Orthogonal Capacity (\le d_h Keys): Because \mathbf{S}_t = \sum_{s \le t} \phi(\mathbf{k}_s)\mathbf{v}_s^\top sums outer products in \mathbb{R}^{d_h \times d_v}, retrieving \mathbf{v}_s without cross-talk requires \phi(\mathbf{q}_t) to be orthogonal to \phi(\mathbf{k}_{s'}) for s' \neq s—possible for at most d_h keys.
  • 2. No Temperature Sharpening: In softmax, scaling \mathbf{q} \mapsto \beta \mathbf{q} exponentiates score gaps (e^{\beta\Delta} \to \infty), converging to a 1-hot lookup. For \phi(x) = \mathrm{elu}(x) + 1, large \beta gives \phi(\beta \mathbf{q}) \approx \beta\,\mathrm{relu}(\mathbf{q}), and \beta cancels between numerator and denominator.
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

Engineering Guide: Choosing an Attention Mechanism

Architectural Decision Guide

  • Short/medium contexts (n \le 32\text{K}): Exact fused FlashAttention (\Theta(n^2 d) time, full 1-hop recall).
  • Long contexts (n = 128\text{K}\text{--}1\text{M}): Interleaved sliding window + periodic global layers (e.g., Gemma 3 5{:}1 schedule cuts KV cache to 17\%).
  • Constant-state streaming: Gated linear attention / modern RNNs with input-dependent decay gates \gamma_t + hybrid softmax layers.

Concept Check: Tiles, Caches, and Linear Kernels

Check Your Understanding

  1. Sub-Tile Window Width: In a fused kernel with tile size b = 128 at sequence length n = 2{,}048 (T = 16 tile rows), a causal window of width w = 128 visits 2T - 1 = 31 tiles. How many 128 \times 128 tiles does the kernel visit if you shrink the window to w = 32?
  2. ReLU Feature Map Scaling: If you use \phi(x) = \mathrm{relu}(x) in linear attention and multiply a query vector \mathbf{q}_t by \beta = 16 (assuming \phi(\mathbf{q}_t)^\top \mathbf{z}_t > 0), by how much do the attention weights change?
  3. Degree-2 Taylor Feature Map (Based): Expanding \exp(\mathbf{q}^\top\mathbf{k}/\sqrt{d_h}) \approx 1 + \frac{\mathbf{q}^\top\mathbf{k}}{\sqrt{d_h}} + \frac{(\mathbf{q}^\top\mathbf{k})^2}{2d_h} factorizes into a feature map of dimension D = 1 + d_h + d_h^2. For d_h = 64, how large is the state \mathbf{S}_t \in \mathbb{R}^{D \times d_v} (d_v = 64), and at what sequence length n does a softmax KV cache exceed it?

Concept Check: Tiles, Caches, and Linear Kernels (answers)

Check Your Understanding

Answers:

  1. Still 31 tiles. Because a kernel skips only completely empty 128 \times 128 tiles, any window 2 \le w \le 128 crosses the boundary into the left-neighbor tile and visits the exact same 2T - 1 = 31 tiles.
  2. Zero change. Because \mathrm{relu}(16x) = 16\,\mathrm{relu}(x) is positively homogeneous of degree 1, the factor 16 cancels identically between numerator and denominator.
  3. D = 1 + 64 + 4{,}096 = 4{,}161, so \mathbf{S}_t holds 4{,}161 \times 64 floats (1.02\text{ MiB} in fp32), matching a softmax KV cache (2 \times 64 floats/token) at n = 2{,}081 tokens.

Summary: Windowed and Linear Attention

Key Takeaways

Concept / Variant Mathematical Rule Time & Memory Cost Key Trade-Off / Engineering Lesson
Causal Sliding Window j \le i and i - j < w \Theta(nwd) FLOPs, O(wd) cache L layers reach 1 + L(w-1) tokens via multi-hop relays
Hybrid Window + Global r window layers per 1 global layer Cache fraction \to \dfrac{1}{r+1} for n \gg w Preserves 1-hop long-range retrieval at a fraction of the KV cache
Tiled Block Sparsity Skip b \times b tile iff all b^2 entries False Window w=b visits 2T-1 vs. T(T+1)/2 tiles > 30\times speedup at n=32\text{K}; align w and packed docs to tile size b
Linear Attention \mathbf{o}_t^\top = \dfrac{\phi(\mathbf{q}_t)^\top \mathbf{S}_t}{\phi(\mathbf{q}_t)^\top \mathbf{z}_t + \epsilon} \Theta(n d_h d_v) FLOPs, O(d_h d_v) state Associativity (\phi(\mathbf{Q})\phi(\mathbf{K})^\top)\mathbf{V} = \phi(\mathbf{Q})(\phi(\mathbf{K})^\top\mathbf{V}) removes n^2
Chunked Linear Form Intra-chunk c \times c + inter-chunk \mathbf{Q}_p\mathbf{S} \Theta(nc d_h + n d_h d_v) FLOPs Runs on GPU Tensor Cores without storing n full state matrices
Capacity & Sharpness \operatorname{rank}(\mathbf{S}_t) \le d_h; \beta cancels for \mathrm{elu}+1 Stores at most d_h orthogonal keys Requires data-dependent decay gates \gamma_t and hybrid softmax layers