from torch.nn.attention.flex_attention import create_block_mask, flex_attention10.6 窗口注意力与线性注意力
融合核函数(10.5 节)消除了 \(O(n^2)\) 的中间得分矩阵,但其 \(\Theta(n^2 d)\) 浮点运算数与键值缓存依然随序列长度 \(n\) 增长。然而,在处理 100,000 个词元的文档时,大多数词元主要依赖局部上下文,只有偶发查找才需要长程检索。
有两种主流架构策略将注意力的计算开销降至 \(O(n)\):
- 滑动窗口注意力 (Child 等 2019年; Beltagy 等 2020年) 将每个查询限制在最近的 \(w\) 个键上,将单层计算量降至 \(O(nw)\),并将键值缓存封顶在 \(w\) 个词元。
- 线性注意力 (Katharopoulos 等 2020年) 用因子化核 \(\phi(\mathbf{q})^\top \phi(\mathbf{k})\) 替代 softmax 核 \(\exp(\mathbf{q}^\top\mathbf{k}/\sqrt{d_h})\),使键与值得以累加进固定大小的 \(d_h \times d_v\) 循环状态矩阵。
这两种方法计算的函数都不同于稠密 softmax 注意力。本节分析滑动窗口如何以单跳可达性换取瓦片稀疏性,推导线性注意力的并行、循环与分块三种形式,并阐明为何因子化特征映射缺乏 softmax 的温度锐化能力。
10.6.1 滑动窗口注意力
10.6.1.1 带状掩码
在宽度为 \(w\) 的因果滑动窗口注意力中,查询 \(i\) 仅当 \(j \le i\) 且 \(i - j < w\) 时才关注键 \(j\)。因果性与局部性的这一合取,用至多 \(nw\) 个活跃对的对角带取代了包含 \(n(n+1)/2\) 个活跃对的下三角:
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)def window_mask(n, w):
"""Causal band: query i may attend to keys i - w + 1, ..., i."""
i = jnp.arange(n)
return d2l.causal_mask(n) & (i[:, None] - i[None, :] < w)10.6.1.2 感受野随深度增长
正如堆叠卷积层会随深度扩大感受野(第 6 章),堆叠 \(L\) 层宽度为 \(w\) 的滑动窗口层使信息每层向前传播 \(w - 1\) 步,理论感受野达到
\[1 + L(w - 1) \tag{10.6.1}\]
个词元。例如,Mistral 7B v0.1 (Jiang 等 2023年) 在 \(L = 32\) 层上取 \(w = 4{,}096\),跨度可达 \(131{,}041\) 个词元。然而,理论可达范围不同于直接检索:全自注意力以单跳连接任意两个词元,而窗口堆叠需要跨越 \(\lceil \Delta / (w - 1) \rceil\) 层顺序接力才能把信息传递距离 \(\Delta\)。接力信息还会逐跳稀释。图 10.6.1 展示了最小情形:在均匀窗口平均(\(w = 4\),\(L = 4\))下,边界 \(\Delta = 12\) 处的词元沿唯一一条四跳路径抵达,权重仅为 \((1/4)^4 = 1/256\),而在单个全局层中为 \(1/13\)。
10.6.1.3 全局层
为了在保留局部窗口大部分显存与算力节省的同时维持一跳长程检索,现代长上下文架构将 \(r\) 个窗口层与一个全(全局)注意力层交错排布——例如 Gemma 3 每配置 \(r = 5\) 个窗口层(\(w = 1{,}024\))就插入一个全局层 (Gemma Team 2025年)。由于窗口层在生成期间只需缓存最近 \(\min(n, w)\) 个键与值(11.3 节),交错排布将总 KV 缓存缩减为全全局堆叠的
\[ \frac{r \min(n, w) + n}{(r + 1)\, n} \;\xrightarrow{n \gg w}\; \frac{1}{r + 1} \]
倍(对 \(r = 5, w = 1{,}024\),在 \(n = 8{,}192\) 时为 \(\approx 27\%\),渐近趋近 \(1/6\))。
10.6.1.4 融合核函数中的瓦片
在稠密 \(n \times n\) 矩阵乘法中施加 window_mask 依然会算出全部 \(n^2\) 个得分。要真正实现 \(O(nw)\) 时间与显存,实现必须只评估活跃带——例如把查询按大小 \(w\) 分块,每块仅关注当前与紧邻前一个键块(合计 \(2nw\) 个得分):
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)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: jnp.concatenate([jnp.zeros_like(X[:1]), X[:-1]])
Kb = jnp.concatenate([prev(Kb), Kb], 1)
Vb = jnp.concatenate([prev(Vb), Vb], 1)
i = jnp.arange(w)[:, None] # Query in its block
j = jnp.arange(-w, w)[None, :] # Key offset from it
first = jnp.arange(n // w)[:, None, None] == 0
mask = (j <= i) & (i - j < w) & ~(first & (j < 0)) # No keys before 0
scores = Qb @ Kb.swapaxes(-1, -2) / math.sqrt(d_h)
return (d2l.masked_softmax(scores, mask) @ Vb).reshape(n, -1)在 FlashAttention 或 FlexAttention (Dong 等 2025年) 等分片 GPU 核函数中,计算按 \(b \times b\) 瓦片进行(FlexAttention 默认 \(b = 128\)),仅当一个瓦片的全部 \(b^2\) 个元素都被掩码时才跳过它。在 \(n = 2{,}048\)、\(b = w = 128\) 处,因果掩码访问 \(T^2\) 个瓦片中的 \(T(T+1)/2\) 个(\(T = n/b = 16\) 时为 \(53.1\%\)),而滑动窗口在每个瓦片行只访问对角瓦片及其左侧相邻瓦片(共 \(2T - 1 = 31\) 个瓦片,即 \(12.1\%\);图 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
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 float(mask.reshape(T, b, T, b).any(axis=(1, 3)).mean())
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
windowed_attention 与框架的融合滑动窗口核函数均在 float32 舍入误差内与稠密掩码定义一致:
融合核函数为配合 create_block_mask 的 flex_attention。
融合核函数为设置 local_window_size=(w - 1, 0) 的 dot_product_attention。
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
n, w, d_h = 2048, 128, 64
Q, K, V = (jax.random.normal(k, (n, d_h))
for k in jax.random.split(d2l.get_key(), 3))
with jax.default_matmul_precision('highest'):
reference = d2l.masked_softmax(Q @ K.T / math.sqrt(d_h),
window_mask(n, w)) @ V
# The window as an argument: w - 1 keys back, none ahead. The default
# XLA implementation runs in float32; cuDNN's needs 16-bit inputs
fused = jax.nn.dot_product_attention(
Q[None, :, None], K[None, :, None], V[None, :, None],
is_causal=True, local_window_size=(w - 1, 0))
for name, O in (('blocked', windowed_attention(Q, K, V, w)),
('fused kernel', fused[0, :, 0])):
print(f'{name:>12}: maximum deviation '
f'{float(jnp.abs(O - reference).max()):.2e}') blocked: maximum deviation 2.98e-07
fused kernel: maximum deviation 0.00e+00
10.6.1.5 窗口核函数与稠密核函数对比
当有 \(T = n / 128\) 个瓦片行时,活跃因果瓦片数与活跃窗口瓦片数(\(w = b = 128\))之比为 \(T(T + 1) / (2(2T - 1)) \approx T/4\),预测在 \(n = 32{,}768\)(\(T = 256\))处有 \(64\times\) 的理论瓦片缩减。我们在同一融合 bfloat16 核函数中跨 \(n \in [512, 32{,}768]\)(\(H = 32\) 头,\(d_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
# cuDNN takes (batch, length, heads, width); it skips the tiles outside the
# band only together with is_causal=True
w = b = 128 # Window width; tile size of the kernel
masks = {'dense causal': {},
f'window (w={w})': {'local_window_size': (w - 1, 0)}}
kernels = {name: jax.jit(lambda X, kw=kw: jax.nn.dot_product_attention(
X, X, X, is_causal=True, implementation='cudnn', **kw))
for name, kw in masks.items()}
H, lengths = 32, [512, 1024, 2048, 4096, 8192, 16384, 32768]
times = {name: [] for name in masks}
for n in lengths:
X = jax.random.normal(d2l.get_key(), (1, n, H, d_h), dtype=jnp.bfloat16)
for name, f in kernels.items():
times[name].append(d2l.Benchmark(lambda: f(X)).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 0.8x faster, tile count predicts 1.4x
n = 1,024: window 0.9x faster, tile count predicts 2.4x
n = 2,048: window 1.6x faster, tile count predicts 4.4x
n = 4,096: window 7.3x faster, tile count predicts 8.4x
n = 8,192: window 9.0x faster, tile count predicts 16.4x
n = 16,384: window 20.5x faster, tile count predicts 32.4x
n = 32,768: window 31.9x faster, tile count predicts 64.4x
超过 \(n \approx 2{,}048\) 后,稠密因果耗时按二次方增长,而窗口耗时按线性增长,在 \(n = 32{,}768\) 处取得 \(> 30\times\) 加速。这大约是瓦片计数所预测的 \(64\times\) 的一半到四分之三。瓦片计数把每个被访问的瓦片视为同等工作量,因此它给出的是加速上界而非精确估计。
在 FlexAttention 中,宽度为 \(b\) 的带状掩码访问的每个瓦片都被掩码边界切开(图 10.6.2),都需要付出逐元素掩码开销,而因果三角内部的瓦片则无掩码运行。
cuDNN 未公开其得分矩阵分片方式,因此此处假设 \(b = 128\)。
10.6.2 线性注意力
10.6.2.1 核化得分函数
线性注意力 (Katharopoulos 等 2020年) 不再限制参与打分的词元对,而是用基于非负逐元素特征映射 \(\phi: \mathbb{R}^{d_h} \to \mathbb{R}_+^{d_h}\) 的因子化核 \(K(\mathbf{q}, \mathbf{k}) = \phi(\mathbf{q})^\top \phi(\mathbf{k})\) 取代指数相似度 \(\exp(\mathbf{q}^\top\mathbf{k}/\sqrt{d_h})\)。利用矩阵乘法结合律,
\[ \bigl(\phi(\mathbf{Q})\,\phi(\mathbf{K})^\top\bigr)\,\mathbf{V} = \phi(\mathbf{Q})\,\bigl(\phi(\mathbf{K})^\top \mathbf{V}\bigr), \]
避开了 \(n \times n\) 矩阵 \(\phi(\mathbf{Q})\phi(\mathbf{K})^\top\),转而计算 \(d_h \times d_v\) 汇总矩阵。在因果掩码(\(s \le t\))下,将 \(\phi(\mathbf{q}_t)^\top\) 提到分子分母求和号外可得
\[ \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}\]
沿用 Katharopoulos 等 (2020年),我们逐元素取 \(\phi(x) = \mathrm{elu}(x) + 1 > 0\)(并在分母加小常数 \(\epsilon = 10^{-6}\) 以防 float32 下溢)。前缀和 \((\mathbf{S}_t, \mathbf{z}_t)\) 满足线性递推
\[ \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}\]
从而将因果注意力转化为一个循环神经网络:其隐藏状态是以外积更新的 \(d_h \times d_v\) 联想记忆矩阵(快速权重编程器,(Schlag 等 2021年))。我们既可通过累积和(cumsum)并行计算 式 10.6.2,也可在 \(O(d_h d_v)\) 内存中逐步循环计算:
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)def phi(X):
return jax.nn.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 = jnp.cumsum(Kp[:, :, None] * V[:, None, :], axis=0) # (n, d_h, d_v)
z = jnp.cumsum(Kp, axis=0) # (n, d_h)
den = (Qp * z).sum(-1, keepdims=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)
def step(carry, qkv):
S, z = carry
q, k, v = qkv
S = S + k[:, None] * v[None, :] # Outer-product write
z = z + k
return (S, z), q @ S / (q @ z + eps) # Query the memory
init = (jnp.zeros((Q.shape[-1], V.shape[-1])), jnp.zeros(Q.shape[-1]))
_, outputs = jax.lax.scan(step, init, (Qp, Kp, V))
return outputs10.6.2.2 分块计算
在 GPU 上训练时,linear_attention_parallel 物化全部 \(n\) 个中间矩阵 \(\mathbf{S}_t \in \mathbb{R}^{d_h \times d_v}\) 会耗费 \(O(n d_h d_v)\) 显存(在 \(n = 16{,}384, d_h = d_v = 64\) 时每头 256 MiB),而 linear_attention_recurrent 执行 \(n\) 步顺序向量运算,无法充分利用 GPU 矩阵核心。将序列切分为长度为 \(c\) 的块 (Yang 等 2024年) 兼顾二者之长:对起始于 \(t_0\)、块前状态为 \((\mathbf{S}, \mathbf{z})\) 的块,
\[ \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}\]
使块内注意力(\(c \times c\))与块间状态传播均采用稠密矩阵乘法,以 \(O(nc(d_h + d_v) + n d_h d_v)\) 浮点运算运行,且仅存储 \(n/c\) 个块状态:
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)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 = jnp.cumsum(Kp.swapaxes(-1, -2) @ Vc, axis=0) # (n/c, d_h, d_v)
z = jnp.cumsum(Kp.sum(1), axis=0) # (n/c, d_h)
S = jnp.concatenate([jnp.zeros_like(S[:1]), S[:-1]])
z = jnp.concatenate([jnp.zeros_like(z[:1]), z[:-1]])
A = jnp.tril(Qp @ Kp.swapaxes(-1, -2)) # (n/c, c, c)
num = Qp @ S + A @ Vc # Past + this chunk
den = Qp @ z[..., None] + A.sum(-1, keepdims=True) + eps
return (num / den).reshape(n, -1)三种形式在 float32 舍入误差内给出完全相同的输出,且无论序列多长,循环状态每头仅占恒定的 16 KiB(\(64 \times 64 + 64\) 个浮点数):
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
n = 512
Q, K, V = (jax.random.normal(k, (n, d_h))
for k in jax.random.split(d2l.get_key(), 3))
with jax.default_matmul_precision('highest'):
recurrent = linear_attention_recurrent(Q, K, V)
for name, f in (('parallel', linear_attention_parallel),
('chunked', linear_attention_chunked)):
err = jnp.abs(f(Q, K, V) - recurrent).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 2.38e-07
chunked: maximum deviation 3.87e-07
recurrent state: 64x64 + 64 floats = 16 KiB at any sequence length
10.6.2.3 容量与锐度
将任意数量的键值对压缩进 \(d_h \times d_v\) 状态矩阵会付出两项根本代价:
- 有限联想容量:由于 \(\phi(\mathbf{k}_s) \in \mathbb{R}_+^{d_h}\) 非负,查询唯有在键特征向量近似正交(支撑几乎不相交)时才能无串扰地分离出单个存储值,这将精确检索限制在至多 \(d_h\) 个键以内。
- 缺乏温度锐化:在 softmax 注意力中,将查询放大 \(\beta > 1\) 倍会把得分差指数放大(\(e^{\beta \Delta}\)),当 \(\beta \to \infty\) 时推动分布趋近独热查找。而在采用 \(\phi(x) = \mathrm{elu}(x) + 1\) 的线性注意力中,将 \(\mathbf{q}\) 放大较大的 \(\beta\) 倍得到 \(\phi(\beta \mathbf{q}) \approx \beta\, \mathrm{relu}(\mathbf{q})\),缩放因子 \(\beta\) 在分子与分母之间直接相消(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
kq, kk = jax.random.split(d2l.get_key())
Q, K = jax.random.normal(kq, (1000, d_h)), jax.random.normal(kk, (8, d_h))
for beta in (1, 4, 16): # Scale the queries up; 8 keys: uniform is 0.125
soft = jax.nn.softmax(beta * Q @ K.T / math.sqrt(d_h), axis=-1)
lin = phi(beta * Q) @ phi(K).T
lin = lin / lin.sum(-1, keepdims=True)
print(f'queries x{beta:<2}: mean largest weight, softmax '
f'{soft.max(-1).mean():.2f}, elu+1 {lin.max(-1).mean():.2f}')queries x1 : mean largest weight, softmax 0.35, elu+1 0.14
queries x4 : mean largest weight, softmax 0.74, elu+1 0.15
queries x16: mean largest weight, softmax 0.93, elu+1 0.15
10.6.2.4 各机制下的召回表现
上述两项局限以及窗口的局限,在最简单的查找任务中便暴露无遗。我们存入 \(N\) 个宽度为 \(d_h = 64\) 的随机键值对,用其中一个存储键发起查询,当输出与正确值的内积大于与其余任何存储值的内积时记为命中。四种机制同时应答:稠密 softmax 注意力;仅能看到最近 \(w = 16\) 对的窗口;采用 elu+1 特征映射的线性注意力;以及外积状态 \(\mathbf{q}^\top \sum_i \mathbf{k}_i \mathbf{v}_i^\top\)(即恒等特征映射且无规范化的线性注意力)。最后一种撇开特征映射,专门展示 \(d_h \times d_v\) 状态本身的容量:
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
def recall(N, w=16, trials=1000):
"""Look up one of N stored pairs by its key; fraction of hits per rule."""
key_K, key_V, key_t = jax.random.split(d2l.get_key(), 3)
K, V = (jax.random.normal(k, (trials, N, d_h)) for k in (key_K, key_V))
target = jax.random.randint(key_t, (trials,), 0, N)
q = K[jnp.arange(trials), target][:, None] # (trials, 1, d_h)
scores = q @ K.swapaxes(1, 2) / math.sqrt(d_h) # (trials, 1, N)
recent = jnp.arange(N) >= N - w # The last w pairs
lin = phi(q) @ phi(K).swapaxes(1, 2)
outputs = {'softmax': jax.nn.softmax(scores, axis=-1) @ V,
f'window (w={w})': d2l.masked_softmax(scores, recent) @ V,
'elu+1': lin / lin.sum(-1, keepdims=True) @ V,
'outer-product state': q @ (K.swapaxes(1, 2) @ V)}
# A hit: of the N stored values, the target is nearest to the output
return {name: float(((O @ V.swapaxes(1, 2)).argmax(-1)[:, 0] == target)
.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.21, outer-product state 1.00
N = 64: softmax 1.00, window (w=16) 0.25, elu+1 0.03, outer-product state 0.99
N = 256: softmax 1.00, window (w=16) 0.07, elu+1 0.01, outer-product state 0.66
N = 1024: softmax 1.00, window (w=16) 0.02, elu+1 0.00, outer-product state 0.09
softmax 注意力在每个 \(N\) 上都能找回目标对。窗口仅当目标对落在最近 \(w\) 个之内时才命中,因此召回率约为 \(w/N\):\(N = 16\) 时满分,\(N = 64\) 时降为四分之一,\(N = 1{,}024\) 时仅剩百分之几。更引人注目的是 elu+1 线性注意力,它连在 \(N = 16\)(状态行数足足是存储对数的四倍)时都失败了:其权重无法锐化,输出接近所有存储值的平均,正确值几乎无法脱颖而出。
外积状态表现好得多,并清晰展现出容量极限。对查询 \(\mathbf{q} = \mathbf{k}_j\),其输出为 \(\|\mathbf{k}_j\|^2\, \mathbf{v}_j \approx d_h \mathbf{v}_j\) 加上来自其余对的串扰 \(\sum_{i \ne j} (\mathbf{k}_j^\top \mathbf{k}_i)\, \mathbf{v}_i\)。每个串扰系数幅值约为 \(\sqrt{d_h}\),因此噪声相对信号之比约为 \(\sqrt{(N - 1)/d_h}\)。直到 \(N \approx d_h\) 召回仍近乎完美,在 \(N = 4 d_h\) 处跌至约三分之二,到 \(N = 16 d_h\) 时彻底崩塌。softmax 注意力保留全部 \(N\) 对并在任意 \(N\) 下都能召回;固定大小的状态则只能在 \(N\) 贴近其宽度时维持召回。
10.6.3 选择合适的机制
- 精确融合注意力是中短上下文的默认方案,在 \(O(n)\) 工作显存内提供精确的一跳检索。
- 交错滑动窗口与全局层是长上下文 Transformer(如 Gemma 3)的标准配置,在局部层大幅削减 KV 缓存与瓦片浮点运算,同时在周期性全局层保留一跳全局路由。
- 线性注意力需要数据相关的衰减门(以遗忘旧条目;见 4 与 第 12 章)以及与全 softmax 层的混合交错(如 MiniMax-01,(MiniMax 2025年)),才能胜任精确联想召回 (Arora 等 2024年; Yang 等 2024年)。
10.6.4 小结
滑动窗口注意力将每个查询限制在最近的 \(w\) 个键上,将算术量降至 \(O(nw)\)、缓存显存降至 \(O(w)\),同时跨 \(L\) 层将有效感受野扩展至 \(1 + L(w - 1)\) 个词元;现代长上下文模型将这些局部层与周期性全局注意力层交错以保留单跳检索。在 GPU 上,分片核函数通过跳过全被掩码的 \(b \times b\) 得分瓦片实现加速(受限于边界掩码开销)。线性注意力则走代数路线,用因子化相似度核 \(\phi(\mathbf{q})^\top \phi(\mathbf{k})\) 替代指数得分,将因果注意力折叠为固定 \(d_h \times d_v\) 矩阵状态上的 \(O(n)\) 递推,并支持按并行块训练。由于带非负特征的固定大小状态既无法通过缩放查询来锐化权重,也无法无串扰地存储超过 \(O(d_h)\) 个正交键,实用的线性注意力架构都会结合数据相关衰减门与混合 softmax 层。
10.6.5 练习
- [code] 融合核函数的瓦片。融合核函数在 \(b \times b\) 得分瓦片上运行,仅当掩码排除整个瓦片时才跳过它。令 \(T = n/b\)。
- 证明因果掩码在 \(T^2\) 个瓦片中保留 \(T(T+1)/2\) 个,而宽度为 \(w = kb\)(整数 \(k < T\))的窗口保留 \(T(k + 1) - k(k + 1)/2\) 个。用
tiles_visited检验两项计数。当 \(w\) 不是 \(b\) 的整数倍时,计数如何变化? - 将多篇文档打包进一条长度为 \(n = 2048\) 个词元的序列,掩码如 10.2 节 那样将因果性与“同文档”组合。在 \(b = 128\) 下使用
tiles_visited,对比四篇各 512 词元的文档与长度分别为 1,000、600、300 和 148 词元的文档。解释为何边界未落在瓦片边界上的文档耗费更多瓦片。
- 证明因果掩码在 \(T^2\) 个瓦片中保留 \(T(T+1)/2\) 个,而宽度为 \(w = kb\)(整数 \(k < T\))的窗口保留 \(T(k + 1) - k(k + 1)/2\) 个。用
- [code] 特征映射。
phi中的特征映射 \(\phi(x) = \mathrm{elu}(x) + 1\) 只是众多选择之一。在 \(n = 512\) 个宽度为d_h的随机查询与键上,将其与逐元素施加的 \(\phi(x) = \mathrm{relu}(x)\) 及 \(\phi(x) = \exp(x)\) 对比。- 对每种映射,计算因果线性注意力权重矩阵,其元素为 \[\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,\] 测量它与因果 softmax 权重矩阵
d2l.masked_softmax(Q @ K.T / math.sqrt(d_h), d2l.causal_mask(n))的最大绝对差值以及各行的平均熵。 - 在关于 \(\mathbf{q}_t\) 与键 \(\mathbf{k}_1, \ldots, \mathbf{k}_t\) 的什么条件下,ReLU 映射会产生未定义行?当所有元素独立服从标准正态分布时,推导第 \(t\) 行发生该事件的概率,并在宽度 \(64\) 与宽度 \(4\) 下计算 \(t = 1\) 处的概率。
- 正文将查询按 \(\beta \in \{1, 4, 16\}\) 缩放并观察最大权重。对 ReLU 与指数映射做同样实验,改为测量平均行熵。针对三种映射各自推导 \(\beta \to \infty\) 时规范化权重的极限,并解释为何它们在 softmax 变为独热之处无一能变为独热。
- 对每种映射,计算因果线性注意力权重矩阵,其元素为 \[\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,\] 测量它与因果 softmax 权重矩阵
- 精确特征映射。● softmax 核 \(K(\mathbf{q}, \mathbf{k}) = \exp(\mathbf{q}^\top \mathbf{k} / \sqrt{d_h})\) 同样可以因子化,但需要无穷维特征。
- 将 \(K\) 展开为泰勒级数,证明第 \(p\) 阶项等于 \(\phi_p(\mathbf{q})^\top \phi_p(\mathbf{k})\),其中 \(\phi_p\) 是由自变量的 \(p\) 重张量积构造的 \(d_h^p\) 维特征映射。
- 在 \(2\) 阶处截断级数。证明截断核对任意 \(\mathbf{q}\) 与 \(\mathbf{k}\) 恒正,从而 式 10.6.2 的规范化分母不会为零,并给出拼接 \(\phi_0\)、\(\phi_1\) 与 \(\phi_2\) 所得特征映射的维度。对 \(d_h = 64\) 与宽度 \(64\) 的值,计算单精度下状态 \((\mathbf{S}, \mathbf{z})\) 的大小,以及 softmax 头的键值缓存达到相同大小时的长度 \(n\)。此类截断正是 Based (Arora 等 2024年) 的特征映射。
- 已知对互异的 \(\mathbf{x}_1, \ldots, \mathbf{x}_n\),以 \(K(\mathbf{x}_i, \mathbf{x}_j)\) 为元素的 \(n \times n\) 矩阵正定。证明当查询与键重合时,不存在维度 \(D < n\) 的特征映射能在这些点上精确复现 \(K\)。
- [code] 衰减状态。● 给 式 10.6.3 的状态引入标量衰减 \(\gamma \in (0, 1)\): \[\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}\]
- 证明并行形式现在以 \(\gamma^{t-s}\) 加权位置 \(s\) 对位置 \(t\) 输出的贡献,并通过用 \(\gamma\) 的幂次重缩放
linear_attention_parallel的累积和来实现它。 - 将该衰减加入
linear_attention_recurrent,并验证在 \(n = 512\)、\(\gamma = 0.99\) 下两种形式一致。 - 该重缩放在累积和之前将位置 \(s\) 乘以 \(\gamma^{-s}\)。在 \(\gamma = 0.9\) 与 \(\gamma = 0.5\) 下,从哪个 \(n\) 开始会在单精度中上溢?
- 将衰减加入
linear_attention_chunked:相对于所在块的起始位置重缩放每个位置,并以衰减递推将状态从一块传至下一块。证明不会出现大于 \(\gamma^{-c}\) 的因子;在 \(\gamma = 0.5\)、\(n = 512\)、\(c = 64\) 下运行并与循环形式对比。 - 计算 \(\gamma = 0.99\) 时权重 \(\gamma^{t-s}\) 跌破 \(0.01\) 所需的滞后步数。某任务要求召回 \(2000\) 位之前的一个词元,中间全是填充词元。解释为何没有任何固定 \(\gamma\) 能同时服务好该词元与填充词元,以及由每个词元自身输入算出的衰减能如何解决这一矛盾。
- 证明并行形式现在以 \(\gamma^{t-s}\) 加权位置 \(s\) 对位置 \(t\) 输出的贡献,并通过用 \(\gamma\) 的幂次重缩放