Flash Attention V1 & v2
从 Online Softmax 开始理解 Flash Attention
本文用于记录笔者学习 Flash Attention 的思考.
参考资料#
- From Online Softmax to FlashAttention ↗
- Tilelang FlashAttention Examples ↗
- FlashAttention V1 论文 ↗
- FlashAttention V2 论文 ↗
- AIInfraGuide:FlashAttention V2 详解 ↗
Online Softmax#
朴素 Safe Softmax 需要扫描三遍:

Online Softmax 的优化方案是将前两次扫描结合:第一次扫描的状态转移是
如果第二次扫描也可以由类似的状态转移
那么就可以将这两次合并.
然而,这种形式的状态转移并不存在,因为我们无法提前知道最大值.但可以确定的是,我们扫描一遍后一定可以知道最大值,定义
则有
因此可以在求 的同时求 .虽然大部分情况下 ,但
也就是最后结果相等.因此可以优化成扫描两次:

代码参考(未使用 warp shuffle 优化):
#include <cuda_runtime.h>
#include <cfloat>
#include <math.h>
const int BLOCKSIZE = 256;
__global__ void softmax_kernel(const float* input, float* output, int N) {
__shared__ float shared_max[BLOCKSIZE];
__shared__ float shared_sum[BLOCKSIZE];
int tid = threadIdx.x + blockDim.x * blockIdx.x;
float prev_max = -FLT_MAX, prev_sum = 0.0f;
for (int i = tid; i < N; i += blockDim.x * gridDim.x) {
float x = input[i];
float cur_max = fmaxf(prev_max, x);
prev_sum = prev_sum * expf(prev_max - cur_max) + expf(x - cur_max);
prev_max = cur_max;
}
shared_max[tid] = prev_max;
shared_sum[tid] = prev_sum;
__syncthreads();
for (int stride = BLOCKSIZE / 2; stride > 0; stride >>= 1) {
if (tid < stride) {
float m1 = shared_max[tid], m2 = shared_max[tid + stride];
float s1 = shared_sum[tid], s2 = shared_sum[tid + stride];
float m = fmaxf(m1, m2);
shared_sum[tid] = s1 * expf(m1 - m) + s2 * expf(m2 - m);
shared_max[tid] = m;
}
__syncthreads();
}
float global_max = shared_max[0], global_sum = shared_sum[0];
for (int i = tid; i < N; i += blockDim.x * gridDim.x) {
output[i] = expf(input[i] - global_max) / global_sum;
}
}
// input, output are device pointers (i.e. pointers to memory on the GPU)
extern "C" void solve(const float* input, float* output, int N) {
softmax_kernel<<<1, BLOCKSIZE>>>(input, output, N);
cudaDeviceSynchronize();
}cppFlash Attention#
Flash Attention V1 和 V2 的优化在本节放在一起讲,最后直接呈现 V2 的 tilelang 版本.
为什么这么做?笔者在学习 V1 时很疑惑为什么要将 放到外循环, 如果将 放到外循环不仅更符合直觉而且可以减少对结果矩阵 的写回,问了 AI 后发现 V2 就把这个点优化了……
Single Query#
将 Online Softmax 的方法扩展到 Attention 时,最主要是考虑最后的结果 能不能用之前 一样的处理思路.
先看朴素 MHA.由于求 softmax 是逐行求,我们只需要模拟 的单行(也可以看作是 decode 过程)就可以推广到多行:

与之前 类似的,我们想要优化
将 和 换成 和 ,构造
按照之前类似的推导过程,有
也就是可以实现在线更新结果 .
更近一步,我们可以将除以指数和 的操作先忽略,最后再进行归一化操作,即:
最后做
Tiling#
与矩阵乘法类似,tiling 可以增加数据复用,减少搬运.因此我们可以让一个 CTA 负责 的多行,并使用 SMEM tile 来实现数据复用. 示意图如下,详细步骤可阅读代码:

Flash Attention V2 版本提出:在 tiling 的基础上,应该使用 split-Q 而不是 split-K,也就是多个 warp 应该沿 来划分, 让 的一个请求由一个 warp 负责,减少 warp 之间的通信开销.
def flashattn(batch, heads, seq_len, dim, is_causal, block_M=64, block_N=64, num_stages=1, threads=128):
scale = (1.0 / dim) ** 0.5 * 1.44269504 # log2(e)
shape = [batch, seq_len, heads, dim]
dtype = T.float16
accum_dtype = T.float32
@T.prim_func
def main(
Q: T.Tensor(shape, dtype),
K: T.Tensor(shape, dtype),
V: T.Tensor(shape, dtype),
Output: T.Tensor(shape, dtype),
):
with T.Kernel(T.ceildiv(seq_len, block_M), heads, batch, threads=threads) as (bx, by, bz):
Q_shared = T.alloc_shared([block_M, dim], dtype)
K_shared = T.alloc_shared([block_N, dim], dtype)
V_shared = T.alloc_shared([block_N, dim], dtype)
O_shared = T.alloc_shared([block_M, dim], dtype)
acc_s = T.alloc_fragment([block_M, block_N], accum_dtype)
acc_s_cast = T.alloc_fragment([block_M, block_N], dtype)
acc_o = T.alloc_fragment([block_M, dim], accum_dtype)
scores_max = T.alloc_fragment([block_M], accum_dtype)
scores_max_prev = T.alloc_fragment([block_M], accum_dtype)
scores_scale = T.alloc_fragment([block_M], accum_dtype)
scores_sum = T.alloc_fragment([block_M], accum_dtype)
exp_sum = T.alloc_fragment([block_M], accum_dtype)
T.copy(Q[bz, bx * block_M : (bx + 1) * block_M, by, :], Q_shared)
T.fill(acc_o, 0)
T.fill(exp_sum, 0)
T.fill(scores_max, -T.infinity(accum_dtype))
loop_range = (
T.min(T.ceildiv(seq_len, block_N), T.ceildiv((bx + 1) * block_M, block_N)) if is_causal else T.ceildiv(seq_len, block_N)
)
for k in T.Pipelined(loop_range, num_stages=num_stages):
T.copy(K[bz, k * block_N : (k + 1) * block_N, by, :], K_shared)
if is_causal:
for i, j in T.Parallel(block_M, block_N):
acc_s[i, j] = T.if_then_else(bx * block_M + i >= k * block_N + j, 0, -T.infinity(acc_s.dtype))
else:
for i, j in T.Parallel(block_M, block_N):
acc_s[i, j] = T.if_then_else(k * block_N + j >= seq_len, -T.infinity(acc_s.dtype), 0)
T.gemm(Q_shared, K_shared, acc_s, transpose_B=True, policy=T.GemmWarpPolicy.FullRow)
T.copy(scores_max, scores_max_prev)
T.fill(scores_max, -T.infinity(accum_dtype))
T.reduce_max(acc_s, scores_max, dim=1, clear=False)
for i in T.Parallel(block_M):
scores_max[i] = T.max(scores_max[i], scores_max_prev[i])
for i in T.Parallel(block_M):
scores_scale[i] = T.exp2(scores_max_prev[i] * scale - scores_max[i] * scale)
for i, j in T.Parallel(block_M, block_N):
acc_s[i, j] = T.exp2(acc_s[i, j] * scale - scores_max[i] * scale)
T.reduce_sum(acc_s, scores_sum, dim=1)
for i in T.Parallel(block_M):
exp_sum[i] = exp_sum[i] * scores_scale[i] + scores_sum[i]
T.copy(acc_s, acc_s_cast)
for i, j in T.Parallel(block_M, dim):
acc_o[i, j] *= scores_scale[i]
T.copy(V[bz, k * block_N : (k + 1) * block_N, by, :], V_shared)
T.gemm(acc_s_cast, V_shared, acc_o, policy=T.GemmWarpPolicy.FullRow)
for i, j in T.Parallel(block_M, dim):
acc_o[i, j] /= exp_sum[i]
T.copy(acc_o, O_shared)
T.copy(O_shared, Output[bz, bx * block_M : (bx + 1) * block_M, by, :])
return mainpython如果使用的是 GQA,只需要将 q_shape 和 kv_shape 分开,并将所有 的头有关的寻址都改为 by // group 即可.
将
scale乘以log2(e),再用exp2代替exp,可以在结果不变的前提下加快计算速度.
性能分析#
考虑单个 batch、单个 head 的非 causal 前向计算,设 ,输入和输出每个元素占 bytes.、 分别是 block_M、block_N,并记
访存数量#
朴素 Attention 分为三个步骤,令 、,并假设 的元素也占 bytes:
| 步骤 | 读取的元素数 | 写入的元素数 |
|---|---|---|
每个算子将输入读一遍、输出写一遍,softmax 在片上完成行归约,可得
其中 来自 各自的一次写入和一次读取.
再看上面的 Flash Attention 代码.每个 CTA 负责 行 ,在循环开始前读入一次,在循环结束后写回一次 .但每个 CTA 都要遍历完整的 ,所以:
| 张量 | 每个元素的访问次数 | 元素数 |
|---|---|---|
| 读 1 次 | ||
| 各读 次 | ||
| 写 1 次 | ||
| 只保留当前 tile,不读写 HBM |
因此
Flash Attention 省去了完整 的读写,同时用重复读取 来换取较小的片上工作集.增大 ,同一块 就可以服务更多 query,访存量也就更少.
例如 时,:
其中 V2 的 合计只有 1 MiB,剩下 64 MiB 都是对 的重复读取,总访存量约为朴素实现的一半.
对固定的 ,V2 的访存量随 增长.V1 论文的 IO 分析给出 ,其中 是片上存储可容纳的元素个数.
V1 与 V2 的循环顺序#
回到前面笔者疑惑的地方:将 放到外循环,究竟省了多少读写?按 V1 论文 Algorithm 1 中 在外层的调度,每读入一块 ,就需要遍历所有 ,并读写所有 :
| 张量 | V1: 在外层 | V2: 在外层 |
|---|---|---|
| 读 次 | 读 1 次 | |
| 各读 1 次 | 各读 次 | |
| 读 次、写 次 | 写 1 次 |
当 且分块数很大时,同精度矩阵的搬运量之比接近 .V2 将 的反复读写换成了 的重复读取,总访存量降到 V1 的约 .
显存占用#
对于朴素实现,如果 都分配独立缓冲区,且都采用相同 dtype,则张量占用为
如果 softmax 原地覆盖 ,只保留一份 缓冲区,占用变成 ,仍然随序列长度二次增长.
上面的 Flash Attention 前向代码只在 HBM 中保留 ,因此
随序列长度线性增长.
以单个 head、、FP16 为例,这些前向张量的显存占用为:
| 序列长度 | 朴素: 加独立的 | Flash Attention: |
|---|---|---|
| 4096 | 66 MiB | 2 MiB |
| 16384 | 1032 MiB | 8 MiB |
| 65536 | 16416 MiB | 32 MiB |
片上存储与分块大小#
增大 会减少访存,同时增加片上存储占用.代码中的四个 shared buffer 按声明大小合计需要
当 时是 32 KiB.除此之外,acc_s、acc_s_cast、acc_o 和五个行统计向量还占用 fragment 存储,其逻辑数据量为
代入同一组参数得到 41.25 KiB.这部分通常分布在线程的寄存器中,与 shared memory 分别占用各自的片上资源.
增大 会增加输出累加器和 score tile 的大小;增大 则减少循环次数,同时增大 score tile 和 缓冲区.资源占用过高会减少一个 SM 上同时驻留的 CTA,甚至导致寄存器 spill.num_stages 增大也会增加流水缓冲的需求,tile 大小需要在数据复用和并行度之间取舍.
计算量与并行度#
两次矩阵乘的主体计算量没有改变,按一次乘加计 2 FLOPs:
仅考虑矩阵乘法的 FLOPs,当 时有
tiling 提高了算术强度,减少了矩阵乘等待数据的时间;softmax 的指数、归约以及同步开销则成为进一步优化的重点.
在 RTX5060 laptop 上、batch=8, heads=64, seq_len=4096, dim=128, groups=16 下,Flash Attention V2 版本相对 Pytorch 版本的性能:
Ref: 76.74 ms
Ref: 7.16 TFlops
Tile-lang: 18.83 ms
Tile-lang: 29.19 TFlopstext