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
窗口、稀疏与线性注意力
滑动窗口掩码 · 多跳感受野 · 瓦片稀疏性 · 核化线性注意力 · 循环与分块形式
动机
设计权衡
局部注意力
宽度为 w 的因果滑动窗口允许查询 i 关注键 j 当且仅当 j \le i(因果性)且 i - j < w(局部性):
window_mask(n, w) 是 d2l.causal_mask(n) 与偏移约束 i[:, None] - i[None, :] < w 的逻辑与(&)。多跳传播
混合长上下文架构
分块实现
把 window_mask(n, w) 传入稠密 n \times n 矩阵乘法仍会计算全部 n^2 个得分。要实现真正的 O(nw) 时间与显存,windowed_attention 将查询按 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)硬件瓦片跳过
causal: 53.1% of tiles
window: 12.1% of tiles
blocked: maximum deviation 4.17e-07
fused kernel: maximum deviation 6.56e-07
高达 32K 的挂钟缩放
bfloat16 融合核函数(H = 32, d_h = 64)内,从 n = 512 至 n = 32{,}768 对稠密因果与滑动窗口(w = 128)计时: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
因子化核
循环矩阵状态
float32 下为 16.25\text{ KiB})。两种等价求值
由于状态递推 \mathbf{S}_t = \sum_{s \le t} \phi(\mathbf{k}_s)\mathbf{v}_s^\top 是前缀和,我们既可通过 cumsum 并行计算,也可逐步顺序计算。并行(训练)形式:
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两种等价求值
循环(生成)形式携带一个 (d_h, d_v) 状态并逐词元更新:
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)分块并行形式
分块代码与等价性
linear_attention_chunked 与另两种形式在 float32 精度(\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
系统对比
cumsum):物化全部 n 个状态矩阵(n = 16\text{K} 时 256\text{ MiB});仅适合短调试序列。根本局限
用有限特征映射 \phi 将无界键值对历史压入固定 d_h \times d_v 矩阵会带来两项根本检索代价:
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
架构决策指南
概念自测
概念自测
答案:
本节要点
| 概念 / 变体 | 数学规则 | 时间与显存开销 | 核心权衡 / 工程教训 |
|---|---|---|---|
| 因果滑动窗口 | j \le i 且 i - j < w | \Theta(nwd) 浮点运算,O(wd) 缓存 | L 层经多跳接力覆盖 1 + L(w-1) 词元 |
| 混合窗口 + 全局 | 每 1 个全局层配 r 个窗口层 | n \gg w 时缓存占比 \to \dfrac{1}{r+1} | 以一小部分 KV 缓存保留 1 跳长程检索 |
| 分片块稀疏 | 仅当全部 b^2 项为 False 时跳过 b \times b 瓦片 |
w=b 窗口访问 2T-1 对比 T(T+1)/2 瓦片 | n=32\text{K} 处提速 > 30\times;将 w 与打包文档对齐瓦片大小 b |
| 线性注意力 | \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) 浮点运算,O(d_h d_v) 状态 | 结合律 (\phi(\mathbf{Q})\phi(\mathbf{K})^\top)\mathbf{V} = \phi(\mathbf{Q})(\phi(\mathbf{K})^\top\mathbf{V}) 消去 n^2 |
| 分块线性形式 | 块内 c \times c + 块间 \mathbf{Q}_p\mathbf{S} | \Theta(nc d_h + n d_h d_v) 浮点运算 | 跑满 GPU Tensor Core 且无需存 n 个完整状态矩阵 |
| 容量与锐度 | \operatorname{rank}(\mathbf{S}_t) \le d_h;\mathrm{elu}+1 下 \beta 相消 | 至多存储 d_h 个正交键 | 需配数据相关衰减门 \gamma_t 与混合 softmax 层 |