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)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
Motivation
Design Trade-Offs
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):
window_mask(n, w) is the logical AND (&) of d2l.causal_mask(n) and the offset constraint i[:, None] - i[None, :] < w.Multi-Hop Propagation
Hybrid Long-Context Architectures
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)Hardware Tile Skipping
causal: 53.1% of tiles
window: 12.1% of tiles
blocked: maximum deviation 4.17e-07
fused kernel: maximum deviation 6.56e-07
Wall-Clock Scaling up to 32K
bfloat16 fused kernel (H = 32, d_h = 64) from n = 512 to n = 32{,}768: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
Factorized Kernels
Recurrent Matrix State
float32 at d_h = d_v = 64) for any sequence length n.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) / denTwo 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)Chunkwise Parallel Form
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
Systems Comparison
cumsum): Materializes all n state matrices (256\text{ MiB} at n = 16\text{K}); useful only for short debug sequences.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:
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
Architectural Decision Guide
Check Your Understanding
Check Your Understanding
Answers:
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 |