10.6 Windowed and Linear Attention

Fused kernels (Section 10.5) eliminate the O(n2)O(n^2) intermediate score matrix, yet both their Θ(n2d)\Theta(n^2 d) FLOP count and their key--value cache still grow with sequence length nn. 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 O(n)O(n):

  1. Sliding-window attention (Child et al., 2019; Beltagy et al., 2020) restricts each query to its ww most recent keys, reducing per-layer work to O(nw)O(nw) and bounding the key--value cache at ww tokens.
  2. Linear attention (Katharopoulos et al., 2020) replaces the softmax kernel exp⁡(q⊤k/dh)\exp(\mathbf{q}^\top\mathbf{k}/\sqrt{d_h}) with a factorized kernel ϕ(q)⊤ϕ(k)\phi(\mathbf{q})^\top \phi(\mathbf{k}), allowing keys and values to be accumulated into a fixed-size dh×dvd_h \times d_v 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_attention

10.6.1 Sliding-Window Attention#

10.6.1.1 The Band Mask#

In causal sliding-window attention of width ww, query ii attends to key jj only if j≤ij \le i and i−j<wi - j \lt w. This conjunction of causality and locality replaces the lower triangle of n(n+1)/2n(n+1)/2 active pairs with a diagonal band of at most nwnw 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 LL sliding-window layers of width ww allows information to propagate w−1w - 1 steps backward per layer, yielding a theoretical receptive field of

1+L(w−1)(10.6.1)1 + L(w - 1) \tag{10.6.1}

tokens. For example, Mistral 7B v0.1 (Jiang et al., 2023) used w=4,096w = 4{,}096 across L=32L = 32 layers, spanning up to 131,041131{,}041 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 ⌈Δ/(w−1)⌉\lceil \Delta / (w - 1) \rceil sequential hops across layers to relay a fact across distance Δ\Delta. A relayed fact is also diluted at every hop. Figure 10.6.1 shows the smallest case: under uniform window averaging (w=4w = 4, L=4L = 4), a token at the boundary Δ=12\Delta = 12 arrives along a single four-hop path with weight (1/4)4=1/256(1/4)^4 = 1/256, compared to 1/131/13 in a single global layer.

Figure 10.6.1:

Stacked windows against one global layer. Left: with four windowed layers of width w=4w = 4, the output at the top right depends on a cone of earlier positions, and the input Δ=12\Delta = 12 positions back reaches it along a single path of four hops (blue), with weight (1/4)4=1/256(1/4)^4 = 1/256 under uniform attention weights. Right: one global layer connects the same two positions in one hop, with weight 1/131/13.

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 rr windowed layers with one full (global) attention layer—for example, Gemma 3 uses r=5r = 5 windowed layers (w=1,024w = 1{,}024) per global layer (Team, 2025). Because a windowed layer caches only the last min⁡(n,w)\min(n, w) keys and values during generation (Section 11.3), interleaving reduces the total KV cache to the fraction

rmin⁡(n,w)+n(r+1) n  →n≫w  1r+1\frac{r \min(n, w) + n}{(r + 1)\, n} \;\xrightarrow{n \gg w}\; \frac{1}{r + 1}

of an all-global stack (≈27%\approx 27\% at n=8,192n = 8{,}192 and 1/61/6 asymptotically for r=5,w=1,024r = 5, w = 1{,}024).

10.6.1.4 Tiles in a Fused Kernel#

Applying window_mask inside a dense n×nn \times n matrix multiplication still computes all n2n^2 scores. To realize O(nw)O(nw) time and memory, an implementation must evaluate only the active band—for instance, by grouping queries into blocks of size ww and attending only to the current and immediately preceding key blocks (2nw2nw 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 b×bb \times b tiles (b=128b = 128 by default in FlexAttention), and a tile is skipped only when all b2b^2 of its entries are masked out. At n=2,048n = 2{,}048 and b=w=128b = w = 128, the causal mask visits T(T+1)/2T(T+1)/2 of the T2T^2 tiles (53.1%53.1\% for T=n/b=16T = n/b = 16), whereas the sliding window visits only the diagonal tile and its left neighbor in each tile row (2T−1=312T - 1 = 31 tiles, or 12.1%12.1\%; 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
Figure 10.6.2:

Tiles visited by a fused kernel, for T=16T = 16 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 T(T+1)/2=136T(T+1)/2 = 136 tiles and cuts only the 1616 on the diagonal. The window of width w=bw = b (right) visits the diagonal tile and its left neighbor in each row, 2T−1=312T - 1 = 31 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 T=n/128T = n / 128 tile rows, the ratio of active causal tiles to active windowed tiles (w=b=128w = b = 128) is T(T+1)/(2(2T−1))≈T/4T(T + 1) / (2(2T - 1)) \approx T/4, predicting a 64×64\times theoretical tile reduction at n=32,768n = 32{,}768 (T=256T = 256). We benchmark both masks inside the same fused bfloat16 kernel across n∈[512,32,768]n \in [512, 32{,}768] (H=32H = 32 heads, dh=64d_h = 64):

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 n≈2,048n \approx 2{,}048, dense causal runtime scales quadratically while windowed runtime scales linearly, reaching a >30×> 30\times speedup at n=32,768n = 32{,}768. This is between one half and three quarters of the 64×64\times 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-bb 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 exp⁡(q⊤k/dh)\exp(\mathbf{q}^\top\mathbf{k}/\sqrt{d_h}) with a factorized kernel K(q,k)=ϕ(q)⊤ϕ(k)K(\mathbf{q}, \mathbf{k}) = \phi(\mathbf{q})^\top \phi(\mathbf{k}) using a nonnegative elementwise feature map ϕ:Rdh→R+dh\phi: \mathbb{R}^{d_h} \to \mathbb{R}_+^{d_h}. By the associativity of matrix multiplication,

(ϕ(Q) ϕ(K)⊤) V=ϕ(Q) (ϕ(K)⊤V),\bigl(\phi(\mathbf{Q})\,\phi(\mathbf{K})^\top\bigr)\,\mathbf{V} = \phi(\mathbf{Q})\,\bigl(\phi(\mathbf{K})^\top \mathbf{V}\bigr),

avoiding the n×nn \times n matrix ϕ(Q)ϕ(K)⊤\phi(\mathbf{Q})\phi(\mathbf{K})^\top in favor of a dh×dvd_h \times d_v summary matrix. Under a causal mask (s≤ts \le t), factoring ϕ(qt)⊤\phi(\mathbf{q}_t)^\top out of the numerator and denominator sums yields

ot⊤=∑s≤tϕ(qt)⊤ϕ(ks) vs⊤∑s≤tϕ(qt)⊤ϕ(ks)=ϕ(qt)⊤Stϕ(qt)⊤zt,St=∑s≤tϕ(ks)vs⊤,zt=∑s≤tϕ(ks).(10.6.2)\begin{aligned} \mathbf{o}_t^\top &= \frac{\sum_{s \leq t} \phi(\mathbf{q}_t)^\top \phi(\mathbf{k}_s)\, \mathbf{v}_s^\top} {\sum_{s \leq t} \phi(\mathbf{q}_t)^\top \phi(\mathbf{k}_s)} = \frac{\phi(\mathbf{q}_t)^\top \mathbf{S}_t} {\phi(\mathbf{q}_t)^\top \mathbf{z}_t}, \\ \mathbf{S}_t &= \sum_{s \leq t} \phi(\mathbf{k}_s) \mathbf{v}_s^\top, \qquad \mathbf{z}_t = \sum_{s \leq t} \phi(\mathbf{k}_s). \end{aligned} \tag{10.6.2}

Following Katharopoulos et al. (2020), we choose ϕ(x)=elu(x)+1>0\phi(x) = \mathrm{elu}(x) + 1 > 0 elementwise (with a small ϵ=10−6\epsilon = 10^{-6} in the denominator against float32 underflow). The prefix sums (St,zt)(\mathbf{S}_t, \mathbf{z}_t) satisfy the linear recurrence

St=St−1+ϕ(kt) vt⊤,zt=zt−1+ϕ(kt),(10.6.3)\begin{aligned} \mathbf{S}_t &= \mathbf{S}_{t-1} + \phi(\mathbf{k}_t)\, \mathbf{v}_t^\top, \\ \mathbf{z}_t &= \mathbf{z}_{t-1} + \phi(\mathbf{k}_t), \end{aligned} \tag{10.6.3}

turning causal attention into an RNN whose hidden state is a dh×dvd_h \times d_v 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 O(dhdv)O(d_h d_v) 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 nn intermediate matrices St∈Rdh×dv\mathbf{S}_t \in \mathbb{R}^{d_h \times d_v} in linear_attention_parallel consumes O(ndhdv)O(n d_h d_v) memory (256 MiB per head at n=16,384,dh=dv=64n = 16{,}384, d_h = d_v = 64), whereas linear_attention_recurrent executes nn sequential vector steps that underutilize GPU matrix cores. Partitioning the sequence into chunks of length cc (Yang et al., 2024) combines both: for a chunk starting at t0t_0 with pre-chunk state (S,z)(\mathbf{S}, \mathbf{z}),

ot⊤=ϕ(qt)⊤S+∑t0≤s≤tϕ(qt)⊤ϕ(ks) vs⊤ϕ(qt)⊤z+∑t0≤s≤tϕ(qt)⊤ϕ(ks),(10.6.4)\mathbf{o}_t^\top = \frac{\phi(\mathbf{q}_t)^\top \mathbf{S} + \sum_{t_0 \le s \le t} \phi(\mathbf{q}_t)^\top\phi(\mathbf{k}_s)\, \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)}, \tag{10.6.4}

so both intra-chunk attention (c×cc \times c) and inter-chunk state propagation use dense matrix multiplications in O(nc(dh+dv)+ndhdv)O(nc(d_h + d_v) + n d_h d_v) FLOPs and store only n/cn/c 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 (64×64+6464 \times 64 + 64 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 dh×dvd_h \times d_v state matrix incurs two fundamental costs:

  1. Finite associative capacity: Because ϕ(ks)∈R+dh\phi(\mathbf{k}_s) \in \mathbb{R}_+^{d_h} 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 dhd_h keys.
  2. Lack of temperature sharpening: In softmax attention, scaling a query by β>1\beta > 1 exponentiates score differences (eβΔe^{\beta \Delta}), driving the distribution toward a one-hot lookup as β→∞\beta \to \infty. In linear attention with ϕ(x)=elu(x)+1\phi(x) = \mathrm{elu}(x) + 1, scaling q\mathbf{q} by large β\beta yields ϕ(βq)≈β relu(q)\phi(\beta \mathbf{q}) \approx \beta\, \mathrm{relu}(\mathbf{q}), so the scale factor β\beta 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 NN random key--value pairs of width dh=64d_h = 64, 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 w=16w = 16 pairs; linear attention with the elu+1 feature map; and the outer-product state q⊤∑ikivi⊤\mathbf{q}^\top \sum_i \mathbf{k}_i \mathbf{v}_i^\top, 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 dh×dvd_h \times d_v 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 NN. The window finds it only when the pair lies among the last ww, so its recall is about w/Nw/N: perfect at N=16N = 16, a quarter at N=64N = 64, and a few percent at N=1,024N = 1{,}024. More striking is elu+1 linear attention, which fails even at N=16N = 16, 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 q=kj\mathbf{q} = \mathbf{k}_j its output is ∥kj∥2 vj≈dhvj\|\mathbf{k}_j\|^2\, \mathbf{v}_j \approx d_h \mathbf{v}_j plus crosstalk ∑i≠j(kj⊤ki) vi\sum_{i \ne j} (\mathbf{k}_j^\top \mathbf{k}_i)\, \mathbf{v}_i from the other pairs. Each crosstalk coefficient has size about dh\sqrt{d_h}, so the noise relative to the signal is about (N−1)/dh\sqrt{(N - 1)/d_h}. Recall is nearly perfect up to N≈dhN \approx d_h, drops to about two thirds at N=4dhN = 4 d_h, and has collapsed at N=16dhN = 16 d_h. Softmax attention keeps all NN pairs and recalls at every NN; a state of fixed size recalls only while NN 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 O(n)O(n) 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 ww most recent keys, reducing arithmetic to O(nw)O(nw) and cache memory to O(w)O(w) while expanding its effective receptive field to 1+L(w−1)1 + L(w - 1) tokens across LL 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 b×bb \times b score tiles, up to boundary masking overhead. Linear attention takes an algebraic route instead, replacing the exponential score with a factorized similarity kernel ϕ(q)⊤ϕ(k)\phi(\mathbf{q})^\top \phi(\mathbf{k}) that collapses causal attention into an O(n)O(n) recurrence over a fixed dh×dvd_h \times d_v matrix state trainable in parallel chunks. Because a fixed-size state with nonnegative features cannot sharpen weights via query scaling or store more than O(dh)O(d_h) orthogonal keys without cross-talk, practical linear-attention architectures incorporate data-dependent decay gates and hybrid softmax layers.

10.6.5 Exercises#

  1. [code] Tiles of a fused kernel. A fused kernel works on tiles of b×bb \times b scores and skips a tile only if the mask excludes all of it. Let T=n/bT = n/b.

    1. Show that a causal mask leaves T(T+1)/2T(T+1)/2 of the T2T^2 tiles, and that a window of width w=kbw = kb, for a whole number k<Tk \lt T, leaves T(k+1)−k(k+1)/2T(k + 1) - k(k + 1)/2. Check both counts with tiles_visited. How does the count change when ww is not a multiple of bb?
    2. Several documents are packed into one sequence of n=2048n = 2048 tokens, and the mask combines causality with "same document" as in the masks of Section 10.2. Using tiles_visited with b=128b = 128, 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.
  2. [code] The feature map. The feature map ϕ(x)=elu(x)+1\phi(x) = \mathrm{elu}(x) + 1 in phi is one choice among many. Compare it with ϕ(x)=relu(x)\phi(x) = \mathrm{relu}(x) and ϕ(x)=exp⁡(x)\phi(x) = \exp(x), both applied elementwise, on n=512n = 512 random queries and keys of width d_h.

    1. For each map, compute the causal linear-attention weight matrix with entries
ϕ(qt)⊤ϕ(ks)∑s′≤tϕ(qt)⊤ϕ(ks′),s≤t,\frac{\phi(\mathbf{q}_t)^\top \phi(\mathbf{k}_s)}{\sum_{s' \leq t} \phi(\mathbf{q}_t)^\top \phi(\mathbf{k}_{s'})}, \qquad s \leq t,

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.

  1. Under which condition on qt\mathbf{q}_t and the keys k1,…,kt\mathbf{k}_1, \ldots, \mathbf{k}_t does the ReLU map produce an undefined row? Derive the probability of this event for row tt when all entries are independent standard normal, and evaluate it for t=1t = 1 at width 6464 and at width 44.
  2. The section scaled the queries by β∈{1,4,16}\beta \in \{1, 4, 16\} 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 β→∞\beta \to \infty, and explain why none of them becomes one-hot where softmax does.
  1. An exact feature map. ● The softmax kernel K(q,k)=exp⁡(q⊤k/dh)K(\mathbf{q}, \mathbf{k}) = \exp(\mathbf{q}^\top \mathbf{k} / \sqrt{d_h}) also factorizes, but only with infinitely many features.

    1. Expand KK in its Taylor series, and show that the degree-pp term equals ϕp(q)⊤ϕp(k)\phi_p(\mathbf{q})^\top \phi_p(\mathbf{k}) for a feature map ϕp\phi_p of dimension dhpd_h^p built from the pp-fold tensor product of its argument.
    2. Truncate the series after degree 22. Show that the truncated kernel is positive for every pair of q\mathbf{q} and k\mathbf{k}, so the normalizer of (10.6.2) cannot vanish, and give the dimension of the feature map that concatenates ϕ0\phi_0, ϕ1\phi_1, and ϕ2\phi_2. For dh=64d_h = 64 and values of width 6464, compute the size of the state (S,z)(\mathbf{S}, \mathbf{z}) in single precision and the length nn 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).
    3. Take as given that the n×nn \times n matrix with entries K(xi,xj)K(\mathbf{x}_i, \mathbf{x}_j) is positive definite for distinct x1,…,xn\mathbf{x}_1, \ldots, \mathbf{x}_n. Show that no feature map of dimension D<nD \lt n reproduces KK exactly on these points when queries and keys coincide.
  2. [code] A decaying state. ● Give the state of (10.6.3) a scalar decay γ∈(0,1)\gamma \in (0, 1),

St=γ St−1+ϕ(kt) vt⊤,zt=γ zt−1+ϕ(kt).(10.6.5)\mathbf{S}_t = \gamma\, \mathbf{S}_{t-1} + \phi(\mathbf{k}_t)\,\mathbf{v}_t^\top, \qquad \mathbf{z}_t = \gamma\, \mathbf{z}_{t-1} + \phi(\mathbf{k}_t). \tag{10.6.5}
  1. Show that the parallel form now weights the contribution of position ss to the output at tt by γt−s\gamma^{t-s}, and implement it by rescaling the cumulative sums of linear_attention_parallel with powers of γ\gamma.
  2. Add the decay to linear_attention_recurrent, and verify that the two forms agree for n=512n = 512 and γ=0.99\gamma = 0.99.
  3. The rescaling multiplies position ss by γ−s\gamma^{-s} before the cumulative sum. For which nn does this overflow single precision at γ=0.9\gamma = 0.9 and at γ=0.5\gamma = 0.5?
  4. 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 γ−c\gamma^{-c} appears, run the result for γ=0.5\gamma = 0.5, n=512n = 512, and c=64c = 64, and compare it with the recurrent form.
  5. Compute the lag at which the weight γt−s\gamma^{t-s} falls below 0.010.01 for γ=0.99\gamma = 0.99. A task requires recalling one token from 20002000 positions back, while the tokens in between are filler. Explain why no fixed γ\gamma serves both that token and the filler, and what a decay computed from each token's own input could do instead.

Discussions