14. FlashAttention Memory Model | FlashAttention 显存模型
难度: Medium | 环境: CPU-first | 标签: 推理优化, FlashAttention, 显存模型 | 目标人群: 系统性能入门者
🚀 云端运行环境
本章节的实战代码可以点击以下链接在免费 GPU 算力平台上直接运行:
本节导读
序列从2048增长到4096时,单个注意力头的完整得分矩阵会扩大四倍。若实现把它写入显存、再读回计算,临时存储和搬运都会增加;FlashAttention通过分块与在线Softmax,避免保存完整的得分与概率矩阵。
本节计算中间矩阵与块级工作集,再解释逐块合并为何仍能得到同一个注意力输出。它支撑推理与算子优化中的注意力访存判断,随后可进入Part02·20的分块模拟和Part03·11的GPU实现。
关键词: 得分矩阵、分块、在线Softmax、片上工作集
前置阅读
先核对注意力计算对象和存储层次,再比较完整矩阵与分块状态。
- 03 GPU架构与内存层次:区分显存、共享内存与寄存器。
- 04 Attention与显存优化:理解Q、K、V、得分矩阵与输出。
Q1:完整得分矩阵为什么会迅速占满临时存储?
对长度为
下面只统计一份得分张量;若完整写出一次再读回一次,逻辑读写量是其大小的两倍。这既不包含其他中间张量,也不等于实际显存流量:缓存和实现方式会改变物理搬运。矩阵越大越值得检查访存,但是否受带宽限制仍需结合运算量与执行测量。
Q1 机制计算器:序列翻倍,存储与一次往返各增加多少?
固定四字节得分,先核对16 MiB与64 MiB,再改变批量大小和头数。MiB按1024进位。
def attention_score_bytes(seq_len: int, batch_size: int = 1,
num_heads: int = 1, dtype_bytes: int = 4) -> int:
"""返回一份完整自注意力得分张量的字节数,不含其他张量。"""
if any(type(value) is not int or value <= 0
for value in (seq_len, batch_size, num_heads, dtype_bytes)):
raise ValueError("序列、批量、头数与元素字节数须为正整数")
return batch_size * num_heads * seq_len * seq_len * dtype_bytes
small = attention_score_bytes(seq_len=2048)
large = attention_score_bytes(seq_len=4096)
assert small == 16 * 1024**2
assert large == 64 * 1024**2 == 4 * small
assert attention_score_bytes(seq_len=4096, batch_size=2, num_heads=4) == 8 * large
for length in (2048, 4096):
size = attention_score_bytes(seq_len=length)
print(f"N={length}: 得分 {size / 1024**2:g} MiB;一次写出再读回 {2 * size / 1024**2:g} MiB")Q2:不保存完整得分,怎样得到相同的归一化输出?
分块(tiling)将Q、K、V划为小块,每次只计算一小块得分。在线Softmax中的“在线”指逐块更新状态,而不是网络服务:对每行保留当前最大得分
例如得分为
Q2 对照验证:完整归一化与逐块合并是否一致?
用同一组得分和值,比较块宽1、2和3;再把全部得分加1000,核对最大值平移仍能避免指数溢出。
import math
def online_attention_scalar(scores: list, values: list, block_size: int) -> float:
"""合并已给定的有限得分与标量值,返回Softmax加权均值。"""
if (not scores or len(scores) != len(values)
or type(block_size) is not int or block_size <= 0):
raise ValueError("得分与值须非空且等长,块宽须为正整数")
if any(not math.isfinite(value) for value in (*scores, *values)):
raise ValueError("得分与值须为有限实数")
maximum, denominator, numerator = -math.inf, 0.0, 0.0
for start in range(0, len(scores), block_size):
block_scores = scores[start:start + block_size]
block_values = values[start:start + block_size]
updated_maximum = max(maximum, max(block_scores))
rescale = math.exp(maximum - updated_maximum)
weights = [math.exp(score - updated_maximum) for score in block_scores]
denominator = denominator * rescale + sum(weights)
numerator = numerator * rescale + sum(w * value for w, value in zip(weights, block_values))
maximum = updated_maximum
return numerator / denominator
scores, values = [0.0, 0.0, math.log(2)], [1.0, 3.0, 5.0]
weights = [math.exp(score - max(scores)) for score in scores]
reference = sum(w * value for w, value in zip(weights, values)) / sum(weights)
assert math.isclose(reference, 3.5)
for block_size in (1, 2, 3):
actual = online_attention_scalar(scores, values, block_size=block_size)
shifted = online_attention_scalar([s + 1000 for s in scores], values, block_size=block_size)
assert math.isclose(actual, reference, abs_tol=1e-12)
assert math.isclose(shifted, reference, abs_tol=1e-12)
print(f"块宽={block_size}: 加权输出 {actual:g}")Q3:块变大后,工作集和分块次数怎样相互制约?
片上存储用来暂存数据和累加状态,容量小于显存;其中共享内存由线程块显式使用,寄存器保存线程临时值,它们不能当成一个可任意互换的SRAM预算。下面用一个方形块的载荷模型分项估算:Q/K/V为两字节元素,局部得分、输出累加器以及每行的最大值与指数和用四字节。块宽128、头维128时,分别为96、64、64和1 KiB,共225 KiB;这个总和用于比较算法工作集,不是某个内核的实际共享内存分配。
块宽变大可减少块组合与循环次数,但增加片上状态;块组合也不等于内核启动次数,一个内核可以遍历多个块。完整得分矩阵与单块得分的大小比只比较存储规模,不能当作显存流量减少倍数或加速比。真实实现还要检查K/V的重复读取、缓冲生命周期、寄存器用量和同步成本;长期KV缓存也仍需单独保存。
| 对象 | 本例载荷模型 | 块宽增大后的变化 |
|---|---|---|
| Q/K/V块 | 随块宽 | |
| 局部得分 | 随块宽平方增长 | |
| 输出累加器 | 随块宽线性增长 | |
| 行统计量 | 随块宽线性增长 | |
| 非因果方形块组合 | 变少,但尾块仍需掩码 |
Q3 机制计算器:先核对225 KiB,再改变块宽与尾块
固定头维128,比较块宽64、128和256。最后用长度130、块宽64核对一维3块与二维9个组合;这里按完整块预留空间。
def num_1d_tiles(seq_len: int, tile_size: int) -> int:
"""返回正长度的一维向上取整块数。"""
if any(type(value) is not int or value <= 0 for value in (seq_len, tile_size)):
raise ValueError("序列长度与块宽须为正整数")
return (seq_len + tile_size - 1) // tile_size
def num_score_tiles(seq_len: int, tile_size: int) -> int:
"""返回非因果方形自注意力的块组合数,不是内核启动次数。"""
return num_1d_tiles(seq_len, tile_size) ** 2
def score_tile_bytes(tile_size: int, dtype_bytes: int = 4) -> int:
"""返回一个完整方形得分块的载荷字节。"""
return attention_score_bytes(seq_len=tile_size, dtype_bytes=dtype_bytes)
def flashattention_working_set_bytes(tile_size: int, head_dim: int,
dtype_bytes: int = 2) -> int:
"""返回Q/K/V、四字节得分、输出累加器及行统计量的载荷总和。"""
if any(type(value) is not int or value <= 0 for value in (tile_size, head_dim, dtype_bytes)):
raise ValueError("块宽、头维与Q/K/V元素字节数须为正整数")
qkv_bytes = 3 * tile_size * head_dim * dtype_bytes
score_bytes = tile_size * tile_size * 4
output_bytes = tile_size * head_dim * 4
statistics_bytes = 2 * tile_size * 4
return qkv_bytes + score_bytes + output_bytes + statistics_bytes
def score_materialization_ratio(seq_len: int, tile_size: int, dtype_bytes: int = 4) -> float:
"""比较完整得分与一个块的存储大小,不计算流量或加速比。"""
return (attention_score_bytes(seq_len=seq_len, dtype_bytes=dtype_bytes)
/ score_tile_bytes(tile_size=tile_size, dtype_bytes=dtype_bytes))
assert flashattention_working_set_bytes(tile_size=128, head_dim=128) == 225 * 1024
assert num_1d_tiles(seq_len=130, tile_size=64) == 3
assert num_score_tiles(seq_len=130, tile_size=64) == 9
assert score_materialization_ratio(seq_len=4096, tile_size=128) == 1024
for tile_size in (64, 128, 256):
working_set = flashattention_working_set_bytes(tile_size=tile_size, head_dim=128)
count = num_score_tiles(seq_len=4096, tile_size=tile_size)
print(f"块宽={tile_size}: 载荷 {working_set / 1024:g} KiB,块组合 {count}")相关阅读
先验证在线状态更新,再查看实际GPU内核如何安排不同存储与执行。
- Part02·20 FlashAttention模拟:分块计算、在线归一化与输出的数值核对。
- Part03·11 Triton FlashAttention:对照掩码、片上状态与实际前向实现。
- FlashAttention论文:阅读分块与显存读写分析,区分算法I/O模型与具体硬件测量。
