def attention(Q, K, V):
"""softmax(Q K^T / sqrt(d_h)) V through the full score matrix."""
scores = Q @ K.transpose(-2, -1) / math.sqrt(Q.shape[-1])
return torch.softmax(scores, dim=-1) @ VDive into Deep Learning · §10.5
大规模注意力:显存带宽、在线 Softmax 与 FlashAttention
二次方浮点运算与显存缩放 · 算术强度 · 分块在线 softmax · SRAM 分片 · FlashAttention
动机
算术缩放
显存分配
为何朴素注意力在 float32 下每头分配 8n^2 字节临时显存?
scores = Q @ K.T / sqrt(d_h) 分配 4n^2 字节,softmax(scores) 在乘以 V 之前又为权重分配第二个 4n^2 字节缓冲区。实证基准
在单个 float32 头(d_h = 64)上测量峰值临时显存(d2l.peak_memory)与挂钟时间(d2l.Benchmark),证实精确的 8n^2 字节占用,且在 n \ge 8{,}192 后 n 每翻倍耗时跃升 4\times:
n = 2048: measured 40.6 MiB, predicted 8n^2 B = 32.0 MiB
n = 4096: measured 129.0 MiB, predicted 8n^2 B = 128.0 MiB
n = 8192: measured 514.0 MiB, predicted 8n^2 B = 512.0 MiB
n = 16384: measured 2052.0 MiB, predicted 8n^2 B = 2048.0 MiB
n = 2048: 0.07 ms/call
n = 4096: 0.46 ms/call
n = 8192: 1.84 ms/call
n = 16384: 7.37 ms/call
两遍扫描瓶颈
float16 上溢,在 a_j \approx 88.7 以上令 float32 上溢。在线 Softmax 递推
分步数值追踪
线性工作显存
代码实现
参考实现 causal_attention 物化完整的 n \times n 得分矩阵,是所有更快核函数必须对齐的基线:
代码实现
用 finfo(dtype).min 而非 -\infty 做掩码,确保全掩码块不产生 -\infty - (-\infty) = \mathrm{NaN}:
def chunked_attention(Q, K, V, chunk_size=512):
"""Exact causal attention, one n-by-chunk_size block at a time."""
n, d_h = Q.shape
m = torch.full((n, 1), torch.finfo(Q.dtype).min, device=Q.device)
s = torch.zeros(n, 1, device=Q.device)
O = torch.zeros(n, V.shape[-1], device=Q.device)
pos_q = torch.arange(n, device=Q.device)[:, None]
for start in range(0, n, chunk_size):
Kc, Vc = K[start:start + chunk_size], V[start:start + chunk_size]
pos_k = torch.arange(start, start + Kc.shape[0], device=Q.device)
scores = Q @ Kc.T / math.sqrt(d_h)
scores.masked_fill_(pos_k[None, :] > pos_q, torch.finfo(Q.dtype).min)
m_new = torch.maximum(m, scores.max(dim=-1, keepdim=True).values)
scale = torch.exp(m - m_new) # Rescale the past
P = torch.exp(scores - m_new)
s = s * scale + P.sum(dim=-1, keepdim=True)
O = O * scale + P @ Vc
m = m_new
return O / s分块对比全矩阵基准
chunked_attention 与 causal_attention 误差在 \sim 10^{-7} 以内(float32 舍入):maximum deviation: 2.38e-07
chunked_attention(c = 512)仅用 \approx 36\text{--}132\text{ MiB}(省 >17\times)。n = 16,384: full matrix 2308.0 MiB, chunked 132.4 MiB
GPU 显存层次
屋顶线分析
IO 感知核函数融合
代码与挂钟加速
我们在 float16、B = 2 条序列、H = 8 个头、d_h = 64、n = 8{,}192 上对比 causal_attention 与框架融合 FlashAttention 核函数:
def fused_attention(Q, K, V, is_causal=True):
"""Attention in PyTorch's fused FlashAttention kernel."""
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
return F.scaled_dot_product_attention(Q, K, V, is_causal=is_causal)
B, H, n = 2, 8, 8192
X = torch.randn(B, H, n, d_h, device=d2l.try_gpu(), dtype=torch.float16)
# The unmasked kernel computes every tile: it shows what skipping saves
for name, f in [('naive', causal_attention), ('fused', fused_attention),
('fused, no mask',
lambda Q, K, V: fused_attention(Q, K, V, is_causal=False))]:
t = d2l.Benchmark(lambda: f(X, X, X)).time
mem = d2l.peak_memory(f, X, X, X)
print(f'{name:>14}: {t*1e3:6.2f} ms, peak memory {mem/2**20:7.1f} MiB') naive: 19.95 ms, peak memory 4176.0 MiB
fused: 1.08 ms, peak memory 16.5 MiB
fused, no mask: 1.72 ms, peak memory 16.5 MiB
拆解基准结果
对比 naive、fused(因果)与 fused, no mask 分离出两个独立的加速来源:
naive \to fused, no mask):将峰值临时显存从 \sim 4{,}096\text{ MiB}(16 \times 4n^2 字节)压低至 16\text{ MiB} 输出张量的小倍数(显存缩减 > 80\times),并贴近 Tensor Core 峰值吞吐率(2.7 \times 10^{11}\text{ FLOPs})提速数倍。fused, no mask \to fused):由于因果掩码将对角线以上(j > i)全部置零,分片核函数直接跳过整个空上三角瓦片而不予计算。架构视角
概念自测
演练以下三道系统与算法问题:
float16(最大有限值 65{,}504 \approx e^{11.09})下,若不减去运行最大值 m 而直接累加 \sum_j e^{a_j},当缩放得分达到 a_j = 12 时会发生什么?概念自测
答案:
inf,随后在输出规范化处产生 inf / inf = NaN。携带 m 保证 a_j - m' \le 0,使每个指数都落在 (0, 1] 内。本节要点